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
63269d1ba4e9f6233eac731a5107aac50afdf13b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/group_theory/eckmann_hilton.lean
6a9a6515f52e7eda7af00fd791baeb4e23f3d5e0
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,249
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau, Robert Y. Lewis -/ import algebra.group.basic /-! # Eckmann-Hilton argument The Eckmann-Hilton argument says that if a type carries two monoid structures that distribute over one another, then they are equal, and in addition commutative. The main application lies in proving that higher homotopy groups (`πₙ` for `n ≥ 2`) are commutative. ## Main declarations * `eckmann_hilton.comm_monoid`: If a type carries two unital binary operations that distribute over each other, then these operations are equal, and form a commutative monoid structure. * `eckmann_hilton.comm_group`: If a type carries a group structure that distributes over a unital binary operation, then the group is commutative. -/ universe u namespace eckmann_hilton variables {X : Type u} local notation a `<`m`>` b := m a b /-- `is_unital m e` expresses that `e : X` is a left and right unit for the binary operation `m : X → X → X`. -/ class is_unital (m : X → X → X) (e : X) : Prop := (one_mul : ∀ x : X, (e <m> x) = x) (mul_one : ∀ x : X, (x <m> e) = x) @[to_additive add_group.is_unital] lemma group.is_unital [G : group X] : is_unital (*) (1 : X) := { ..G } variables {m₁ m₂ : X → X → X} {e₁ e₂ : X} variables (h₁ : is_unital m₁ e₁) (h₂ : is_unital m₂ e₂) variables (distrib : ∀ a b c d, ((a <m₂> b) <m₁> (c <m₂> d)) = ((a <m₁> c) <m₂> (b <m₁> d))) include h₁ h₂ distrib /-- If a type carries two unital binary operations that distribute over each other, then they have the same unit elements. In fact, the two operations are the same, and give a commutative monoid structure, see `eckmann_hilton.comm_monoid`. -/ lemma one : e₁ = e₂ := by simpa only [h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] using distrib e₂ e₁ e₁ e₂ /-- If a type carries two unital binary operations that distribute over each other, then these operations are equal. In fact, they give a commutative monoid structure, see `eckmann_hilton.comm_monoid`. -/ lemma mul : (m₁ = m₂) := begin funext a b, calc m₁ a b = m₁ (m₂ a e₁) (m₂ e₁ b) : by simp only [one h₁ h₂ distrib, h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] ... = m₂ a b : by simp only [distrib, h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] end /-- If a type carries two unital binary operations that distribute over each other, then these operations are commutative. In fact, they give a commutative monoid structure, see `eckmann_hilton.comm_monoid`. -/ lemma mul_comm : is_commutative _ m₂ := ⟨λ a b, by simpa [mul h₁ h₂ distrib, h₂.one_mul, h₂.mul_one] using distrib e₂ a b e₂⟩ /-- If a type carries two unital binary operations that distribute over each other, then these operations are associative. In fact, they give a commutative monoid structure, see `eckmann_hilton.comm_monoid`. -/ lemma mul_assoc : is_associative _ m₂ := ⟨λ a b c, by simpa [mul h₁ h₂ distrib, h₂.one_mul, h₂.mul_one] using distrib a b e₂ c⟩ /-- If a type carries two unital binary operations that distribute over each other, then these operations are equal, and form a commutative monoid structure. -/ @[to_additive "If a type carries two unital binary operations that distribute over each other, then these operations are equal, and form a additive commutative monoid structure."] def comm_monoid : comm_monoid X := { mul := m₂, one := e₂, mul_comm := (mul_comm h₁ h₂ distrib).comm, mul_assoc := (mul_assoc h₁ h₂ distrib).assoc, ..h₂ } omit h₁ h₂ distrib /-- If a type carries a group structure that distributes over a unital binary operation, then the group is commutative. -/ @[to_additive "If a type carries an additive group structure that distributes over a unital binary operation, then the additive group is commutative."] def comm_group [G : group X] (distrib : ∀ a b c d, ((a * b) <m₁> (c * d)) = ((a <m₁> c) * (b <m₁> d))) : comm_group X := { mul_comm := (eckmann_hilton.comm_monoid h₁ group.is_unital distrib).mul_comm, ..G } end eckmann_hilton
7682497fde62e9bd020374c23fa6737940201563
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/infinite_sum.lean
37914fdcf2a7b059a5542b3acee57b1b5588f91e
[]
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
52,538
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.intervals import Mathlib.topology.instances.real import Mathlib.topology.algebra.module import Mathlib.data.indicator_function import Mathlib.data.equiv.encodable.lattice import Mathlib.order.filter.at_top_bot import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 u_6 namespace Mathlib /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (f : β → α) (a : α) := filter.tendsto (fun (s : finset β) => finset.sum s fun (b : β) => f b) filter.at_top (nhds a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (f : β → α) := ∃ (a : α), has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ def tsum {α : Type u_1} [add_comm_monoid α] [topological_space α] {β : Type u_2} (f : β → α) : α := dite (summable f) (fun (h : summable f) => classical.some h) fun (h : ¬summable f) => 0 -- see Note [operator precedence of big operators] theorem summable.has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} (ha : summable f) : has_sum f (tsum fun (b : β) => f b) := sorry theorem has_sum.summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} (h : has_sum f a) : summable f := Exists.intro a h /-- Constant zero function has sum `0` -/ theorem has_sum_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] : has_sum (fun (b : β) => 0) 0 := sorry theorem summable_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] : summable fun (b : β) => 0 := has_sum.summable has_sum_zero theorem tsum_eq_zero_of_not_summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} (h : ¬summable f) : (tsum fun (b : β) => f b) = 0 := sorry theorem has_sum.has_sum_of_sum_eq {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (h_eq : ∀ (u : finset γ), ∃ (v : finset β), ∀ (v' : finset β), v ⊆ v' → ∃ (u' : finset γ), u ⊆ u' ∧ (finset.sum u' fun (x : γ) => g x) = finset.sum v' fun (b : β) => f b) (hf : has_sum g a) : has_sum f a := le_trans (filter.map_at_top_finset_sum_le_of_sum_eq h_eq) hf theorem has_sum_iff_has_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (h₁ : ∀ (u : finset γ), ∃ (v : finset β), ∀ (v' : finset β), v ⊆ v' → ∃ (u' : finset γ), u ⊆ u' ∧ (finset.sum u' fun (x : γ) => g x) = finset.sum v' fun (b : β) => f b) (h₂ : ∀ (v : finset β), ∃ (u : finset γ), ∀ (u' : finset γ), u ⊆ u' → ∃ (v' : finset β), v ⊆ v' ∧ (finset.sum v' fun (b : β) => f b) = finset.sum u' fun (x : γ) => g x) : has_sum f a ↔ has_sum g a := { mp := has_sum.has_sum_of_sum_eq h₂, mpr := has_sum.has_sum_of_sum_eq h₁ } theorem function.injective.has_sum_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → β} (hg : function.injective g) (hf : ∀ (x : β), ¬x ∈ set.range g → f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := sorry theorem function.injective.summable_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {g : γ → β} (hg : function.injective g) (hf : ∀ (x : β), ¬x ∈ set.range g → f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr fun (_x : α) => function.injective.has_sum_iff hg hf theorem has_sum_subtype_iff_of_support_subset {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {s : set β} (hf : function.support f ⊆ s) : has_sum (f ∘ coe) a ↔ has_sum f a := sorry theorem has_sum_subtype_iff_indicator {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {s : set β} : has_sum (f ∘ coe) a ↔ has_sum (set.indicator s f) a := sorry @[simp] theorem has_sum_subtype_support {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} : has_sum (f ∘ coe) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset (set.subset.refl (function.support f)) theorem has_sum_fintype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [fintype β] (f : β → α) : has_sum f (finset.sum finset.univ fun (b : β) => f b) := order_top.tendsto_at_top_nhds fun (s : finset β) => finset.sum s fun (b : β) => f b protected theorem finset.has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (s : finset β) (f : β → α) : has_sum (f ∘ coe) (finset.sum s fun (b : β) => f b) := eq.mpr (id (Eq._oldrec (Eq.refl (has_sum (f ∘ coe) (finset.sum s fun (b : β) => f b))) (Eq.symm finset.sum_attach))) (has_sum_fintype (f ∘ coe)) protected theorem finset.summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (s : finset β) (f : β → α) : summable (f ∘ coe) := has_sum.summable (finset.has_sum s f) protected theorem set.finite.summable {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {s : set β} (hs : set.finite s) (f : β → α) : summable (f ∘ coe) := sorry /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ theorem has_sum_sum_of_ne_finset_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {s : finset β} (hf : ∀ (b : β), ¬b ∈ s → f b = 0) : has_sum f (finset.sum s fun (b : β) => f b) := iff.mp (has_sum_subtype_iff_of_support_subset (iff.mpr function.support_subset_iff' hf)) (finset.has_sum s f) theorem summable_of_ne_finset_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {s : finset β} (hf : ∀ (b : β), ¬b ∈ s → f b = 0) : summable f := has_sum.summable (has_sum_sum_of_ne_finset_zero hf) theorem has_sum_single {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} (b : β) (hf : ∀ (b' : β), b' ≠ b → f b' = 0) : has_sum f (f b) := sorry theorem has_sum_ite_eq {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] (b : β) (a : α) : has_sum (fun (b' : β) => ite (b' = b) a 0) a := sorry theorem equiv.has_sum_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} (e : γ ≃ β) : has_sum (f ∘ ⇑e) a ↔ has_sum f a := sorry theorem equiv.summable_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} (e : γ ≃ β) : summable (f ∘ ⇑e) ↔ summable f := exists_congr fun (a : α) => equiv.has_sum_iff e theorem summable.prod_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β × γ → α} (hf : summable f) : summable fun (p : γ × β) => f (prod.swap p) := iff.mpr (equiv.summable_iff (equiv.prod_comm γ β)) hf theorem equiv.has_sum_iff_of_support {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (e : ↥(function.support f) ≃ ↥(function.support g)) (he : ∀ (x : ↥(function.support f)), g ↑(coe_fn e x) = f ↑x) : has_sum f a ↔ has_sum g a := sorry theorem has_sum_iff_has_sum_of_ne_zero_bij {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {g : γ → α} (i : ↥(function.support g) → β) (hi : ∀ {x y : ↥(function.support g)}, i x = i y → ↑x = ↑y) (hf : function.support f ⊆ set.range i) (hfg : ∀ (x : ↥(function.support g)), f (i x) = g ↑x) : has_sum f a ↔ has_sum g a := sorry theorem equiv.summable_iff_of_support {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {g : γ → α} (e : ↥(function.support f) ≃ ↥(function.support g)) (he : ∀ (x : ↥(function.support f)), g ↑(coe_fn e x) = f ↑x) : summable f ↔ summable g := exists_congr fun (_x : α) => equiv.has_sum_iff_of_support e he protected theorem has_sum.map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous ⇑g) : has_sum (⇑g ∘ f) (coe_fn g a) := sorry protected theorem summable.map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {f : β → α} [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous ⇑g) : summable (⇑g ∘ f) := has_sum.summable (has_sum.map (summable.has_sum hf) g hg) /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ theorem has_sum.tendsto_sum_nat {α : Type u_1} [add_comm_monoid α] [topological_space α] {a : α} {f : ℕ → α} (h : has_sum f a) : filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds a) := filter.tendsto.comp h filter.tendsto_finset_range theorem has_sum.unique {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a₁ : α} {a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique theorem summable.has_sum_iff_tendsto_nat {α : Type u_1} [add_comm_monoid α] [topological_space α] [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds a) := sorry theorem equiv.summable_iff_of_has_sum_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] {α' : Type u_4} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a : α'}, has_sum f (coe_fn e a) ↔ has_sum g a) : summable f ↔ summable g := sorry theorem has_sum.add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {g : β → α} {a : α} {b : α} [has_continuous_add α] (hf : has_sum f a) (hg : has_sum g b) : has_sum (fun (b : β) => f b + g b) (a + b) := sorry theorem summable.add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {g : β → α} [has_continuous_add α] (hf : summable f) (hg : summable g) : summable fun (b : β) => f b + g b := has_sum.summable (has_sum.add (summable.has_sum hf) (summable.has_sum hg)) theorem has_sum_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [has_continuous_add α] {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀ (i : γ), i ∈ s → has_sum (f i) (a i)) → has_sum (fun (b : β) => finset.sum s fun (i : γ) => f i b) (finset.sum s fun (i : γ) => a i) := sorry theorem summable_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [has_continuous_add α] {f : γ → β → α} {s : finset γ} (hf : ∀ (i : γ), i ∈ s → summable (f i)) : summable fun (b : β) => finset.sum s fun (i : γ) => f i b := has_sum.summable (has_sum_sum fun (i : γ) (hi : i ∈ s) => summable.has_sum (hf i hi)) theorem has_sum.add_compl {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {b : α} [has_continuous_add α] {s : set β} (ha : has_sum (f ∘ coe) a) (hb : has_sum (f ∘ coe) b) : has_sum f (a + b) := sorry theorem summable.add_compl {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} [has_continuous_add α] {s : set β} (hs : summable (f ∘ coe)) (hsc : summable (f ∘ coe)) : summable f := has_sum.summable (has_sum.add_compl (summable.has_sum hs) (summable.has_sum hsc)) theorem has_sum.compl_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} {b : α} [has_continuous_add α] {s : set β} (ha : has_sum (f ∘ coe) a) (hb : has_sum (f ∘ coe) b) : has_sum f (a + b) := sorry theorem summable.compl_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] {f : β → α} [has_continuous_add α] {s : set β} (hs : summable (f ∘ coe)) (hsc : summable (f ∘ coe)) : summable f := has_sum.summable (has_sum.compl_add (summable.has_sum hs) (summable.has_sum hsc)) theorem has_sum.sigma {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀ (b : β), has_sum (fun (c : γ b) => f (sigma.mk b c)) (g b)) : has_sum g a := sorry /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ theorem has_sum.prod_fiberwise {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀ (b : β), has_sum (fun (c : γ) => f (b, c)) (g b)) : has_sum g a := has_sum.sigma (iff.mpr (equiv.has_sum_iff (equiv.sigma_equiv_prod β γ)) ha) hf theorem summable.sigma' {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) (hf : ∀ (b : β), summable fun (c : γ b) => f (sigma.mk b c)) : summable fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := has_sum.summable (has_sum.sigma (summable.has_sum ha) fun (b : β) => summable.has_sum (hf b)) theorem has_sum.sigma_of_has_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀ (b : β), has_sum (fun (c : γ b) => f (sigma.mk b c)) (g b)) (hf' : summable f) : has_sum f a := sorry theorem has_sum.tsum_eq {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {a : α} (ha : has_sum f a) : (tsum fun (b : β) => f b) = a := has_sum.unique (summable.has_sum (Exists.intro a ha)) ha theorem summable.has_sum_iff {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {a : α} (h : summable f) : has_sum f a ↔ (tsum fun (b : β) => f b) = a := { mp := has_sum.tsum_eq, mpr := fun (eq : (tsum fun (b : β) => f b) = a) => eq ▸ summable.has_sum h } @[simp] theorem tsum_zero {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] : (tsum fun (b : β) => 0) = 0 := has_sum.tsum_eq has_sum_zero theorem tsum_eq_sum {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {s : finset β} (hf : ∀ (b : β), ¬b ∈ s → f b = 0) : (tsum fun (b : β) => f b) = finset.sum s fun (b : β) => f b := has_sum.tsum_eq (has_sum_sum_of_ne_finset_zero hf) theorem tsum_fintype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] [fintype β] (f : β → α) : (tsum fun (b : β) => f b) = finset.sum finset.univ fun (b : β) => f b := has_sum.tsum_eq (has_sum_fintype f) @[simp] theorem finset.tsum_subtype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (s : finset β) (f : β → α) : (tsum fun (x : Subtype fun (x : β) => x ∈ s) => f ↑x) = finset.sum s fun (x : β) => f x := has_sum.tsum_eq (finset.has_sum s f) @[simp] theorem finset.tsum_subtype' {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (s : finset β) (f : β → α) : (tsum fun (x : ↥↑s) => f ↑x) = finset.sum s fun (x : β) => f x := finset.tsum_subtype s f theorem tsum_eq_single {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} (b : β) (hf : ∀ (b' : β), b' ≠ b → f b' = 0) : (tsum fun (b : β) => f b) = f b := has_sum.tsum_eq (has_sum_single b hf) @[simp] theorem tsum_ite_eq {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (b : β) (a : α) : (tsum fun (b' : β) => ite (b' = b) a 0) = a := has_sum.tsum_eq (has_sum_ite_eq b a) theorem equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {α' : Type u_4} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : coe_fn e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a : α'}, has_sum f (coe_fn e a) ↔ has_sum g a) : (tsum fun (b : β) => f b) = coe_fn e (tsum fun (c : γ) => g c) := sorry theorem tsum_eq_tsum_of_has_sum_iff_has_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : γ → α} (h : ∀ {a : α}, has_sum f a ↔ has_sum g a) : (tsum fun (b : β) => f b) = tsum fun (c : γ) => g c := equiv.tsum_eq_tsum_of_has_sum_iff_has_sum (equiv.refl α) rfl h theorem equiv.tsum_eq {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] (j : γ ≃ β) (f : β → α) : (tsum fun (c : γ) => f (coe_fn j c)) = tsum fun (b : β) => f b := tsum_eq_tsum_of_has_sum_iff_has_sum fun (a : α) => equiv.has_sum_iff j theorem equiv.tsum_eq_tsum_of_support {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : γ → α} (e : ↥(function.support f) ≃ ↥(function.support g)) (he : ∀ (x : ↥(function.support f)), g ↑(coe_fn e x) = f ↑x) : (tsum fun (x : β) => f x) = tsum fun (y : γ) => g y := tsum_eq_tsum_of_has_sum_iff_has_sum fun (_x : α) => equiv.has_sum_iff_of_support e he theorem tsum_eq_tsum_of_ne_zero_bij {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : γ → α} (i : ↥(function.support g) → β) (hi : ∀ {x y : ↥(function.support g)}, i x = i y → ↑x = ↑y) (hf : function.support f ⊆ set.range i) (hfg : ∀ (x : ↥(function.support g)), f (i x) = g ↑x) : (tsum fun (x : β) => f x) = tsum fun (y : γ) => g y := tsum_eq_tsum_of_has_sum_iff_has_sum fun (_x : α) => has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg theorem tsum_subtype {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] (s : set β) (f : β → α) : (tsum fun (x : ↥s) => f ↑x) = tsum fun (x : β) => set.indicator s f x := tsum_eq_tsum_of_has_sum_iff_has_sum fun (_x : α) => has_sum_subtype_iff_indicator theorem tsum_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] {f : β → α} {g : β → α} [has_continuous_add α] (hf : summable f) (hg : summable g) : (tsum fun (b : β) => f b + g b) = (tsum fun (b : β) => f b) + tsum fun (b : β) => g b := has_sum.tsum_eq (has_sum.add (summable.has_sum hf) (summable.has_sum hg)) theorem tsum_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] {f : γ → β → α} {s : finset γ} (hf : ∀ (i : γ), i ∈ s → summable (f i)) : (tsum fun (b : β) => finset.sum s fun (i : γ) => f i b) = finset.sum s fun (i : γ) => tsum fun (b : β) => f i b := has_sum.tsum_eq (has_sum_sum fun (i : γ) (hi : i ∈ s) => summable.has_sum (hf i hi)) theorem tsum_sigma' {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (h₁ : ∀ (b : β), summable fun (c : γ b) => f (sigma.mk b c)) (h₂ : summable f) : (tsum fun (p : sigma fun (b : β) => γ b) => f p) = tsum fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := Eq.symm (has_sum.tsum_eq (has_sum.sigma (summable.has_sum h₂) fun (b : β) => summable.has_sum (h₁ b))) theorem tsum_prod' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀ (b : β), summable fun (c : γ) => f (b, c)) : (tsum fun (p : β × γ) => f p) = tsum fun (b : β) => tsum fun (c : γ) => f (b, c) := Eq.symm (has_sum.tsum_eq (has_sum.prod_fiberwise (summable.has_sum h) fun (b : β) => summable.has_sum (h₁ b))) theorem tsum_comm' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [has_continuous_add α] [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀ (b : β), summable (f b)) (h₂ : ∀ (c : γ), summable fun (b : β) => f b c) : (tsum fun (c : γ) => tsum fun (b : β) => f b c) = tsum fun (b : β) => tsum fun (c : γ) => f b c := sorry /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [encodable γ] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : (tsum fun (i : ℕ) => m (supr fun (b : γ) => supr fun (H : b ∈ encodable.decode2 γ i) => s b)) = tsum fun (b : γ) => m (s b) := sorry /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [encodable γ] (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : (tsum fun (i : ℕ) => m (set.Union fun (b : γ) => set.Union fun (H : b ∈ encodable.decode2 γ i) => s b)) = tsum fun (b : γ) => m (s b) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_monoid α] [topological_space α] [t2_space α] [encodable γ] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀ (s : ℕ → β), R (m (supr fun (i : ℕ) => s i)) (tsum fun (i : ℕ) => m (s i))) (s : γ → β) : R (m (supr fun (b : γ) => s b)) (tsum fun (b : γ) => m (s b)) := sorry /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum {α : Type u_1} {β : Type u_2} {δ : Type u_4} [add_comm_monoid α] [topological_space α] [t2_space α] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀ (s : ℕ → β), R (m (supr fun (i : ℕ) => s i)) (tsum fun (i : ℕ) => m (s i))) (s : δ → β) (t : finset δ) : R (m (supr fun (d : δ) => supr fun (H : d ∈ t) => s d)) (finset.sum t fun (d : δ) => m (s d)) := sorry /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add {α : Type u_1} {β : Type u_2} [add_comm_monoid α] [topological_space α] [t2_space α] [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀ (s : ℕ → β), R (m (supr fun (i : ℕ) => s i)) (tsum fun (i : ℕ) => m (s i))) (s₁ : β) (s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := sorry theorem pi.has_sum {α : Type u_1} {ι : Type u_5} {π : α → Type u_6} [(x : α) → add_comm_monoid (π x)] [(x : α) → topological_space (π x)] {f : ι → (x : α) → π x} {g : (x : α) → π x} : has_sum f g ↔ ∀ (x : α), has_sum (fun (i : ι) => f i x) (g x) := sorry theorem pi.summable {α : Type u_1} {ι : Type u_5} {π : α → Type u_6} [(x : α) → add_comm_monoid (π x)] [(x : α) → topological_space (π x)] {f : ι → (x : α) → π x} : summable f ↔ ∀ (x : α), summable fun (i : ι) => f i x := sorry theorem tsum_apply {α : Type u_1} {ι : Type u_5} {π : α → Type u_6} [(x : α) → add_comm_monoid (π x)] [(x : α) → topological_space (π x)] [∀ (x : α), t2_space (π x)] {f : ι → (x : α) → π x} {x : α} (hf : summable f) : tsum (fun (i : ι) => f i) x = tsum fun (i : ι) => f i x := Eq.symm (has_sum.tsum_eq (iff.mp pi.has_sum (summable.has_sum hf) x)) -- `by simpa using` speeds up elaboration. Why? theorem has_sum.neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a : α} (h : has_sum f a) : has_sum (fun (b : β) => -f b) (-a) := eq.mpr (id (Eq.refl (has_sum (fun (b : β) => -f b) (-a)))) (eq.mp (Eq.refl (has_sum (⇑(-add_monoid_hom.id α) ∘ f) (coe_fn (-add_monoid_hom.id α) a))) (has_sum.map h (-add_monoid_hom.id α) continuous_neg)) theorem summable.neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} (hf : summable f) : summable fun (b : β) => -f b := has_sum.summable (has_sum.neg (summable.has_sum hf)) theorem summable.of_neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} (hf : summable fun (b : β) => -f b) : summable f := sorry theorem summable_neg_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} : (summable fun (b : β) => -f b) ↔ summable f := { mp := summable.of_neg, mpr := summable.neg } theorem has_sum.sub {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {g : β → α} {a₁ : α} {a₂ : α} (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (fun (b : β) => f b - g b) (a₁ - a₂) := sorry theorem summable.sub {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {g : β → α} (hf : summable f) (hg : summable g) : summable fun (b : β) => f b - g b := has_sum.summable (has_sum.sub (summable.has_sum hf) (summable.has_sum hg)) theorem has_sum.has_sum_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a₁ : α} {a₂ : α} {s : set β} (hf : has_sum (f ∘ coe) a₁) : has_sum (f ∘ coe) a₂ ↔ has_sum f (a₁ + a₂) := sorry theorem has_sum.has_sum_iff_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a₁ : α} {a₂ : α} {s : set β} (hf : has_sum (f ∘ coe) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe) (a₂ - a₁) := sorry theorem summable.summable_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {s : set β} (hf : summable (f ∘ coe)) : summable (f ∘ coe) ↔ summable f := sorry protected theorem finset.has_sum_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a : α} (s : finset β) : has_sum (fun (x : Subtype fun (x : β) => ¬x ∈ s) => f ↑x) a ↔ has_sum f (a + finset.sum s fun (i : β) => f i) := sorry protected theorem finset.has_sum_iff_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {a : α} (s : finset β) : has_sum f a ↔ has_sum (fun (x : Subtype fun (x : β) => ¬x ∈ s) => f ↑x) (a - finset.sum s fun (i : β) => f i) := has_sum.has_sum_iff_compl (finset.has_sum s f) protected theorem finset.summable_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} (s : finset β) : (summable fun (x : Subtype fun (x : β) => ¬x ∈ s) => f ↑x) ↔ summable f := summable.summable_compl_iff (finset.summable s f) theorem set.finite.summable_compl_iff {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {s : set β} (hs : set.finite s) : summable (f ∘ coe) ↔ summable f := summable.summable_compl_iff (set.finite.summable hs f) theorem tsum_neg {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} [t2_space α] (hf : summable f) : (tsum fun (b : β) => -f b) = -tsum fun (b : β) => f b := has_sum.tsum_eq (has_sum.neg (summable.has_sum hf)) theorem tsum_sub {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} {g : β → α} [t2_space α] (hf : summable f) (hg : summable g) : (tsum fun (b : β) => f b - g b) = (tsum fun (b : β) => f b) - tsum fun (b : β) => g b := has_sum.tsum_eq (has_sum.sub (summable.has_sum hf) (summable.has_sum hg)) theorem tsum_add_tsum_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} [t2_space α] {s : set β} (hs : summable (f ∘ coe)) (hsc : summable (f ∘ coe)) : ((tsum fun (x : ↥s) => f ↑x) + tsum fun (x : ↥(sᶜ)) => f ↑x) = tsum fun (x : β) => f x := Eq.symm (has_sum.tsum_eq (has_sum.add_compl (summable.has_sum hs) (summable.has_sum hsc))) theorem sum_add_tsum_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [topological_space α] [topological_add_group α] {f : β → α} [t2_space α] {s : finset β} (hf : summable f) : ((finset.sum s fun (x : β) => f x) + tsum fun (x : ↥(↑sᶜ)) => f ↑x) = tsum fun (x : β) => f x := Eq.symm (has_sum.tsum_eq (has_sum.add_compl (finset.has_sum s f) (summable.has_sum (iff.mpr (finset.summable_compl_iff s) hf)))) /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ theorem has_sum_nat_add_iff {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] {f : ℕ → α} (k : ℕ) {a : α} : has_sum (fun (n : ℕ) => f (n + k)) a ↔ has_sum f (a + finset.sum (finset.range k) fun (i : ℕ) => f i) := sorry theorem summable_nat_add_iff {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] {f : ℕ → α} (k : ℕ) : (summable fun (n : ℕ) => f (n + k)) ↔ summable f := iff.symm (equiv.summable_iff_of_has_sum_iff (equiv.add_right (finset.sum (finset.range k) fun (i : ℕ) => f i)) fun (a : α) => iff.symm (has_sum_nat_add_iff k)) theorem has_sum_nat_add_iff' {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] {f : ℕ → α} (k : ℕ) {a : α} : has_sum (fun (n : ℕ) => f (n + k)) (a - finset.sum (finset.range k) fun (i : ℕ) => f i) ↔ has_sum f a := sorry theorem sum_add_tsum_nat_add {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : ((finset.sum (finset.range k) fun (i : ℕ) => f i) + tsum fun (i : ℕ) => f (i + k)) = tsum fun (i : ℕ) => f i := sorry theorem tsum_eq_zero_add {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] [t2_space α] {f : ℕ → α} (hf : summable f) : (tsum fun (b : ℕ) => f b) = f 0 + tsum fun (b : ℕ) => f (b + 1) := sorry /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ theorem tendsto_sum_nat_add {α : Type u_1} [add_comm_group α] [topological_space α] [topological_add_group α] [t2_space α] (f : ℕ → α) : filter.tendsto (fun (i : ℕ) => tsum fun (k : ℕ) => f (k + i)) filter.at_top (nhds 0) := sorry theorem has_sum.mul_left {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} (a₂ : α) (h : has_sum f a₁) : has_sum (fun (b : β) => a₂ * f b) (a₂ * a₁) := eq.mpr (id (Eq.refl (has_sum (fun (b : β) => a₂ * f b) (a₂ * a₁)))) (eq.mp (Eq.refl (has_sum (⇑(add_monoid_hom.mul_left a₂) ∘ f) (coe_fn (add_monoid_hom.mul_left a₂) a₁))) (has_sum.map h (add_monoid_hom.mul_left a₂) (continuous.mul continuous_const continuous_id))) theorem has_sum.mul_right {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} (a₂ : α) (hf : has_sum f a₁) : has_sum (fun (b : β) => f b * a₂) (a₁ * a₂) := eq.mpr (id (Eq.refl (has_sum (fun (b : β) => f b * a₂) (a₁ * a₂)))) (eq.mp (Eq.refl (has_sum (⇑(add_monoid_hom.mul_right a₂) ∘ f) (coe_fn (add_monoid_hom.mul_right a₂) a₁))) (has_sum.map hf (add_monoid_hom.mul_right a₂) (continuous.mul continuous_id continuous_const))) theorem summable.mul_left {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} (a : α) (hf : summable f) : summable fun (b : β) => a * f b := has_sum.summable (has_sum.mul_left a (summable.has_sum hf)) theorem summable.mul_right {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} (a : α) (hf : summable f) : summable fun (b : β) => f b * a := has_sum.summable (has_sum.mul_right a (summable.has_sum hf)) theorem summable.tsum_mul_left {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} [t2_space α] (a : α) (hf : summable f) : (tsum fun (b : β) => a * f b) = a * tsum fun (b : β) => f b := has_sum.tsum_eq (has_sum.mul_left a (summable.has_sum hf)) theorem summable.tsum_mul_right {α : Type u_1} {β : Type u_2} [semiring α] [topological_space α] [topological_semiring α] {f : β → α} [t2_space α] (a : α) (hf : summable f) : (tsum fun (b : β) => f b * a) = (tsum fun (b : β) => f b) * a := has_sum.tsum_eq (has_sum.mul_right a (summable.has_sum hf)) theorem has_sum.smul {α : Type u_1} {β : Type u_2} {R : Type u_5} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} {a : α} {r : R} (hf : has_sum f a) : has_sum (fun (z : β) => r • f z) (r • a) := has_sum.map hf (const_smul_hom α r) (continuous.smul continuous_const continuous_id) theorem summable.smul {α : Type u_1} {β : Type u_2} {R : Type u_5} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} {r : R} (hf : summable f) : summable fun (z : β) => r • f z := has_sum.summable (has_sum.smul (summable.has_sum hf)) theorem tsum_smul {α : Type u_1} {β : Type u_2} {R : Type u_5} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} [t2_space α] {r : R} (hf : summable f) : (tsum fun (z : β) => r • f z) = r • tsum fun (z : β) => f z := has_sum.tsum_eq (has_sum.smul (summable.has_sum hf)) theorem has_sum.div_const {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} (h : has_sum f a) (b : α) : has_sum (fun (x : β) => f x / b) (a / b) := sorry theorem has_sum_mul_left_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} {a₂ : α} (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (fun (b : β) => a₂ * f b) (a₂ * a₁) := sorry theorem has_sum_mul_right_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a₁ : α} {a₂ : α} (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (fun (b : β) => f b * a₂) (a₁ * a₂) := sorry theorem summable_mul_left_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} (h : a ≠ 0) : summable f ↔ summable fun (b : β) => a * f b := sorry theorem summable_mul_right_iff {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} (h : a ≠ 0) : summable f ↔ summable fun (b : β) => f b * a := sorry theorem tsum_mul_left {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} [t2_space α] : (tsum fun (x : β) => a * f x) = a * tsum fun (x : β) => f x := sorry theorem tsum_mul_right {α : Type u_1} {β : Type u_2} [division_ring α] [topological_space α] [topological_semiring α] {f : β → α} {a : α} [t2_space α] : (tsum fun (x : β) => f x * a) = (tsum fun (x : β) => f x) * a := sorry theorem has_sum_le {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {g : β → α} {a₁ : α} {a₂ : α} (h : ∀ (b : β), f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg fun (s : finset β) => finset.sum_le_sum fun (b : β) (_x : b ∈ s) => h b theorem has_sum_le_inj {α : Type u_1} {β : Type u_2} {γ : Type u_3} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {a₁ : α} {a₂ : α} {g : γ → α} (i : β → γ) (hi : function.injective i) (hs : ∀ (c : γ), ¬c ∈ set.range i → 0 ≤ g c) (h : ∀ (b : β), f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := sorry theorem tsum_le_tsum_of_inj {α : Type u_1} {β : Type u_2} {γ : Type u_3} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {g : γ → α} (i : β → γ) (hi : function.injective i) (hs : ∀ (c : γ), ¬c ∈ set.range i → 0 ≤ g c) (h : ∀ (b : β), f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h (summable.has_sum hf) (summable.has_sum hg) theorem sum_le_has_sum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {a : α} {f : β → α} (s : finset β) (hs : ∀ (b : β), ¬b ∈ s → 0 ≤ f b) (hf : has_sum f a) : (finset.sum s fun (b : β) => f b) ≤ a := sorry theorem le_has_sum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {a : α} (hf : has_sum f a) (b : β) (hb : ∀ (b' : β), b' ≠ b → 0 ≤ f b') : f b ≤ a := sorry theorem sum_le_tsum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (s : finset β) (hs : ∀ (b : β), ¬b ∈ s → 0 ≤ f b) (hf : summable f) : (finset.sum s fun (b : β) => f b) ≤ tsum f := sum_le_has_sum s hs (summable.has_sum hf) theorem le_tsum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (hf : summable f) (b : β) (hb : ∀ (b' : β), b' ≠ b → 0 ≤ f b') : f b ≤ tsum fun (b : β) => f b := le_has_sum (summable.has_sum hf) b hb theorem tsum_le_tsum {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {g : β → α} (h : ∀ (b : β), f b ≤ g b) (hf : summable f) (hg : summable g) : (tsum fun (b : β) => f b) ≤ tsum fun (b : β) => g b := has_sum_le h (summable.has_sum hf) (summable.has_sum hg) theorem has_sum.nonneg {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {g : β → α} {a : α} (h : ∀ (b : β), 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha theorem has_sum.nonpos {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {g : β → α} {a : α} (h : ∀ (b : β), g b ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero theorem tsum_nonneg {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {g : β → α} (h : ∀ (b : β), 0 ≤ g b) : 0 ≤ tsum fun (b : β) => g b := sorry theorem tsum_nonpos {α : Type u_1} {β : Type u_2} [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (h : ∀ (b : β), f b ≤ 0) : (tsum fun (b : β) => f b) ≤ 0 := sorry theorem le_has_sum' {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} {a : α} (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b fun (_x : β) (_x_1 : _x ≠ b) => zero_le (f _x) theorem le_tsum' {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (hf : summable f) (b : β) : f b ≤ tsum fun (b : β) => f b := le_tsum hf b fun (_x : β) (_x_1 : _x ≠ b) => zero_le (f _x) theorem has_sum_zero_iff {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} : has_sum f 0 ↔ ∀ (x : β), f x = 0 := sorry theorem tsum_eq_zero_iff {α : Type u_1} {β : Type u_2} [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : β → α} (hf : summable f) : (tsum fun (i : β) => f i) = 0 ↔ ∀ (x : β), f x = 0 := sorry theorem summable_iff_cauchy_seq_finset {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [complete_space α] {f : β → α} : summable f ↔ cauchy_seq fun (s : finset β) => finset.sum s fun (b : β) => f b := iff.symm cauchy_map_iff_exists_tendsto theorem cauchy_seq_finset_iff_vanishing {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} : (cauchy_seq fun (s : finset β) => finset.sum s fun (b : β) => f b) ↔ ∀ (e : set α), e ∈ nhds 0 → ∃ (s : finset β), ∀ (t : finset β), disjoint t s → (finset.sum t fun (b : β) => f b) ∈ e := sorry theorem summable_iff_vanishing {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] : summable f ↔ ∀ (e : set α), e ∈ nhds 0 → ∃ (s : finset β), ∀ (t : finset β), disjoint t s → (finset.sum t fun (b : β) => f b) ∈ e := sorry /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ theorem summable.summable_of_eq_zero_or_self {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} {g : β → α} [complete_space α] (hf : summable f) (h : ∀ (b : β), g b = 0 ∨ g b = f b) : summable g := sorry protected theorem summable.indicator {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] (hf : summable f) (s : set β) : summable (set.indicator s f) := summable.summable_of_eq_zero_or_self hf (set.indicator_eq_zero_or_self s f) theorem summable.comp_injective {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] {i : γ → β} (hf : summable f) (hi : function.injective i) : summable (f ∘ i) := sorry theorem summable.subtype {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] (hf : summable f) (s : set β) : summable (f ∘ coe) := summable.comp_injective hf subtype.coe_injective theorem summable_subtype_and_compl {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] {f : β → α} [complete_space α] {s : set β} : ((summable fun (x : ↥s) => f ↑x) ∧ summable fun (x : ↥(sᶜ)) => f ↑x) ↔ summable f := { mp := iff.mpr and_imp summable.add_compl, mpr := fun (h : summable f) => { left := summable.subtype h s, right := summable.subtype h (sᶜ) } } theorem summable.sigma_factor {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) (b : β) : summable fun (c : γ b) => f (sigma.mk b c) := summable.comp_injective ha sigma_mk_injective theorem summable.sigma {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) : summable fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := summable.sigma' ha fun (b : β) => summable.sigma_factor ha b theorem summable.prod_factor {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] {f : β × γ → α} (h : summable f) (b : β) : summable fun (c : γ) => f (b, c) := summable.comp_injective h fun (c₁ c₂ : γ) (h : (fun (c : γ) => (b, c)) c₁ = (fun (c : γ) => (b, c)) c₂) => and.right (iff.mp prod.ext_iff h) theorem tsum_sigma {α : Type u_1} {β : Type u_2} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {γ : β → Type u_3} {f : (sigma fun (b : β) => γ b) → α} (ha : summable f) : (tsum fun (p : sigma fun (b : β) => γ b) => f p) = tsum fun (b : β) => tsum fun (c : γ b) => f (sigma.mk b c) := tsum_sigma' (fun (b : β) => summable.sigma_factor ha b) ha theorem tsum_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {f : β × γ → α} (h : summable f) : (tsum fun (p : β × γ) => f p) = tsum fun (b : β) => tsum fun (c : γ) => f (b, c) := tsum_prod' h (summable.prod_factor h) theorem tsum_comm {α : Type u_1} {β : Type u_2} {γ : Type u_3} [add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : (tsum fun (c : γ) => tsum fun (b : β) => f b c) = tsum fun (b : β) => tsum fun (c : γ) => f b c := tsum_comm' h (summable.prod_factor h) (summable.prod_factor (summable.prod_symm h)) theorem summable.vanishing {α : Type u_1} {G : Type u_5} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} (hf : summable f) {e : set G} (he : e ∈ nhds 0) : ∃ (s : finset α), ∀ (t : finset α), disjoint t s → (finset.sum t fun (k : α) => f k) ∈ e := sorry /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ theorem summable.tendsto_cofinite_zero {α : Type u_1} {G : Type u_5} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} (hf : summable f) : filter.tendsto f filter.cofinite (nhds 0) := sorry theorem summable_abs_iff {α : Type u_1} {β : Type u_2} [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : (summable fun (x : α) => abs (f x)) ↔ summable f := sorry theorem summable.of_abs {α : Type u_1} {β : Type u_2} [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : (summable fun (x : α) => abs (f x)) → summable f := iff.mp summable_abs_iff /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ theorem cauchy_seq_of_edist_le_of_summable {α : Type u_1} [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal) (hf : ∀ (n : ℕ), edist (f n) (f (Nat.succ n)) ≤ ↑(d n)) (hd : summable d) : cauchy_seq f := sorry /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ theorem cauchy_seq_of_dist_le_of_summable {α : Type u_1} [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ (n : ℕ), dist (f n) (f (Nat.succ n)) ≤ d n) (hd : summable d) : cauchy_seq f := sorry theorem cauchy_seq_of_summable_dist {α : Type u_1} [metric_space α] {f : ℕ → α} (h : summable fun (n : ℕ) => dist (f n) (f (Nat.succ n))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable (fun (n : ℕ) => dist (f n) (f (Nat.succ n))) (fun (_x : ℕ) => le_refl (dist (f _x) (f (Nat.succ _x)))) h theorem dist_le_tsum_of_dist_le_of_tendsto {α : Type u_1} [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ (n : ℕ), dist (f n) (f (Nat.succ n)) ≤ d n) (hd : summable d) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) (n : ℕ) : dist (f n) a ≤ tsum fun (m : ℕ) => d (n + m) := sorry theorem dist_le_tsum_of_dist_le_of_tendsto₀ {α : Type u_1} [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ (n : ℕ), dist (f n) (f (Nat.succ n)) ≤ d n) (hd : summable d) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) : dist (f 0) a ≤ tsum d := sorry theorem dist_le_tsum_dist_of_tendsto {α : Type u_1} [metric_space α] {f : ℕ → α} (h : summable fun (n : ℕ) => dist (f n) (f (Nat.succ n))) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) (n : ℕ) : dist (f n) a ≤ tsum fun (m : ℕ) => dist (f (n + m)) (f (Nat.succ (n + m))) := (fun (this : dist (f n) a ≤ tsum fun (m : ℕ) => (fun (n : ℕ) => dist (f n) (f (Nat.succ n))) (n + m)) => this) (dist_le_tsum_of_dist_le_of_tendsto (fun (n : ℕ) => dist (f n) (f (Nat.succ n))) (fun (_x : ℕ) => le_refl (dist (f _x) (f (Nat.succ _x)))) h ha n) theorem dist_le_tsum_dist_of_tendsto₀ {α : Type u_1} [metric_space α] {f : ℕ → α} (h : summable fun (n : ℕ) => dist (f n) (f (Nat.succ n))) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) : dist (f 0) a ≤ tsum fun (n : ℕ) => dist (f n) (f (Nat.succ n)) := sorry
4b2aa9c9c98f9ed828053783f3f10a46b6731c73
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/order/ring.lean
3f5ec798f04983d6d4c9e64b6285790e3e66b66e
[ "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
77,415
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.char_zero.defs import algebra.order.group import algebra.order.monoid_lemmas_zero_lt import algebra.order.sub import algebra.hom.ring import data.set.intervals.basic /-! # Ordered rings and semirings This file develops the basics of ordered (semi)rings. Each typeclass here comprises * an algebraic class (`semiring`, `comm_semiring`, `ring`, `comm_ring`) * an order class (`partial_order`, `linear_order`) * assumptions on how both interact ((strict) monotonicity, canonicity) For short, * "`+` respects `≤`" means "monotonicity of addition" * "`*` respects `<`" means "strict monotonicity of multiplication by a positive number". ## Typeclasses * `ordered_semiring`: Semiring with a partial order such that `+` respects `≤` and `*` respects `<`. * `ordered_comm_semiring`: Commutative semiring with a partial order such that `+` respects `≤` and `*` respects `<`. * `ordered_ring`: Ring with a partial order such that `+` respects `≤` and `*` respects `<`. * `ordered_comm_ring`: Commutative ring with a partial order such that `+` respects `≤` and `*` respects `<`. * `linear_ordered_semiring`: Semiring with a linear order such that `+` respects `≤` and `*` respects `<`. * `linear_ordered_ring`: Ring with a linear order such that `+` respects `≤` and `*` respects `<`. * `linear_ordered_comm_ring`: Commutative ring with a linear order such that `+` respects `≤` and `*` respects `<`. * `canonically_ordered_comm_semiring`: Commutative semiring with a partial order such that `+` respects `≤`, `*` respects `<`, and `a ≤ b ↔ ∃ c, b = a + c`. and some typeclasses to define ordered rings by specifying their nonegative elements: * `nonneg_ring`: To define `ordered_ring`s. * `linear_nonneg_ring`: To define `linear_ordered_ring`s. ## Hierarchy The hardest part of proving order lemmas might be to figure out the correct generality and its corresponding typeclass. Here's an attempt at demystifying it. For each typeclass, we list its immediate predecessors and what conditions are added to each of them. * `ordered_semiring` - `ordered_cancel_add_comm_monoid` & multiplication & `*` respects `<` - `semiring` & partial order structure & `+` respects `≤` & `*` respects `<` * `ordered_comm_semiring` - `ordered_semiring` & commutativity of multiplication - `comm_semiring` & partial order structure & `+` respects `≤` & `*` respects `<` * `ordered_ring` - `ordered_semiring` & additive inverses - `ordered_add_comm_group` & multiplication & `*` respects `<` - `ring` & partial order structure & `+` respects `≤` & `*` respects `<` * `ordered_comm_ring` - `ordered_ring` & commutativity of multiplication - `ordered_comm_semiring` & additive inverses - `comm_ring` & partial order structure & `+` respects `≤` & `*` respects `<` * `linear_ordered_semiring` - `ordered_semiring` & totality of the order & nontriviality - `linear_ordered_add_comm_monoid` & multiplication & nontriviality & `*` respects `<` * `linear_ordered_ring` - `ordered_ring` & totality of the order & nontriviality - `linear_ordered_semiring` & additive inverses - `linear_ordered_add_comm_group` & multiplication & `*` respects `<` - `domain` & linear order structure * `linear_ordered_comm_ring` - `ordered_comm_ring` & totality of the order & nontriviality - `linear_ordered_ring` & commutativity of multiplication - `is_domain` & linear order structure * `canonically_ordered_comm_semiring` - `canonically_ordered_add_monoid` & multiplication & `*` respects `<` & no zero divisors - `comm_semiring` & `a ≤ b ↔ ∃ c, b = a + c` & no zero divisors ## TODO We're still missing some typeclasses, like * `linear_ordered_comm_semiring` * `canonically_ordered_semiring` They have yet to come up in practice. -/ set_option old_structure_cmd true universe u variable {α : Type u} namespace order_dual /-! Note that `order_dual` does not satisfy any of the ordered ring typeclasses due to the `zero_le_one` field. -/ instance [h : distrib α] : distrib αᵒᵈ := h instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg αᵒᵈ := h instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵒᵈ := h instance [h : non_unital_semiring α] : non_unital_semiring αᵒᵈ := h instance [h : non_assoc_semiring α] : non_assoc_semiring αᵒᵈ := h instance [h : semiring α] : semiring αᵒᵈ := h instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring αᵒᵈ := h instance [h : comm_semiring α] : comm_semiring αᵒᵈ := h instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵒᵈ := h instance [h : non_unital_ring α] : non_unital_ring αᵒᵈ := h instance [h : non_assoc_ring α] : non_assoc_ring αᵒᵈ := h instance [h : ring α] : ring αᵒᵈ := h instance [h : non_unital_comm_ring α] : non_unital_comm_ring αᵒᵈ := h instance [h : comm_ring α] : comm_ring αᵒᵈ := h end order_dual lemma add_one_le_two_mul [has_le α] [semiring α] [covariant_class α α (+) (≤)] {a : α} (a1 : 1 ≤ a) : a + 1 ≤ 2 * a := calc a + 1 ≤ a + a : add_le_add_left a1 a ... = 2 * a : (two_mul _).symm /-- An `ordered_semiring α` is a semiring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (zero_le_one : (0 : α) ≤ 1) (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ @[priority 100] -- see Note [lower instance priority] instance ordered_semiring.zero_le_one_class : zero_le_one_class α := { ..‹ordered_semiring α› } @[priority 200] -- see Note [lower instance priority] instance ordered_semiring.pos_mul_strict_mono : zero_lt.pos_mul_strict_mono α := ⟨λ x a b h, mul_lt_mul_of_pos_left h x.prop⟩ @[priority 200] -- see Note [lower instance priority] instance ordered_semiring.mul_pos_strict_mono : zero_lt.mul_pos_strict_mono α := ⟨λ x a b h, mul_lt_mul_of_pos_right h x.prop⟩ section nontrivial variables [nontrivial α] @[simp] lemma zero_lt_one : 0 < (1 : α) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := zero_lt_two.ne' lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one @[field_simps] lemma three_ne_zero : (3:α) ≠ 0 := zero_lt_three.ne' lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two @[field_simps] lemma four_ne_zero : (4:α) ≠ 0 := zero_lt_four.ne' alias zero_lt_one ← one_pos alias zero_lt_two ← two_pos alias zero_lt_three ← three_pos alias zero_lt_four ← four_pos end nontrivial lemma mul_lt_of_lt_one_left (hb : 0 < b) (ha : a < 1) : a * b < b := (mul_lt_mul_of_pos_right ha hb).trans_le (one_mul _).le lemma mul_lt_of_lt_one_right (ha : 0 < a) (hb : b < 1) : a * b < a := (mul_lt_mul_of_pos_left hb ha).trans_le (mul_one _).le -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonneg_right -- TODO: there are four variations, depending on which variables we assume to be nonneg -- See Note [decidable namespace] protected lemma decidable.mul_le_mul [@decidable_rel α (≤)] (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_le_mul : a ≤ c → b ≤ d → 0 ≤ b → 0 ≤ c → a * b ≤ c * d := by classical; exact decidable.mul_le_mul -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] [@decidable_rel α (≤)] {a b c : α} (h₁ : 0 ≤ c) (h₂ : a ≤ c) (h₃ : 0 ≤ b) (h₄ : b ≤ 1) : a * b ≤ c := by simpa only [mul_one] using decidable.mul_le_mul h₂ h₄ h₃ h₁ lemma mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] {a b c : α} : 0 ≤ c → a ≤ c → 0 ≤ b → b ≤ 1 → a * b ≤ c := by classical; exact decidable.mul_nonneg_le_one_le -- See Note [decidable namespace] protected lemma decidable.mul_nonneg [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.mul_nonneg @[simp] theorem pow_nonneg (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := by { rw pow_zero, exact zero_le_one} | (n+1) := by { rw pow_succ, exact mul_nonneg H (pow_nonneg _) } -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonneg_of_nonpos [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from decidable.mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonneg_of_nonpos : 0 ≤ a → b ≤ 0 → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonneg_of_nonpos -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonpos_of_nonneg [@decidable_rel α (≤)] (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_nonpos_of_nonpos_of_nonneg : a ≤ 0 → 0 ≤ b → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonpos_of_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul [@decidable_rel α (≤)] (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul : a < c → b ≤ d → 0 < b → 0 ≤ c → a * b < c * d := by classical; exact decidable.mul_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul' [@decidable_rel α (≤)] (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_lt_mul' : a ≤ c → b < d → 0 ≤ b → 0 < c → a * b < c * d := by classical; exact decidable.mul_lt_mul' lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h @[simp] theorem pow_pos (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := by { nontriviality, rw pow_zero, exact zero_lt_one } | (n+1) := by { rw pow_succ, exact mul_pos H (pow_pos _) } lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h -- See Note [decidable namespace] protected lemma decidable.mul_self_lt_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := decidable.mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 -- See Note [decidable namespace] protected lemma decidable.strict_mono_on_mul_self [@decidable_rel α (≤)] : strict_mono_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, decidable.mul_self_lt_mul_self hx hxy lemma strict_mono_on_mul_self : strict_mono_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, mul_self_lt_mul_self hx hxy -- See Note [decidable namespace] protected lemma decidable.mul_self_le_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := decidable.mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul'' [@decidable_rel α (≤)] (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := h4.lt_or_eq_dec.elim (λ b0, decidable.mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma mul_lt_mul'' : a < c → b < d → 0 ≤ a → 0 ≤ b → a * b < c * d := by classical; exact decidable.mul_lt_mul'' -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_right [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, decidable.mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_right : 0 ≤ b → 1 ≤ a → b ≤ b * a := by classical; exact decidable.le_mul_of_one_le_right -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, decidable.mul_le_mul_of_nonneg_right h hb lemma le_mul_of_one_le_left : 0 ≤ b → 1 ≤ a → b ≤ a * b := by classical; exact decidable.le_mul_of_one_le_left -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_right [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, decidable.mul_lt_mul' le_rfl h zero_le_one hb lemma lt_mul_of_one_lt_right : 0 < b → 1 < a → b < b * a := by classical; exact decidable.lt_mul_of_one_lt_right -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_left [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < a * b := suffices 1 * b < a * b, by rwa one_mul at this, decidable.mul_lt_mul h le_rfl hb (zero_le_one.trans h.le) lemma lt_mul_of_one_lt_left : 0 < b → 1 < a → b < a * b := by classical; exact decidable.lt_mul_of_one_lt_left lemma lt_two_mul_self [nontrivial α] (ha : 0 < a) : a < 2 * a := lt_mul_of_one_lt_left ha one_lt_two lemma lt_mul_left (hn : 0 < a) (hm : 1 < b) : a < b * a := by { convert mul_lt_mul_of_pos_right hm hn, rw one_mul } lemma lt_mul_right (hn : 0 < a) (hm : 1 < b) : a < a * b := by { convert mul_lt_mul_of_pos_left hm hn, rw mul_one } lemma lt_mul_self (hn : 1 < a) : a < a * a := lt_mul_left (hn.trans_le' zero_le_one) hn -- See Note [decidable namespace] protected lemma decidable.add_le_mul_two_add [@decidable_rel α (≤)] {a b : α} (a2 : 2 ≤ a) (b0 : 0 ≤ b) : a + (2 + b) ≤ a * (2 + b) := calc a + (2 + b) ≤ a + (a + a * b) : add_le_add_left (add_le_add a2 (decidable.le_mul_of_one_le_left b0 (one_le_two.trans a2))) a ... ≤ a * (2 + b) : by rw [mul_add, mul_two, add_assoc] lemma add_le_mul_two_add {a b : α} : 2 ≤ a → 0 ≤ b → a + (2 + b) ≤ a * (2 + b) := by classical; exact decidable.add_le_mul_two_add -- See Note [decidable namespace] protected lemma decidable.one_le_mul_of_one_le_of_one_le [@decidable_rel α (≤)] {a b : α} (a1 : 1 ≤ a) (b1 : 1 ≤ b) : (1 : α) ≤ a * b := (mul_one (1 : α)).symm.le.trans (decidable.mul_le_mul a1 b1 zero_le_one (zero_le_one.trans a1)) lemma one_le_mul_of_one_le_of_one_le {a b : α} : 1 ≤ a → 1 ≤ b → (1 : α) ≤ a * b := by classical; exact decidable.one_le_mul_of_one_le_of_one_le /-- Pullback an `ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : ordered_semiring β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, zero_le_one], mul_lt_mul_of_pos_left := λ a b c ab c0, show f (c * a) < f (c * b), begin rw [mul, mul], refine mul_lt_mul_of_pos_left ab _, rwa ← zero, end, mul_lt_mul_of_pos_right := λ a b c ab c0, show f (a * c) < f (b * c), begin rw [mul, mul], refine mul_lt_mul_of_pos_right ab _, rwa ← zero, end, ..hf.ordered_cancel_add_comm_monoid f zero add nsmul, ..hf.semiring f zero one add mul nsmul npow nat_cast } section variable [nontrivial α] lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end -- See Note [decidable namespace] protected lemma decidable.one_lt_mul [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : α)) ▸ decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_le_one [@decidable_rel α (≤)] (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := one_mul (1 : α) ▸ decidable.mul_le_mul ha hb hb' zero_le_one lemma mul_le_one : a ≤ 1 → 0 ≤ b → b ≤ 1 → a * b ≤ 1 := by classical; exact decidable.mul_le_one -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_le_of_lt [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_le_of_lt : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_le_of_lt -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_lt_of_le [@decidable_rel α (≤)] (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma one_lt_mul_of_lt_of_le : 1 < a → 1 ≤ b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_lt_of_le -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_right [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : decidable.mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_right : 0 ≤ a → b ≤ 1 → a * b ≤ a := by classical; exact decidable.mul_le_of_le_one_right -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : decidable.mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_le_of_le_one_left : 0 ≤ b → a ≤ 1 → a * b ≤ b := by classical; exact decidable.mul_le_of_le_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_left [@decidable_rel α (≤)] (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : decidable.mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_left : 0 ≤ a → a < 1 → b ≤ 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_right [@decidable_rel α (≤)] (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : decidable.mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_lt_one_of_nonneg_of_lt_one_right : a ≤ 1 → 0 ≤ b → b < 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_right theorem nat.strict_mono_cast [nontrivial α] : strict_mono (coe : ℕ → α) := strict_mono_nat_of_lt_succ $ λ n, by rw [nat.cast_succ]; apply lt_add_one /-- Note this is not an instance as `char_zero` implies `nontrivial`, and this would risk forming a loop. -/ lemma ordered_semiring.to_char_zero [nontrivial α] : char_zero α := ⟨nat.strict_mono_cast.injective⟩ section has_exists_add_of_le variables [has_exists_add_of_le α] /-- Binary **rearrangement inequality**. -/ lemma mul_add_mul_le_mul_add_mul (hab : a ≤ b) (hcd : c ≤ d) : a * d + b * c ≤ a * c + b * d := begin obtain ⟨b, rfl⟩ := exists_add_of_le hab, obtain ⟨d, rfl⟩ := exists_add_of_le hcd, rw [mul_add, add_right_comm, mul_add, ←add_assoc], exact add_le_add_left (mul_le_mul_of_nonneg_right hab $ (le_add_iff_nonneg_right _).1 hcd) _, end /-- Binary **rearrangement inequality**. -/ lemma mul_add_mul_le_mul_add_mul' (hba : b ≤ a) (hdc : d ≤ c) : a • d + b • c ≤ a • c + b • d := by { rw [add_comm (a • d), add_comm (a • c)], exact mul_add_mul_le_mul_add_mul hba hdc } /-- Binary strict **rearrangement inequality**. -/ lemma mul_add_mul_lt_mul_add_mul (hab : a < b) (hcd : c < d) : a * d + b * c < a * c + b * d := begin obtain ⟨b, rfl⟩ := exists_add_of_le hab.le, obtain ⟨d, rfl⟩ := exists_add_of_le hcd.le, rw [mul_add, add_right_comm, mul_add, ←add_assoc], exact add_lt_add_left (mul_lt_mul_of_pos_right hab $ (lt_add_iff_pos_right _).1 hcd) _, end /-- Binary **rearrangement inequality**. -/ lemma mul_add_mul_lt_mul_add_mul' (hba : b < a) (hdc : d < c) : a • d + b • c < a • c + b • d := by { rw [add_comm (a • d), add_comm (a • c)], exact mul_add_mul_lt_mul_add_mul hba hdc } end has_exists_add_of_le end ordered_semiring section ordered_comm_semiring /-- An `ordered_comm_semiring α` is a commutative semiring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_comm_semiring (α : Type u) extends ordered_semiring α, comm_semiring α /-- Pullback an `ordered_comm_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_semiring [ordered_comm_semiring α] {β : Type*} [add_monoid_with_one β] [has_mul β] [has_pow β ℕ] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : ordered_comm_semiring β := { ..hf.comm_semiring f zero one add mul nsmul npow nat_cast, ..hf.ordered_semiring f zero one add mul nsmul npow nat_cast } end ordered_comm_semiring /-- A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_ordered_add_comm_monoid α, nontrivial α section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from decidable.mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from decidable.mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin haveI := @linear_order.decidable_le α _, rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonneg_of_nonpos ha.le hb }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonpos_of_nonneg ha.le hb } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) : (0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) := begin haveI := @linear_order.decidable_le α _, refine decidable.or_iff_not_and_not.2 _, simp only [not_and, not_le], intros ab nab, apply not_lt_of_le hab _, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (ab ha.le), ((ab le_rfl).asymm (nab le_rfl)).elim, mul_neg_of_neg_of_pos ha (nab ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1 lemma pos_of_mul_pos_right (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2 lemma pos_iff_pos_of_mul_pos (hab : 0 < a * b) : 0 < a ↔ 0 < b := ⟨pos_of_mul_pos_right hab ∘ le_of_lt, pos_of_mul_pos_left hab ∘ le_of_lt⟩ lemma neg_of_mul_pos_left (h : 0 < a * b) (ha : b ≤ 0) : a < 0 := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_left $ λ h, h.2.not_le ha).1 lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_left $ λ h, h.1.not_le ha).2 lemma neg_iff_neg_of_mul_pos (hab : 0 < a * b) : a < 0 ↔ b < 0 := ⟨neg_of_mul_pos_right hab ∘ le_of_lt, neg_of_mul_pos_left hab ∘ le_of_lt⟩ lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : 0 < b) : 0 ≤ a := le_of_not_gt $ λ ha, (mul_neg_of_neg_of_pos ha hb).not_le h lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : 0 < a) : 0 ≤ b := le_of_not_gt $ λ hb, (mul_neg_of_pos_of_neg ha hb).not_le h lemma neg_of_mul_neg_left (h : a * b < 0) (hb : 0 ≤ b) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha : a ≥ 0, (decidable.mul_nonneg ha hb).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (ha : 0 ≤ a) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume hb : b ≥ 0, (decidable.mul_nonneg ha hb).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (hb : 0 < b) : a ≤ 0 := le_of_not_gt (assume ha : a > 0, (mul_pos ha hb).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (ha : 0 < a) : b ≤ 0 := le_of_not_gt (assume hb : b > 0, (mul_pos ha hb).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_left h' h, λ h', decidable.mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_right h' h, λ h', decidable.mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_left h' h.le, λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_right h' h.le, λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } lemma add_le_mul_of_left_le_right (a2 : 2 ≤ a) (ab : a ≤ b) : a + b ≤ a * b := have 0 < b, from calc 0 < 2 : zero_lt_two ... ≤ a : a2 ... ≤ b : ab, calc a + b ≤ b + b : add_le_add_right ab b ... = 2 * b : (two_mul b).symm ... ≤ a * b : (mul_le_mul_right this).mpr a2 lemma add_le_mul_of_right_le_left (b2 : 2 ≤ b) (ba : b ≤ a) : a + b ≤ a * b := have 0 < a, from calc 0 < 2 : zero_lt_two ... ≤ b : b2 ... ≤ a : ba, calc a + b ≤ a + a : add_le_add_left ba a ... = a * 2 : (mul_two a).symm ... ≤ a * b : (mul_le_mul_left this).mpr b2 lemma add_le_mul (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ a * b := if hab : a ≤ b then add_le_mul_of_left_le_right a2 hab else add_le_mul_of_right_le_left b2 (le_of_not_le hab) lemma add_le_mul' (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ b * a := (le_of_eq (add_comm _ _)).trans (add_le_mul b2 a2) section @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb theorem mul_nonneg_iff_right_nonneg_of_pos (ha : 0 < a) : 0 ≤ a * b ↔ 0 ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h, nonneg_of_mul_nonneg_right h ha, λ h, decidable.mul_nonneg ha.le h⟩ theorem mul_nonneg_iff_left_nonneg_of_pos (hb : 0 < b) : 0 ≤ a * b ↔ 0 ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨λ h, nonneg_of_mul_nonneg_left h hb, λ h, decidable.mul_nonneg h hb.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := lt_iff_lt_of_le_iff_le $ le_mul_iff_one_le_left hb lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := lt_iff_lt_of_le_iff_le $ le_mul_iff_one_le_right hb lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_max_order {α : Type*} [linear_ordered_semiring α] : no_max_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ /-- Pullback a `linear_ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_semiring β := { .. linear_order.lift f hf hsup hinf, .. pullback_nonzero f zero one, .. hf.ordered_semiring f zero one add mul nsmul npow nat_cast } @[simp] lemma units.inv_pos {u : αˣ} : (0 : α) < ↑u⁻¹ ↔ (0 : α) < u := have ∀ {u : αˣ}, (0 : α) < u → (0 : α) < ↑u⁻¹ := λ u h, (zero_lt_mul_left h).mp $ u.mul_inv.symm ▸ zero_lt_one, ⟨this, this⟩ @[simp] lemma units.inv_neg {u : αˣ} : ↑u⁻¹ < (0 : α) ↔ ↑u < (0 : α) := have ∀ {u : αˣ}, ↑u < (0 : α) → ↑u⁻¹ < (0 : α) := λ u h, neg_of_mul_pos_right (by exact (u.mul_inv.symm ▸ zero_lt_one)) h.le, ⟨this, this⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero : char_zero α := ordered_semiring.to_char_zero end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (zero_le_one : 0 ≤ (1 : α)) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_nonneg [@decidable_rel α (≤)] {a b : α} (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin by_cases ha : a ≤ 0, { simp [le_antisymm ha h₁] }, by_cases hb : b ≤ 0, { simp [le_antisymm hb h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le ha) (h₂.lt_of_not_le hb))).1, end lemma ordered_ring.mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.ordered_ring.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin rw [← sub_nonneg, ← mul_sub], exact decidable.ordered_ring.mul_nonneg h₂ (sub_nonneg.2 h₁), end lemma ordered_ring.mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin rw [← sub_nonneg, ← sub_mul], exact decidable.ordered_ring.mul_nonneg (sub_nonneg.2 h₁) h₂, end lemma ordered_ring.mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_right lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := begin rw [← sub_pos, ← mul_sub], exact ordered_ring.mul_pos _ _ h₂ (sub_pos.2 h₁), end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := begin rw [← sub_pos, ← sub_mul], exact ordered_ring.mul_pos _ _ (sub_pos.2 h₁) h₂, end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_left [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from decidable.mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [neg_mul, neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_left {a b c : α} : b ≤ a → c ≤ 0 → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonpos_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_right [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from decidable.mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [mul_neg, mul_neg] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} : b ≤ a → c ≤ 0 → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonpos_right -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_of_nonpos_of_nonpos [@decidable_rel α (≤)] {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} : a ≤ 0 → b ≤ 0 → 0 ≤ a * b := by classical; exact decidable.mul_nonneg_of_nonpos_of_nonpos lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [neg_mul, neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [mul_neg, mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this /-- Pullback an `ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : ordered_ring β := { mul_pos := λ a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero }, ..hf.ordered_semiring f zero one add mul nsmul npow nat_cast, ..hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } lemma le_iff_exists_nonneg_add (a b : α) : a ≤ b ↔ ∃ c ≥ 0, b = a + c := ⟨λ h, ⟨b - a, sub_nonneg.mpr h, by simp⟩, λ ⟨c, hc, h⟩, by { rw [h, le_add_iff_nonneg_right], exact hc }⟩ end ordered_ring section ordered_comm_ring /-- An `ordered_comm_ring α` is a commutative ring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_comm_ring (α : Type u) extends ordered_ring α, comm_ring α @[priority 100] -- See note [lower instance priority] instance ordered_comm_ring.to_ordered_comm_semiring {α : Type u} [ordered_comm_ring α] : ordered_comm_semiring α := { .. (by apply_instance : ordered_semiring α), .. ‹ordered_comm_ring α› } /-- Pullback an `ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_ring [ordered_comm_ring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_pow β ℕ] [has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β] [has_int_cast β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) : ordered_comm_ring β := { ..hf.ordered_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast, ..hf.comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } end ordered_comm_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α, nontrivial α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] : linear_ordered_add_comm_group α := { .. s } section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} local attribute [instance] linear_ordered_semiring.decidable_le lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : decidable.mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_sq_le_sq {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := le_of_not_gt (λhab, (decidable.mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := ⟨decidable.mul_self_le_mul_self h1, nonneg_le_nonneg_of_sq_le_sq h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := ((@decidable.strict_mono_on_mul_self α _ _).lt_iff_lt h1 h2).symm lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b := (@decidable.strict_mono_on_mul_self α _ _).inj_on.eq_iff h1 h2 end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.is_domain : is_domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, refine decidable.or_iff_not_and_not.2 (λ h, _), revert hab, cases lt_or_gt_of_ne h.1 with ha ha; cases lt_or_gt_of_ne h.2 with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. ‹linear_ordered_ring α› } @[simp] lemma abs_one : |(1 : α)| = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : |(2 : α)| = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : |a * b| = |a| * |b| := begin haveI := @linear_order.decidable_le α _, rw [abs_eq (decidable.mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp only [abs_of_nonpos, abs_of_nonneg, true_or, or_true, eq_self_iff_true, neg_mul, mul_neg, neg_neg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : α →*₀ α := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] lemma abs_mul_abs_self (a : α) : |a| * |a| = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) @[simp] lemma abs_mul_self (a : α) : |a * a| = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by haveI := @linear_order.decidable_le α _; exact ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, λ h, h.elim (and_imp.2 decidable.mul_nonneg) (and_imp.2 decidable.mul_nonneg_of_nonpos_of_nonpos)⟩ /-- Out of three elements of a `linear_ordered_ring`, two must have the same sign. -/ lemma mul_nonneg_of_three (a b c : α) : 0 ≤ a * b ∨ 0 ≤ b * c ∨ 0 ≤ c * a := by iterate 3 { rw mul_nonneg_iff }; have := le_total 0 a; have := le_total 0 b; have := le_total 0 c; itauto lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : α) : 0 ≤ a * a := abs_mul_self a ▸ abs_nonneg _ @[simp] lemma neg_le_self_iff : -a ≤ a ↔ 0 ≤ a := by simp [neg_le_iff_add_nonneg, ← two_mul, mul_nonneg_iff, zero_le_one, (@zero_lt_two α _ _).not_le] @[simp] lemma neg_lt_self_iff : -a < a ↔ 0 < a := by simp [neg_lt_iff_pos_add, ← two_mul, mul_pos_iff, zero_lt_one, (@zero_lt_two α _ _).not_lt] @[simp] lemma le_neg_self_iff : a ≤ -a ↔ a ≤ 0 := calc a ≤ -a ↔ -(-a) ≤ -a : by rw neg_neg ... ↔ 0 ≤ -a : neg_le_self_iff ... ↔ a ≤ 0 : neg_nonneg @[simp] lemma lt_neg_self_iff : a < -a ↔ a < 0 := calc a < -a ↔ -(-a) < -a : by rw neg_neg ... ↔ 0 < -a : neg_lt_self_iff ... ↔ a < 0 : neg_pos @[simp] lemma abs_eq_self : |a| = a ↔ 0 ≤ a := by simp [abs_eq_max_neg] @[simp] lemma abs_eq_neg_self : |a| = -a ↔ a ≤ 0 := by simp [abs_eq_max_neg] /-- For an element `a` of a linear ordered ring, either `abs a = a` and `0 ≤ a`, or `abs a = -a` and `a < 0`. Use cases on this lemma to automate linarith in inequalities -/ lemma abs_cases (a : α) : (|a| = a ∧ 0 ≤ a) ∨ (|a| = -a ∧ a < 0) := begin by_cases 0 ≤ a, { left, exact ⟨abs_eq_self.mpr h, h⟩ }, { right, push_neg at h, exact ⟨abs_eq_neg_self.mpr (le_of_lt h), h⟩ } end @[simp] lemma max_zero_add_max_neg_zero_eq_abs_self (a : α) : max a 0 + max (-a) 0 = |a| := begin symmetry, rcases le_total 0 a with ha|ha; simp [ha], end lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := neg_lt_zero.2 zero_lt_one @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', decidable.mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', decidable.mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) @[simp] lemma mul_self_pos {a : α} : 0 < a * a ↔ a ≠ 0 := begin split, { rintro h rfl, rw mul_zero at h, exact h.false }, { intro h, cases h.lt_or_lt with h h, exacts [mul_pos_of_neg_of_neg h h, mul_pos h h] } end lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin haveI := @linear_order.decidable_le α _, rw [← abs_mul_abs_self x], exact decidable.mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 h₂, h₁⟩) end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma neg_iff_pos_of_mul_neg (hab : a * b < 0) : a < 0 ↔ 0 < b := ⟨pos_of_mul_neg_right hab ∘ le_of_lt, neg_of_mul_neg_left hab ∘ le_of_lt⟩ lemma pos_iff_neg_of_mul_neg (hab : a * b < 0) : 0 < a ↔ b < 0 := ⟨neg_of_mul_neg_right hab ∘ le_of_lt, pos_of_mul_neg_left hab ∘ le_of_lt⟩ /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : |a| = |b| ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : |a| < |b| ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : |a| ≤ |b| ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : |a| ≤ 1 ↔ a * a ≤ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1 /-- Pullback a `linear_ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_smul ℕ β] [has_smul ℤ β] [has_pow β ℕ] [has_nat_cast β] [has_int_cast β] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_ring β := { .. linear_order.lift f hf hsup hinf, .. pullback_nonzero f zero one, .. hf.ordered_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_ordered_comm_ring [d : linear_ordered_comm_ring α] : ordered_comm_ring α := { ..d } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] : linear_ordered_semiring α := { .. d, ..linear_ordered_ring.to_linear_ordered_semiring } section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := by haveI := @linear_order.decidable_le α _; exact have ba : b * a ≤ max d b * max c a, from decidable.mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from decidable.mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_sq (a b : α) : |a - b| * |a - b| = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp only [mul_add, add_comm, add_left_comm, mul_comm, sub_eq_add_neg, mul_one, mul_neg, neg_add_rev, neg_neg], end end linear_ordered_comm_ring section variables [ring α] [linear_order α] {a b : α} @[simp] lemma abs_dvd (a b : α) : |a| ∣ b ↔ a ∣ b := by { cases abs_choice a with h h; simp only [h, neg_dvd] } lemma abs_dvd_self (a : α) : |a| ∣ a := (abs_dvd a a).mpr (dvd_refl a) @[simp] lemma dvd_abs (a b : α) : a ∣ |b| ↔ a ∣ b := by { cases abs_choice b with h h; simp only [h, dvd_neg] } lemma self_dvd_abs (a : α) : a ∣ |a| := (dvd_abs a a).mpr (dvd_refl a) lemma abs_dvd_abs (a b : α) : |a| ∣ |b| ↔ a ∣ b := (abs_dvd _ _).trans (dvd_abs _ _) end section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] /-- Pullback a `linear_ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_comm_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_pow β ℕ] [has_smul ℕ β] [has_smul ℤ β] [has_nat_cast β] [has_int_cast β] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_comm_ring β := { .. linear_order.lift f hf hsup hinf, .. pullback_nonzero f zero one, .. hf.ordered_comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } end linear_ordered_comm_ring namespace ring /-- A positive cone in a ring consists of a positive cone in underlying `add_comm_group`, which contains `1` and such that the positive elements are closed under multiplication. -/ @[nolint has_nonempty_instance] structure positive_cone (α : Type*) [ring α] extends add_comm_group.positive_cone α := (one_nonneg : nonneg 1) (mul_pos : ∀ (a b), pos a → pos b → pos (a * b)) /-- Forget that a positive cone in a ring respects the multiplicative structure. -/ add_decl_doc positive_cone.to_positive_cone /-- A positive cone in a ring induces a linear order if `1` is a positive element. -/ @[nolint has_nonempty_instance] structure total_positive_cone (α : Type*) [ring α] extends positive_cone α, add_comm_group.total_positive_cone α := (one_pos : pos 1) /-- Forget that a `total_positive_cone` in a ring is total. -/ add_decl_doc total_positive_cone.to_positive_cone /-- Forget that a `total_positive_cone` in a ring respects the multiplicative structure. -/ add_decl_doc total_positive_cone.to_total_positive_cone end ring namespace ordered_ring open ring /-- Construct an `ordered_ring` by designating a positive cone in an existing `ring`. -/ def mk_of_positive_cone {α : Type*} [ring α] (C : positive_cone α) : ordered_ring α := { zero_le_one := by { change C.nonneg (1 - 0), convert C.one_nonneg, simp, }, mul_pos := λ x y xp yp, begin change C.pos (x*y - 0), convert C.mul_pos x y (by { convert xp, simp, }) (by { convert yp, simp, }), simp, end, ..‹ring α›, ..ordered_add_comm_group.mk_of_positive_cone C.to_positive_cone } end ordered_ring namespace linear_ordered_ring open ring /-- Construct a `linear_ordered_ring` by designating a positive cone in an existing `ring`. -/ def mk_of_positive_cone {α : Type*} [ring α] (C : total_positive_cone α) : linear_ordered_ring α := { exists_pair_ne := ⟨0, 1, begin intro h, have one_pos := C.one_pos, rw [←h, C.pos_iff] at one_pos, simpa using one_pos, end⟩, ..ordered_ring.mk_of_positive_cone C.to_positive_cone, ..linear_ordered_add_comm_group.mk_of_positive_cone C.to_total_positive_cone, } end linear_ordered_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring α] {a b : α} @[priority 100] -- see Note [lower instance priority] instance to_no_zero_divisors : no_zero_divisors α := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance to_covariant_mul_le : covariant_class α α (*) (≤) := begin refine ⟨λ a b c h, _⟩, rcases exists_add_of_le h with ⟨c, rfl⟩, rw mul_add, apply self_le_add_right end @[priority 200] -- see Note [lower instance priority] instance canonically_ordered_comm_semiring.pos_mul_mono : zero_lt.pos_mul_mono α := ⟨λ x a b h, by { obtain ⟨d, rfl⟩ := exists_add_of_le h, simp_rw [left_distrib, le_self_add], }⟩ @[priority 200] -- see Note [lower instance priority] instance canonically_ordered_comm_semiring.mul_pos_mono : zero_lt.mul_pos_mono α := ⟨λ x a b h, by { obtain ⟨d, rfl⟩ := exists_add_of_le h, simp_rw [right_distrib, le_self_add], }⟩ /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one @[simp] lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_comm_semiring section sub variables [canonically_ordered_comm_semiring α] {a b c : α} variables [has_sub α] [has_ordered_sub α] variables [is_total α (≤)] namespace add_le_cancellable protected lemma mul_tsub (h : add_le_cancellable (a * c)) : a * (b - c) = a * b - a * c := begin cases total_of (≤) b c with hbc hcb, { rw [tsub_eq_zero_iff_le.2 hbc, mul_zero, tsub_eq_zero_iff_le.2 (mul_le_mul_left' hbc a)] }, { apply h.eq_tsub_of_add_eq, rw [← mul_add, tsub_add_cancel_of_le hcb] } end protected lemma tsub_mul (h : add_le_cancellable (b * c)) : (a - b) * c = a * c - b * c := by { simp only [mul_comm _ c] at *, exact h.mul_tsub } end add_le_cancellable variables [contravariant_class α α (+) (≤)] lemma mul_tsub (a b c : α) : a * (b - c) = a * b - a * c := contravariant.add_le_cancellable.mul_tsub lemma tsub_mul (a b c : α) : (a - b) * c = a * c - b * c := contravariant.add_le_cancellable.tsub_mul end sub /-! ### Structures involving `*` and `0` on `with_top` and `with_bot` The main results of this section are `with_top.canonically_ordered_comm_semiring` and `with_bot.comm_monoid_with_zero`. -/ namespace with_top instance [nonempty α] : nontrivial (with_top α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λ m n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end lemma mul_lt_top [preorder α] {a b : with_top α} (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a * b < ⊤ := begin lift a to α using ha, lift b to α using hb, simp only [← coe_mul, coe_lt_top] end @[simp] lemma untop'_zero_mul (a b : with_top α) : (a * b).untop' 0 = a.untop' 0 * b.untop' 0 := begin by_cases ha : a = 0, { rw [ha, zero_mul, ← coe_zero, untop'_coe, zero_mul] }, by_cases hb : b = 0, { rw [hb, mul_zero, ← coe_zero, untop'_coe, mul_zero] }, induction a using with_top.rec_top_coe, { rw [top_mul hb, untop'_top, zero_mul] }, induction b using with_top.rec_top_coe, { rw [mul_top ha, untop'_top, mul_zero] }, rw [← coe_mul, untop'_coe, untop'_coe, untop'_coe] end end mul_zero_class /-- `nontrivial α` is needed here as otherwise we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`. -/ instance [mul_zero_one_class α] [nontrivial α] : mul_zero_one_class (with_top α) := { mul := (*), one := 1, zero := 0, one_mul := λ a, match a with | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one] end, mul_one := λ a, match a with | none := show ⊤ * ((1:α) : with_top α) = ⊤, by simp [-with_top.coe_one] | (some a) := show ↑a * ((1:α) : with_top α) = a, by simp [coe_mul.symm, -with_top.coe_one] end, .. with_top.mul_zero_class } /-- A version of `with_top.map` for `monoid_with_zero_hom`s. -/ @[simps { fully_applied := ff }] protected def _root_.monoid_with_zero_hom.with_top_map {R S : Type*} [mul_zero_one_class R] [decidable_eq R] [nontrivial R] [mul_zero_one_class S] [decidable_eq S] [nontrivial S] (f : R →*₀ S) (hf : function.injective f) : with_top R →*₀ with_top S := { to_fun := with_top.map f, map_mul' := λ x y, begin have : ∀ z, map f z = 0 ↔ z = 0, from λ z, (option.map_injective hf).eq_iff' f.to_zero_hom.with_top_map.map_zero, rcases eq_or_ne x 0 with rfl|hx, { simp }, rcases eq_or_ne y 0 with rfl|hy, { simp }, induction x using with_top.rec_top_coe, { simp [hy, this] }, induction y using with_top.rec_top_coe, { have : (f x : with_top S) ≠ 0, by simpa [hf.eq_iff' (map_zero f)] using hx, simp [hx, this] }, simp [← coe_mul] end, .. f.to_zero_hom.with_top_map, .. f.to_monoid_hom.to_one_hom.with_top_map } instance [mul_zero_class α] [no_zero_divisors α] : no_zero_divisors (with_top α) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ instance [semigroup_with_zero α] [no_zero_divisors α] : semigroup_with_zero (with_top α) := { mul := (*), zero := 0, mul_assoc := λ a b c, begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end, .. with_top.mul_zero_class } instance [monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : monoid_with_zero (with_top α) := { .. with_top.mul_zero_one_class, .. with_top.semigroup_with_zero } instance [comm_monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : comm_monoid_with_zero (with_top α) := { mul := (*), zero := 0, mul_comm := λ a b, begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end, .. with_top.monoid_with_zero } variables [canonically_ordered_comm_semiring α] private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end /-- This instance requires `canonically_ordered_comm_semiring` as it is the smallest class that derives from both `non_assoc_non_unital_semiring` and `canonically_ordered_add_monoid`, both of which are required for distributivity. -/ instance [nontrivial α] : comm_semiring (with_top α) := { right_distrib := distrib', left_distrib := λ a b c, by { rw [mul_comm, distrib', mul_comm b, mul_comm c], refl }, .. with_top.add_comm_monoid_with_one, .. with_top.comm_monoid_with_zero } instance [nontrivial α] : canonically_ordered_comm_semiring (with_top α) := { .. with_top.comm_semiring, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, } /-- A version of `with_top.map` for `ring_hom`s. -/ @[simps { fully_applied := ff }] protected def _root_.ring_hom.with_top_map {R S : Type*} [canonically_ordered_comm_semiring R] [decidable_eq R] [nontrivial R] [canonically_ordered_comm_semiring S] [decidable_eq S] [nontrivial S] (f : R →+* S) (hf : function.injective f) : with_top R →+* with_top S := { to_fun := with_top.map f, .. f.to_monoid_with_zero_hom.with_top_map hf, .. f.to_add_monoid_hom.with_top_map } end with_top namespace with_bot instance [nonempty α] : nontrivial (with_bot α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_bot α) := with_top.mul_zero_class lemma mul_def {a b : with_bot α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_bot {a : with_bot α} (h : a ≠ 0) : a * ⊥ = ⊥ := with_top.mul_top h @[simp] lemma bot_mul {a : with_bot α} (h : a ≠ 0) : ⊥ * a = ⊥ := with_top.top_mul h @[simp] lemma bot_mul_bot : (⊥ * ⊥ : with_bot α) = ⊥ := with_top.top_mul_top end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_bot α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) {a : with_bot α} : a * b = a.bind (λa:α, ↑(a * b)) := with_top.mul_coe hb @[simp] lemma mul_eq_bot_iff {a b : with_bot α} : a * b = ⊥ ↔ (a ≠ 0 ∧ b = ⊥) ∨ (a = ⊥ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma bot_lt_mul [preorder α] {a b : with_bot α} (ha : ⊥ < a) (hb : ⊥ < b) : ⊥ < a * b := begin lift a to α using ne_bot_of_gt ha, lift b to α using ne_bot_of_gt hb, simp only [← coe_mul, bot_lt_coe], end end mul_zero_class /-- `nontrivial α` is needed here as otherwise we have `1 * ⊥ = ⊥` but also `= 0 * ⊥ = 0`. -/ instance [mul_zero_one_class α] [nontrivial α] : mul_zero_one_class (with_bot α) := with_top.mul_zero_one_class instance [mul_zero_class α] [no_zero_divisors α] : no_zero_divisors (with_bot α) := with_top.no_zero_divisors instance [semigroup_with_zero α] [no_zero_divisors α] : semigroup_with_zero (with_bot α) := with_top.semigroup_with_zero instance [monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : monoid_with_zero (with_bot α) := with_top.monoid_with_zero instance [comm_monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : comm_monoid_with_zero (with_bot α) := with_top.comm_monoid_with_zero instance [canonically_ordered_comm_semiring α] [nontrivial α] : comm_semiring (with_bot α) := with_top.comm_semiring instance [canonically_ordered_comm_semiring α] [nontrivial α] : zero_lt.pos_mul_mono (with_bot α) := ⟨ begin rintros ⟨x, x0⟩ a b h, simp only [subtype.coe_mk], induction x using with_bot.rec_bot_coe, { have := bot_lt_coe (0 : α), rw [coe_zero] at this, exact absurd x0.le this.not_le, }, { induction a using with_bot.rec_bot_coe, { simp_rw [mul_bot x0.ne.symm, bot_le], }, induction b using with_bot.rec_bot_coe, { exact absurd h (bot_lt_coe a).not_le, }, { simp only [← coe_mul, coe_le_coe] at *, exact zero_lt.mul_le_mul_left h (zero_le x), }, }, end ⟩ instance [canonically_ordered_comm_semiring α] [nontrivial α] : zero_lt.mul_pos_mono (with_bot α) := zero_lt.pos_mul_mono_iff_mul_pos_mono.mp zero_lt.pos_mul_mono end with_bot
2d4a66dc886482a8b3322e29d6484712201ce813
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Data/Char/Basic.lean
106a73949c7e3e499c968d56172afc5319ff8527
[ "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
1,974
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.UInt @[inline, reducible] def isValidChar (n : UInt32) : Prop := n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000) namespace Char protected def lt (a b : Char) : Prop := a.val < b.val protected def le (a b : Char) : Prop := a.val ≤ b.val instance : LT Char := ⟨Char.lt⟩ instance : LE Char := ⟨Char.le⟩ instance (a b : Char) : Decidable (a < b) := UInt32.decLt _ _ instance (a b : Char) : Decidable (a ≤ b) := UInt32.decLe _ _ abbrev isValidCharNat (n : Nat) : Prop := n < 0xd800 ∨ (0xdfff < n ∧ n < 0x110000) theorem isValidUInt32 (n : Nat) (h : isValidCharNat n) : n < UInt32.size := by match h with | Or.inl h => apply Nat.lt_trans h decide | Or.inr ⟨h₁, h₂⟩ => apply Nat.lt_trans h₂ decide theorem isValidChar_of_isValidChar_Nat (n : Nat) (h : isValidCharNat n) : isValidChar (UInt32.ofNat' n (isValidUInt32 n h)) := match h with | Or.inl h => Or.inl h | Or.inr ⟨h₁, h₂⟩ => Or.inr ⟨h₁, h₂⟩ theorem isValidChar_zero : isValidChar 0 := Or.inl (by decide) @[inline] def toNat (c : Char) : Nat := c.val.toNat instance : Inhabited Char where default := 'A' def isWhitespace (c : Char) : Bool := c = ' ' || c = '\t' || c = '\r' || c = '\n' def isUpper (c : Char) : Bool := c.val ≥ 65 && c.val ≤ 90 def isLower (c : Char) : Bool := c.val ≥ 97 && c.val ≤ 122 def isAlpha (c : Char) : Bool := c.isUpper || c.isLower def isDigit (c : Char) : Bool := c.val ≥ 48 && c.val ≤ 57 def isAlphanum (c : Char) : Bool := c.isAlpha || c.isDigit def toLower (c : Char) : Char := let n := toNat c; if n >= 65 ∧ n <= 90 then ofNat (n + 32) else c def toUpper (c : Char) : Char := let n := toNat c; if n >= 97 ∧ n <= 122 then ofNat (n - 32) else c end Char
18631908da28a70b445f412a8dd705987b3d1005
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/zsqrtd/basic_auto.lean
a847eafed11f2c169365c75a76b9846055a897d3
[]
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
20,835
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.associated import Mathlib.tactic.ring import Mathlib.PostPort universes l namespace Mathlib /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : ℤ) where re : ℤ im : ℤ prefix:100 "ℤ√" => Mathlib.zsqrtd namespace zsqrtd protected instance decidable_eq {d : ℤ} : DecidableEq (ℤ√d) := id fun (_v : ℤ√d) => cases_on _v fun (re im : ℤ) (w : ℤ√d) => cases_on w fun (w_re w_im : ℤ) => decidable.by_cases (fun (ᾰ : re = w_re) => Eq._oldrec (decidable.by_cases (fun (ᾰ : im = w_im) => Eq._oldrec (is_true sorry) ᾰ) fun (ᾰ : ¬im = w_im) => isFalse sorry) ᾰ) fun (ᾰ : ¬re = w_re) => isFalse sorry theorem ext {d : ℤ} {z : ℤ√d} {w : ℤ√d} : z = w ↔ re z = re w ∧ im z = im w := sorry /-- Convert an integer to a `ℤ√d` -/ def of_int {d : ℤ} (n : ℤ) : ℤ√d := mk n 0 theorem of_int_re {d : ℤ} (n : ℤ) : re (of_int n) = n := rfl theorem of_int_im {d : ℤ} (n : ℤ) : im (of_int n) = 0 := rfl /-- The zero of the ring -/ def zero {d : ℤ} : ℤ√d := of_int 0 protected instance has_zero {d : ℤ} : HasZero (ℤ√d) := { zero := zero } @[simp] theorem zero_re {d : ℤ} : re 0 = 0 := rfl @[simp] theorem zero_im {d : ℤ} : im 0 = 0 := rfl protected instance inhabited {d : ℤ} : Inhabited (ℤ√d) := { default := 0 } /-- The one of the ring -/ def one {d : ℤ} : ℤ√d := of_int 1 protected instance has_one {d : ℤ} : HasOne (ℤ√d) := { one := one } @[simp] theorem one_re {d : ℤ} : re 1 = 1 := rfl @[simp] theorem one_im {d : ℤ} : im 1 = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd {d : ℤ} : ℤ√d := mk 0 1 @[simp] theorem sqrtd_re {d : ℤ} : re sqrtd = 0 := rfl @[simp] theorem sqrtd_im {d : ℤ} : im sqrtd = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add {d : ℤ} : ℤ√d → ℤ√d → ℤ√d := sorry protected instance has_add {d : ℤ} : Add (ℤ√d) := { add := add } @[simp] theorem add_def {d : ℤ} (x : ℤ) (y : ℤ) (x' : ℤ) (y' : ℤ) : mk x y + mk x' y' = mk (x + x') (y + y') := rfl @[simp] theorem add_re {d : ℤ} (z : ℤ√d) (w : ℤ√d) : re (z + w) = re z + re w := cases_on z fun (z_re z_im : ℤ) => cases_on w fun (w_re w_im : ℤ) => idRhs (re (mk z_re z_im + mk w_re w_im) = re (mk z_re z_im + mk w_re w_im)) rfl @[simp] theorem add_im {d : ℤ} (z : ℤ√d) (w : ℤ√d) : im (z + w) = im z + im w := cases_on z fun (z_re z_im : ℤ) => cases_on w fun (w_re w_im : ℤ) => idRhs (im (mk z_re z_im + mk w_re w_im) = im (mk z_re z_im + mk w_re w_im)) rfl @[simp] theorem bit0_re {d : ℤ} (z : ℤ√d) : re (bit0 z) = bit0 (re z) := add_re z z @[simp] theorem bit0_im {d : ℤ} (z : ℤ√d) : im (bit0 z) = bit0 (im z) := add_im z z @[simp] theorem bit1_re {d : ℤ} (z : ℤ√d) : re (bit1 z) = bit1 (re z) := sorry @[simp] theorem bit1_im {d : ℤ} (z : ℤ√d) : im (bit1 z) = bit0 (im z) := sorry /-- Negation in `ℤ√d` -/ def neg {d : ℤ} : ℤ√d → ℤ√d := sorry protected instance has_neg {d : ℤ} : Neg (ℤ√d) := { neg := neg } @[simp] theorem neg_re {d : ℤ} (z : ℤ√d) : re (-z) = -re z := cases_on z fun (z_re z_im : ℤ) => idRhs (re (-mk z_re z_im) = re (-mk z_re z_im)) rfl @[simp] theorem neg_im {d : ℤ} (z : ℤ√d) : im (-z) = -im z := cases_on z fun (z_re z_im : ℤ) => idRhs (im (-mk z_re z_im) = im (-mk z_re z_im)) rfl /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj {d : ℤ} : ℤ√d → ℤ√d := sorry @[simp] theorem conj_re {d : ℤ} (z : ℤ√d) : re (conj z) = re z := cases_on z fun (z_re z_im : ℤ) => idRhs (re (conj (mk z_re z_im)) = re (conj (mk z_re z_im))) rfl @[simp] theorem conj_im {d : ℤ} (z : ℤ√d) : im (conj z) = -im z := cases_on z fun (z_re z_im : ℤ) => idRhs (im (conj (mk z_re z_im)) = im (conj (mk z_re z_im))) rfl /-- Multiplication in `ℤ√d` -/ def mul {d : ℤ} : ℤ√d → ℤ√d → ℤ√d := sorry protected instance has_mul {d : ℤ} : Mul (ℤ√d) := { mul := mul } @[simp] theorem mul_re {d : ℤ} (z : ℤ√d) (w : ℤ√d) : re (z * w) = re z * re w + d * im z * im w := cases_on z fun (z_re z_im : ℤ) => cases_on w fun (w_re w_im : ℤ) => idRhs (re (mk z_re z_im * mk w_re w_im) = re (mk z_re z_im * mk w_re w_im)) rfl @[simp] theorem mul_im {d : ℤ} (z : ℤ√d) (w : ℤ√d) : im (z * w) = re z * im w + im z * re w := cases_on z fun (z_re z_im : ℤ) => cases_on w fun (w_re w_im : ℤ) => idRhs (im (mk z_re z_im * mk w_re w_im) = im (mk z_re z_im * mk w_re w_im)) rfl protected instance comm_ring {d : ℤ} : comm_ring (ℤ√d) := comm_ring.mk Add.add sorry 0 sorry sorry Neg.neg (fun (a b : ℤ√d) => a + -b) sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry protected instance add_comm_monoid {d : ℤ} : add_comm_monoid (ℤ√d) := add_comm_group.to_add_comm_monoid (ℤ√d) protected instance add_monoid {d : ℤ} : add_monoid (ℤ√d) := sub_neg_monoid.to_add_monoid (ℤ√d) protected instance monoid {d : ℤ} : monoid (ℤ√d) := ring.to_monoid (ℤ√d) protected instance comm_monoid {d : ℤ} : comm_monoid (ℤ√d) := comm_semiring.to_comm_monoid (ℤ√d) protected instance comm_semigroup {d : ℤ} : comm_semigroup (ℤ√d) := comm_ring.to_comm_semigroup (ℤ√d) protected instance semigroup {d : ℤ} : semigroup (ℤ√d) := monoid.to_semigroup (ℤ√d) protected instance add_comm_semigroup {d : ℤ} : add_comm_semigroup (ℤ√d) := add_comm_monoid.to_add_comm_semigroup (ℤ√d) protected instance add_semigroup {d : ℤ} : add_semigroup (ℤ√d) := add_monoid.to_add_semigroup (ℤ√d) protected instance comm_semiring {d : ℤ} : comm_semiring (ℤ√d) := comm_ring.to_comm_semiring protected instance semiring {d : ℤ} : semiring (ℤ√d) := ring.to_semiring protected instance ring {d : ℤ} : ring (ℤ√d) := comm_ring.to_ring (ℤ√d) protected instance distrib {d : ℤ} : distrib (ℤ√d) := ring.to_distrib (ℤ√d) protected instance nontrivial {d : ℤ} : nontrivial (ℤ√d) := nontrivial.mk (Exists.intro 0 (Exists.intro 1 (of_as_true trivial))) @[simp] theorem coe_nat_re {d : ℤ} (n : ℕ) : re ↑n = ↑n := sorry @[simp] theorem coe_nat_im {d : ℤ} (n : ℕ) : im ↑n = 0 := sorry theorem coe_nat_val {d : ℤ} (n : ℕ) : ↑n = mk (↑n) 0 := sorry @[simp] theorem coe_int_re {d : ℤ} (n : ℤ) : re ↑n = n := sorry @[simp] theorem coe_int_im {d : ℤ} (n : ℤ) : im ↑n = 0 := sorry theorem coe_int_val {d : ℤ} (n : ℤ) : ↑n = mk n 0 := sorry protected instance char_zero {d : ℤ} : char_zero (ℤ√d) := sorry @[simp] theorem of_int_eq_coe {d : ℤ} (n : ℤ) : of_int n = ↑n := sorry @[simp] theorem smul_val {d : ℤ} (n : ℤ) (x : ℤ) (y : ℤ) : ↑n * mk x y = mk (n * x) (n * y) := sorry @[simp] theorem muld_val {d : ℤ} (x : ℤ) (y : ℤ) : sqrtd * mk x y = mk (d * y) x := sorry @[simp] theorem dmuld {d : ℤ} : sqrtd * sqrtd = ↑d := sorry @[simp] theorem smuld_val {d : ℤ} (n : ℤ) (x : ℤ) (y : ℤ) : sqrtd * ↑n * mk x y = mk (d * n * y) (n * x) := sorry theorem decompose {d : ℤ} {x : ℤ} {y : ℤ} : mk x y = ↑x + sqrtd * ↑y := sorry theorem mul_conj {d : ℤ} {x : ℤ} {y : ℤ} : mk x y * conj (mk x y) = ↑x * ↑x - ↑d * ↑y * ↑y := sorry theorem conj_mul {d : ℤ} {a : ℤ√d} {b : ℤ√d} : conj (a * b) = conj a * conj b := sorry protected theorem coe_int_add {d : ℤ} (m : ℤ) (n : ℤ) : ↑(m + n) = ↑m + ↑n := ring_hom.map_add (int.cast_ring_hom (ℤ√d)) m n protected theorem coe_int_sub {d : ℤ} (m : ℤ) (n : ℤ) : ↑(m - n) = ↑m - ↑n := ring_hom.map_sub (int.cast_ring_hom (ℤ√d)) m n protected theorem coe_int_mul {d : ℤ} (m : ℤ) (n : ℤ) : ↑(m * n) = ↑m * ↑n := ring_hom.map_mul (int.cast_ring_hom (ℤ√d)) m n protected theorem coe_int_inj {d : ℤ} {m : ℤ} {n : ℤ} (h : ↑m = ↑n) : m = n := sorry /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a : ℕ) (c : ℕ) (b : ℕ) (d : ℕ) := c * a * a ≤ d * b * b theorem sq_le_of_le {c : ℕ} {d : ℕ} {x : ℕ} {y : ℕ} {z : ℕ} {w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left c xz) xz (nat.zero_le z) (nat.zero_le (c * x))) (le_trans xy (mul_le_mul (nat.mul_le_mul_left d yw) yw (nat.zero_le y) (nat.zero_le (d * w)))) theorem sq_le_add_mixed {c : ℕ} {d : ℕ} {x : ℕ} {y : ℕ} {z : ℕ} {w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := sorry theorem sq_le_add {c : ℕ} {d : ℕ} {x : ℕ} {y : ℕ} {z : ℕ} {w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := sorry theorem sq_le_cancel {c : ℕ} {d : ℕ} {x : ℕ} {y : ℕ} {z : ℕ} {w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := sorry theorem sq_le_smul {c : ℕ} {d : ℕ} {x : ℕ} {y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := sorry theorem sq_le_mul {d : ℕ} {x : ℕ} {y : ℕ} {z : ℕ} {w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := sorry /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c : ℕ) (d : ℕ) : ℤ → ℤ → Prop := sorry theorem nonnegg_comm {c : ℕ} {d : ℕ} {x : ℤ} {y : ℤ} : nonnegg c d x y = nonnegg d c y x := sorry theorem nonnegg_neg_pos {c : ℕ} {d : ℕ} {a : ℕ} {b : ℕ} : nonnegg c d (-↑a) ↑b ↔ sq_le a d b c := sorry theorem nonnegg_pos_neg {c : ℕ} {d : ℕ} {a : ℕ} {b : ℕ} : nonnegg c d (↑a) (-↑b) ↔ sq_le b c a d := eq.mpr (id (Eq._oldrec (Eq.refl (nonnegg c d (↑a) (-↑b) ↔ sq_le b c a d)) nonnegg_comm)) nonnegg_neg_pos theorem nonnegg_cases_right {c : ℕ} {d : ℕ} {a : ℕ} {b : ℤ} : (∀ (x : ℕ), b = -↑x → sq_le x c a d) → nonnegg c d (↑a) b := fun (ᾰ : ∀ (x : ℕ), b = -↑x → sq_le x c a d) => int.cases_on b (fun (b : ℕ) (ᾰ : ∀ (x : ℕ), Int.ofNat b = -↑x → sq_le x c a d) => idRhs True trivial) (fun (b : ℕ) (ᾰ : ∀ (x : ℕ), Int.negSucc b = -↑x → sq_le x c a d) => idRhs (sq_le (b + 1) c a d) (ᾰ (b + 1) rfl)) ᾰ theorem nonnegg_cases_left {c : ℕ} {d : ℕ} {b : ℕ} {a : ℤ} (h : ∀ (x : ℕ), a = -↑x → sq_le x d b c) : nonnegg c d a ↑b := cast nonnegg_comm (nonnegg_cases_right h) def norm {d : ℤ} (n : ℤ√d) : ℤ := re n * re n - d * im n * im n @[simp] theorem norm_zero {d : ℤ} : norm 0 = 0 := sorry @[simp] theorem norm_one {d : ℤ} : norm 1 = 1 := sorry @[simp] theorem norm_int_cast {d : ℤ} (n : ℤ) : norm ↑n = n * n := sorry @[simp] theorem norm_nat_cast {d : ℤ} (n : ℕ) : norm ↑n = ↑n * ↑n := norm_int_cast ↑n @[simp] theorem norm_mul {d : ℤ} (n : ℤ√d) (m : ℤ√d) : norm (n * m) = norm n * norm m := sorry theorem norm_eq_mul_conj {d : ℤ} (n : ℤ√d) : ↑(norm n) = n * conj n := sorry protected instance norm.is_monoid_hom {d : ℤ} : is_monoid_hom norm := is_monoid_hom.mk norm_one theorem norm_nonneg {d : ℤ} (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ norm n := sorry theorem norm_eq_one_iff {d : ℤ} {x : ℤ√d} : int.nat_abs (norm x) = 1 ↔ is_unit x := sorry /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg {d : ℕ} : ℤ√↑d → Prop := sorry protected def le {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) := nonneg (b - a) protected instance has_le {d : ℕ} : HasLessEq (ℤ√↑d) := { LessEq := zsqrtd.le } protected def lt {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) := ¬b ≤ a protected instance has_lt {d : ℕ} : HasLess (ℤ√↑d) := { Less := zsqrtd.lt } protected instance decidable_nonnegg (c : ℕ) (d : ℕ) (a : ℤ) (b : ℤ) : Decidable (nonnegg c d a b) := int.cases_on a (fun (a : ℕ) => int.cases_on b (fun (b : ℕ) => eq.mpr sorry (eq.mpr sorry (eq.mpr sorry decidable.true))) fun (b : ℕ) => eq.mpr sorry (eq.mpr sorry (nat.decidable_le (c * (b + 1) * (b + 1)) (d * a * a)))) fun (a : ℕ) => int.cases_on b (fun (b : ℕ) => eq.mpr sorry (eq.mpr sorry (nat.decidable_le (d * (a + 1) * (a + 1)) (c * b * b)))) fun (b : ℕ) => eq.mpr sorry decidable.false protected instance decidable_nonneg {d : ℕ} (a : ℤ√↑d) : Decidable (nonneg a) := sorry protected instance decidable_le {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) : Decidable (a ≤ b) := zsqrtd.decidable_nonneg (b - a) theorem nonneg_cases {d : ℕ} {a : ℤ√↑d} : nonneg a → ∃ (x : ℕ), ∃ (y : ℕ), a = mk ↑x ↑y ∨ a = mk (↑x) (-↑y) ∨ a = mk (-↑x) ↑y := sorry theorem nonneg_add_lem {d : ℕ} {x : ℕ} {y : ℕ} {z : ℕ} {w : ℕ} (xy : nonneg (mk (↑x) (-↑y))) (zw : nonneg (mk (-↑z) ↑w)) : nonneg (mk (↑x) (-↑y) + mk (-↑z) ↑w) := sorry theorem nonneg_add {d : ℕ} {a : ℤ√↑d} {b : ℤ√↑d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := sorry theorem le_refl {d : ℕ} (a : ℤ√↑d) : a ≤ a := (fun (this : nonneg (a - a)) => this) (eq.mpr (id ((fun (ᾰ ᾰ_1 : ℤ√↑d) (e_1 : ᾰ = ᾰ_1) => congr_arg nonneg e_1) (a - a) 0 (sub_self a))) trivial) protected theorem le_trans {d : ℕ} {a : ℤ√↑d} {b : ℤ√↑d} {c : ℤ√↑d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := sorry theorem nonneg_iff_zero_le {d : ℕ} {a : ℤ√↑d} : nonneg a ↔ 0 ≤ a := sorry theorem le_of_le_le {d : ℕ} {x : ℤ} {y : ℤ} {z : ℤ} {w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : mk x y ≤ mk z w := sorry theorem le_arch {d : ℕ} (a : ℤ√↑d) : ∃ (n : ℕ), a ≤ ↑n := sorry protected theorem nonneg_total {d : ℕ} (a : ℤ√↑d) : nonneg a ∨ nonneg (-a) := sorry protected theorem le_total {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) : a ≤ b ∨ b ≤ a := let t : nonneg (b - a) ∨ nonneg (-(b - a)) := zsqrtd.nonneg_total (b - a); eq.mp (Eq._oldrec (Eq.refl (nonneg (b - a) ∨ nonneg (-(b - a)))) ((fun (this : -(b - a) = a - b) => this) (neg_sub b a))) t protected instance preorder {d : ℕ} : preorder (ℤ√↑d) := preorder.mk zsqrtd.le zsqrtd.lt le_refl zsqrtd.le_trans protected theorem add_le_add_left {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) (ab : a ≤ b) (c : ℤ√↑d) : c + a ≤ c + b := (fun (this : nonneg (c + b - (c + a))) => this) (eq.mpr (id (Eq._oldrec (Eq.refl (nonneg (c + b - (c + a)))) (add_sub_add_left_eq_sub b a c))) ab) protected theorem le_of_add_le_add_left {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) (c : ℤ√↑d) (h : c + a ≤ c + b) : a ≤ b := sorry protected theorem add_lt_add_left {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) (h : a < b) (c : ℤ√↑d) : c + a < c + b := fun (h' : c + b ≤ c + a) => h (zsqrtd.le_of_add_le_add_left b a c h') theorem nonneg_smul {d : ℕ} {a : ℤ√↑d} {n : ℕ} (ha : nonneg a) : nonneg (↑n * a) := sorry theorem nonneg_muld {d : ℕ} {a : ℤ√↑d} (ha : nonneg a) : nonneg (sqrtd * a) := sorry theorem nonneg_mul_lem {d : ℕ} {x : ℕ} {y : ℕ} {a : ℤ√↑d} (ha : nonneg a) : nonneg (mk ↑x ↑y * a) := sorry theorem nonneg_mul {d : ℕ} {a : ℤ√↑d} {b : ℤ√↑d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := sorry protected theorem mul_nonneg {d : ℕ} (a : ℤ√↑d) (b : ℤ√↑d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := sorry theorem not_sq_le_succ (c : ℕ) (d : ℕ) (y : ℕ) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt (mul_pos (mul_pos h (nat.succ_pos y)) (nat.succ_pos y)) /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) where ns : ∀ (n : ℕ), x ≠ n * n theorem d_pos {d : ℕ} [dnsq : nonsquare d] : 0 < d := lt_of_le_of_ne (nat.zero_le d) (ne.symm (nonsquare.ns d 0)) theorem divides_sq_eq_zero {d : ℕ} [dnsq : nonsquare d] {x : ℕ} {y : ℕ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := sorry theorem divides_sq_eq_zero_z {d : ℕ} [dnsq : nonsquare d] {x : ℤ} {y : ℤ} (h : x * x = ↑d * y * y) : x = 0 ∧ y = 0 := sorry theorem not_divides_square {d : ℕ} [dnsq : nonsquare d] (x : ℕ) (y : ℕ) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := fun (e : (x + 1) * (x + 1) = d * (y + 1) * (y + 1)) => nat.no_confusion (and.left (divides_sq_eq_zero e)) theorem nonneg_antisymm {d : ℕ} [dnsq : nonsquare d] {a : ℤ√↑d} : nonneg a → nonneg (-a) → a = 0 := sorry theorem le_antisymm {d : ℕ} [dnsq : nonsquare d] {a : ℤ√↑d} {b : ℤ√↑d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero (nonneg_antisymm ba (eq.mpr (id (Eq._oldrec (Eq.refl (nonneg (-(a - b)))) (neg_sub a b))) ab)) protected instance linear_order {d : ℕ} [dnsq : nonsquare d] : linear_order (ℤ√↑d) := linear_order.mk preorder.le preorder.lt sorry sorry le_antisymm zsqrtd.le_total zsqrtd.decidable_le Mathlib.decidable_eq_of_decidable_le Mathlib.decidable_lt_of_decidable_le protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {d : ℕ} [dnsq : nonsquare d] {a : ℤ√↑d} {b : ℤ√↑d} : a * b = 0 → a = 0 ∨ b = 0 := sorry protected instance integral_domain {d : ℕ} [dnsq : nonsquare d] : integral_domain (ℤ√↑d) := integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero protected theorem mul_pos {d : ℕ} [dnsq : nonsquare d] (a : ℤ√↑d) (b : ℤ√↑d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := sorry protected instance linear_ordered_comm_ring {d : ℕ} [dnsq : nonsquare d] : linear_ordered_comm_ring (ℤ√↑d) := linear_ordered_comm_ring.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry linear_order.le linear_order.lt sorry sorry sorry zsqrtd.add_le_add_left sorry zsqrtd.mul_pos sorry linear_order.decidable_le linear_order.decidable_eq linear_order.decidable_lt sorry sorry protected instance linear_ordered_semiring {d : ℕ} [dnsq : nonsquare d] : linear_ordered_semiring (ℤ√↑d) := linear_ordered_comm_ring.to_linear_ordered_semiring protected instance ordered_semiring {d : ℕ} [dnsq : nonsquare d] : ordered_semiring (ℤ√↑d) := ordered_ring.to_ordered_semiring theorem norm_eq_zero {d : ℤ} (h_nonsquare : ∀ (n : ℤ), d ≠ n * n) (a : ℤ√d) : norm a = 0 ↔ a = 0 := sorry theorem hom_ext {R : Type} [comm_ring R] {d : ℤ} (f : ℤ√d →+* R) (g : ℤ√d →+* R) (h : coe_fn f sqrtd = coe_fn g sqrtd) : f = g := sorry /-- The unique `ring_hom` from `ℤ√d` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `ℤ√d →+* R` a value of `√d` in `R`. -/ @[simp] theorem lift_symm_apply_coe {R : Type} [comm_ring R] {d : ℤ} (f : ℤ√d →+* R) : ↑(coe_fn (equiv.symm lift) f) = coe_fn f sqrtd := Eq.refl ↑(coe_fn (equiv.symm lift) f) /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `ℤ` into `R` is injective). -/ theorem lift_injective {R : Type} [comm_ring R] [char_zero R] {d : ℤ} (r : Subtype fun (r : R) => r * r = ↑d) (hd : ∀ (n : ℤ), d ≠ n * n) : function.injective ⇑(coe_fn lift r) := sorry end Mathlib
cac4c2d8820142d2f63d56464739e76e782c4742
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/theories/semilattice.lean
e8dec2b914d1cd53e644aa1ba91cfd86df142c1e
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
2,233
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .semigroup import .monoid namespace algebra signature semilattice (α : Type*) := (op : α → α → α) namespace semilattice_sig variables {α : Type*} (s : semilattice_sig α) @[signature_instance] definition to_semigroup : semigroup_sig α := { op := s.op } end semilattice_sig variables {α : Type*} (s : semilattice_sig α) @[theory] class semilattice : Prop := intro :: (associative : identity.op_associative s.op) (commutative : identity.op_commutative s.op) (idempotent : identity.op_idempotent s.op) namespace semilattice variable [i : semilattice s] include i instance to_comm_semigroup : comm_semigroup s.to_semigroup := comm_semigroup.infer _ end semilattice end algebra namespace algebra signature bounded_semilattice (α : Type*) := (op : α → α → α) (id : α) namespace bounded_semilattice_sig variables {α : Type*} (s : bounded_semilattice_sig α) definition to_semilattice : semilattice_sig α := { op := s.op } @[unify] definition to_semilattice_op_hint (t : semilattice_sig α) : unification_hint := { pattern := t.op =?= s.op , constraints := [t =?= s.to_semilattice] } definition to_monoid : monoid_sig α := { op := s.op , id := s.id } @[unify] definition to_monoid_op_hint (t : monoid_sig α) : unification_hint := { pattern := t.op =?= s.op , constraints := [t =?= s.to_monoid] } @[unify] definition to_monoid_id_hint (t : monoid_sig α) : unification_hint := { pattern := t.id =?= s.id , constraints := [t =?= s.to_monoid] } end bounded_semilattice_sig variables {α : Type*} (s : bounded_semilattice_sig α) @[theory] class bounded_semilattice : Prop := intro :: (associative : identity.op_associative s.op) (commutative : identity.op_commutative s.op) (idempotent : identity.op_idempotent s.op) (right_identity : identity.op_right_identity s.op s.id) namespace bounded_semilattice variable [i : bounded_semilattice s] include i instance to_semilattice : semilattice s.to_semilattice := semilattice.infer _ instance to_comm_monoid : comm_monoid s.to_monoid := comm_monoid.infer _ end bounded_semilattice end algebra
6d9dd9bdc6c72e361b0a81384693ac145d71dfa5
7d5ad87afb17e514aee234fcf0a24412eed6384f
/old/model_vector.lean
bd3a3f876a9b59d0e8de8390677370dde4216d8b
[]
no_license
digama0/flypitch
764f849eaef59c045dfbeca142a0f827973e70c1
2ec14b8da6a3964f09521d17e51f363d255b030f
refs/heads/master
1,586,980,069,651
1,547,078,141,000
1,547,078,283,000
164,965,135
1
0
null
1,547,082,858,000
1,547,082,857,000
null
UTF-8
Lean
false
false
5,520
lean
import .language_term_n_de_bruijn import data.vector import init.data.nat.lemmas open term open formula universe u variable L: Language def prod_n : ∀ (α : Type) (n: nat), Type | α 0 := α | α (n+1) := α × prod_n α n def n_ary_prop := λ α n, (vector α n) → Prop def n_ary_fn := λ α n, (vector α n) → α def map_over_term: ∀ α n, term L (vec n) → (term L atm → α) → vector α n | _ 0 (nil L) _ := vector.nil | α (n+1) (conj _ t ts) f := vector.cons (f t) (map_over_term α n ts f) structure L_Structure := struct :: (L : Language) (A: Type) (const_map : L.consts → A) (rel_map : ∀ n, L.relations n → n_ary_prop A n) (fun_map : ∀ n, L.functions n → n_ary_fn A n) variable S: L_Structure /- this realization function is a little fast and loose. the idea is basically that the term f(v0, v5) should act as if it has SIX free variables, not two. ⟦f(v0,v5)⟧ := λ (x0, x1, x2, x3, x4, x5), ⟦f⟧(x0, x5). the reason for this decision is that this way, we do not need to keep track of what "depth" our term is at in order to find the realization. (keeping track of depth was going to be a major problem in this vector-based implementation, and i suspect in any other where we use de bruijn indices) of course, this means that realization does not respect alpha-equivalence... However, one of the perks of of de bruijn indices is that you don't have to worry about α-equivalence! also I can't get lean to see that vector α j is the same type as vector α (min j (max j k)), but this is hopefully an easy fix. -/ /- added a partially-proven lemma for the bit at the end looks like to finish this we need a lemma which says max(j, k) = j => max(j+1, k) = max(j+1, max(j,k)) then we should be able to just hit with simp I also dislike the whole "include ALL the variables!" thing, but... since we have function extensionality it should be """fine""" (for some definition of fine). --- Jesse -/ lemma min_max_lemma (j k : ℕ) : min j (max j k) = j := begin induction j with j ih, {induction k with k ih, {simp [le_refl]}, {simp [le_refl, zero_lt_one]}}, {induction k with k ih, admit} end mutual def realization_atm, realization_vec with realization_atm : ∀ (t: term S.L atm), (Σ n, (vector S.A n → S.A)) | (const c) := ⟨ 0, λ v, S.const_map c⟩ | (var _ n) := let pf: n < n+1 := begin apply lt_add_of_pos_right, apply zero_lt_one end in ⟨ n+1, λ v: vector S.A (n+1), (v.nth {val := n, is_lt := pf}) ⟩ | (apply n f ts) := have 1 + (n + term_sizeof (S.L) (vec n) ts) < term_sizeof (S.L) atm (apply n f ts), from begin simp [term_sizeof], apply add_lt_add_left, apply add_lt_add_right, apply nat.succ_lt_succ, apply nat.zero_lt_succ end, match realization_vec n ts with | ⟨m, g⟩ := ⟨m, (S.fun_map n f) ∘ g⟩ end with realization_vec: ∀ m (t: term S.L (vec m)), (Σ n, (vector S.A n → vector S.A m)) | 0 (nil L) := ⟨0, λ v, vector.nil⟩ | (n+1) (conj x t ts) := have term_sizeof (S.L) atm t < x + (2 + term_sizeof (S.L) (sum.inr (x + 1)) (conj x t ts)), from begin apply lt_add, simp [term_sizeof], apply lt_add, apply nat.lt_add_of_pos_right, apply add_lt, apply nat.zero_lt_succ end, match realization_atm t with | ⟨j, f⟩ := have 1 + term_sizeof (S.L) (vec x) ts < 2 + term_sizeof (S.L) (sum.inr (x + 1)) (conj x t ts), from begin simp [term_sizeof], apply nat.add_lt_add_left, apply lt_add, apply nat.lt_add_of_pos_left, apply nat.zero_lt_succ end, match realization_vec n ts with | ⟨k, g⟩ := ⟨ max j k, λv, vector.cons (f (vector.take j v)) (g (vector.take k v)) ⟩ end end def realization_formula : formula S.L → (Σ n, (vector S.A n → Prop)) | (equal t1 t2) := match realization_atm S t1 with | ⟨j, f⟩ := match realization_atm S t2 with | ⟨k, g⟩ := ⟨ max j k, λ v, (f (take' S.A j (max j k) (j_lt_max j k) v)) = (g (take' S.A k (max j k) (k_lt_max j k) v))⟩ end end | (atomic n r ts) := match realization_vec S n ts with | ⟨j, f⟩ := ⟨ j, (S.rel_map n r) ∘ f⟩ end | (imp f1 f2) := match realization_formula f1 with | ⟨j, f⟩ := match realization_formula f2 with | ⟨k, g⟩ := ⟨ max j k, λ v, (f ( take' S.A j (max j k ) (j_lt_max j k) v) → (g (take' S.A k (max j k) (k_lt_max j k) v)))⟩ end end | (not f1) := match realization_formula f1 with | ⟨ j, f ⟩ := ⟨j, λ v, ¬ f v⟩ end | (all f1) := match realization_formula f1 with | ⟨0, f⟩ := ⟨0, λ v, (∀ x: S.A, f v) ⟩ | ⟨nat.succ(j), f⟩ := ⟨j, λ v, (∀ x: S.A, f (vector.cons x v)) ⟩ end def sentence := { f : formula S.L // (realization_formula S f).fst = 0} def realization_sentence : sentence S → Prop | ⟨ f, p ⟩ := match realization_formula S f with | ⟨0, g⟩ := g vector.nil | ⟨nat.succ(n), x⟩ := begin apply absurd, apply p, admit end end def soundness: ∀ f: sentence S, prf S.L [] f.1 → realization_sentence S f | f (prf.mp [] [] f' g' pf1 pf2) := begin cases f, simp [realization_sentence], end
3db9b93173ccfd34331f06b373d4f3142aef8663
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/measurable_space_def.lean
c7cf0139715b68d7325fd86ed8028e415accf2ae
[ "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
18,170
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.countable import logic.encodable.lattice import order.conditionally_complete_lattice import order.disjointed import order.symm_diff /-! # Measurable spaces and measurable functions This file defines measurable spaces and measurable functions. 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. Do not add measurability lemmas (which could be tagged with @[measurability]) to this file, since the measurability tactic is downstream from here. Use `measure_theory.measurable_space` instead. ## 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, σ-algebra, measurable function -/ open set encodable function equiv open_locale classical variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (measurable_set' : set α → Prop) (measurable_set_empty : measurable_set' ∅) (measurable_set_compl : ∀ s, measurable_set' s → measurable_set' sᶜ) (measurable_set_Union : ∀ f : ℕ → set α, (∀ i, measurable_set' (f i)) → measurable_set' (⋃ i, f i)) attribute [class] measurable_space instance [h : measurable_space α] : measurable_space αᵒᵈ := h section /-- `measurable_set s` means that `s` is measurable (in the ambient measure space on `α`) -/ def measurable_set [measurable_space α] : set α → Prop := ‹measurable_space α›.measurable_set' localized "notation `measurable_set[` m `]` := @measurable_set _ m" in measure_theory @[simp] lemma measurable_set.empty [measurable_space α] : measurable_set (∅ : set α) := ‹measurable_space α›.measurable_set_empty variable {m : measurable_space α} include m lemma measurable_set.compl : measurable_set s → measurable_set sᶜ := ‹measurable_space α›.measurable_set_compl s lemma measurable_set.of_compl (h : measurable_set sᶜ) : measurable_set s := compl_compl s ▸ h.compl @[simp] lemma measurable_set.compl_iff : measurable_set sᶜ ↔ measurable_set s := ⟨measurable_set.of_compl, measurable_set.compl⟩ @[simp] lemma measurable_set.univ : measurable_set (univ : set α) := by simpa using (@measurable_set.empty α _).compl @[nontriviality] lemma subsingleton.measurable_set [subsingleton α] {s : set α} : measurable_set s := subsingleton.set_cases measurable_set.empty measurable_set.univ s lemma measurable_set.congr {s t : set α} (hs : measurable_set s) (h : s = t) : measurable_set t := by rwa ← h lemma measurable_set.bUnion_decode₂ [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) (n : ℕ) : measurable_set (⋃ b ∈ decode₂ β n, f b) := encodable.Union_decode₂_cases measurable_set.empty h lemma measurable_set.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := begin rw ← encodable.Union_decode₂, exact ‹measurable_space α›.measurable_set_Union _ (measurable_set.bUnion_decode₂ h) end lemma measurable_set.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact measurable_set.Union (by simpa using h) end lemma set.finite.measurable_set_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := measurable_set.bUnion hs.countable h lemma finset.measurable_set_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := s.finite_to_set.measurable_set_bUnion h lemma measurable_set.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h } lemma set.finite.measurable_set_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := measurable_set.sUnion hs.countable h lemma measurable_set.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := by { by_cases p; simp [h, hf, measurable_set.empty] } lemma measurable_set.Inter [encodable β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter, exact measurable_set.Union (λ b, (h b).compl) } section fintype local attribute [instance] fintype.to_encodable lemma measurable_set.Union_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := measurable_set.Union h lemma measurable_set.Inter_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.Inter h end fintype lemma measurable_set.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter₂, exact measurable_set.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.measurable_set_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.bInter hs.countable h lemma finset.measurable_set_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := s.finite_to_set.measurable_set_bInter h lemma measurable_set.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := by { rw sInter_eq_bInter, exact measurable_set.bInter hs h } lemma set.finite.measurable_set_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := measurable_set.sInter hs.countable h lemma measurable_set.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := by { by_cases p; simp [h, hf, measurable_set.univ] } @[simp] lemma measurable_set.union {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₂) := by { rw union_eq_Union, exact measurable_set.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma measurable_set.inter {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma measurable_set.diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma measurable_set.symm_diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∆ s₂) := (h₁.diff h₂).union (h₂.diff h₁) @[simp] lemma measurable_set.ite {t s₁ s₂ : set α} (ht : measurable_set t) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (t.ite s₁ s₂) := (h₁.inter ht).union (h₂.diff ht) @[simp] lemma measurable_set.cond {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) {i : bool} : measurable_set (cond i s₁ s₂) := by { cases i, exacts [h₂, h₁] } @[simp] lemma measurable_set.disjointed {f : ℕ → set α} (h : ∀ i, measurable_set (f i)) (n) : measurable_set (disjointed f n) := disjointed_rec (λ t i ht, measurable_set.diff ht $ h _) (h n) @[simp] lemma measurable_set.const (p : Prop) : measurable_set {a : α | p} := by { by_cases p; simp [h, measurable_set.empty]; apply measurable_set.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ measurable_set t} := ⟨⟨univ, subset_univ s, measurable_set.univ⟩⟩ end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' 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₁.measurable_set' s ↔ m₂.measurable_set' 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 := (measurable_set_singleton : ∀ x, measurable_set ({x} : set α)) export measurable_singleton_class (measurable_set_singleton) attribute [simp] measurable_set_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma measurable_set_eq {a : α} : measurable_set {x | x = a} := measurable_set_singleton a lemma measurable_set.insert {s : set α} (hs : measurable_set s) (a : α) : measurable_set (insert a s) := (measurable_set_singleton a).union hs @[simp] lemma measurable_set_insert {a : α} {s : set α} : measurable_set (insert a s) ↔ measurable_set s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (measurable_set_singleton _), λ h, h.insert a⟩ lemma set.subsingleton.measurable_set {s : set α} (hs : s.subsingleton) : measurable_set s := hs.induction_on measurable_set.empty measurable_set_singleton lemma set.finite.measurable_set {s : set α} (hs : finite s) : measurable_set s := finite.induction_on hs measurable_set.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.measurable_set (s : finset α) : measurable_set (↑s : set α) := s.finite_to_set.measurable_set lemma set.countable.measurable_set {s : set α} (hs : countable s) : measurable_set s := begin rw [← bUnion_of_singleton s], exact measurable_set.bUnion hs (λ b hb, measurable_set_singleton b) end end measurable_singleton_class namespace measurable_space section complete_lattice instance : has_le (measurable_space α) := { le := λ m₁ m₂, m₁.measurable_set' ≤ m₂.measurable_set' } lemma le_def {α} {a b : measurable_space α} : a ≤ b ↔ a.measurable_set' ≤ b.measurable_set' := iff.rfl instance : partial_order (measurable_space α) := { le_refl := assume a b, le_rfl, le_trans := assume a b c hab hbc, le_def.mpr (le_trans hab hbc), le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩, ..measurable_space.has_le } /-- 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 α := { measurable_set' := generate_measurable s, measurable_set_empty := generate_measurable.empty, measurable_set_compl := generate_measurable.compl, measurable_set_Union := generate_measurable.union } lemma measurable_set_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : @measurable_set _ (generate_from s) t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.measurable_set' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (measurable_set_empty m) (assume s _ hs, measurable_set_compl m s hs) (assume f _ hf, measurable_set_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.measurable_set' t} := iff.intro (assume h u hu, h _ $ measurable_set_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_measurable_set [measurable_space α] : generate_from {s : set α | measurable_set s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, measurable_set_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).measurable_set' t} = g) : measurable_space α := { measurable_set' := λ s, s ∈ g, measurable_set_empty := hg ▸ measurable_set_empty _, measurable_set_compl := hg ▸ measurable_set_compl _, measurable_set_Union := hg ▸ measurable_set_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).measurable_set' 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 | @measurable_set α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, measurable_set_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 measurable_set_bot_iff {s : set α} : @measurable_set α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { measurable_set' := λ s, s = ∅ ∨ s = univ, measurable_set_empty := or.inl rfl, measurable_set_compl := by simp [or_imp_distrib] {contextual := tt}, measurable_set_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 ▸ @measurable_set_empty _ ⊥) (λ s, s.symm ▸ @measurable_set.univ _ ⊥), this ▸ iff.rfl @[simp] theorem measurable_set_top {s : set α} : @measurable_set _ ⊤ s := trivial @[simp] theorem measurable_set_inf {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊓ m₂) s ↔ @measurable_set _ m₁ s ∧ @measurable_set _ m₂ s := iff.rfl @[simp] theorem measurable_set_Inf {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Inf ms) s ↔ ∀ m ∈ ms, @measurable_set _ m s := show s ∈ (⋂₀ _) ↔ _, by simp @[simp] theorem measurable_set_infi {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (infi m) s ↔ ∀ i, @measurable_set _ (m i) s := by rw [infi, measurable_set_Inf, forall_range_iff] theorem measurable_set_sup {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.measurable_set' ∪ m₂.measurable_set') s := iff.refl _ theorem measurable_set_Sup {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @measurable_set _ m s} s := begin change @measurable_set' _ (generate_from $ ⋃₀ _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem measurable_set_supr {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @measurable_set _ (m i) s} s := by simp only [supr, measurable_set_Sup, exists_range_iff] end complete_lattice 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 β⦄, measurable_set t → measurable_set (f ⁻¹' t) localized "notation `measurable[` m `]` := @measurable _ _ m _" in measure_theory lemma measurable_id {ma : measurable_space α} : measurable (@id α) := λ t, id lemma measurable_id' {ma : measurable_space α} : measurable (λ a : α, a) := measurable_id lemma measurable.comp {mα : measurable_space α} {mβ : measurable_space β} {mγ : measurable_space γ} {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) @[simp] lemma measurable_const {ma : measurable_space α} {mb : measurable_space β} {a : α} : measurable (λ b : β, a) := assume s hs, measurable_set.const (a ∈ s) lemma measurable.le {α} {m m0 : measurable_space α} {mb : measurable_space β} (hm : m ≤ m0) {f : α → β} (hf : measurable[m] f) : measurable[m0] f := λ s hs, hm _ (hf hs) end measurable_functions
4c8e9b609effdfafb1d35200a289fa4323565bfe
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/transport.lean
65a2cb5f8b75705da1bc914ebc5942d5ee7c4db4
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
3,151
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison definition {u v} transport {A : Type u} { P : A → Type v} {x y : A} (u : P x) (p : x = y) : P y := by induction p; exact u @[simp] lemma {u v} congr_arg_refl {α : Sort u} {β : Sort v} (f : α → β) (a : α) : congr_arg f (eq.refl a) = eq.refl (f a) := begin refl, end @[simp] lemma {u v} congr_fun_refl {α : Sort u} {β : Sort v} (f : α → β) (a : α) : congr_fun (eq.refl f) a = eq.refl (f a) := begin refl, end @[simp] lemma {u v} congr_refl_arg {α : Sort u} {f₁ f₂ : α → Prop} (h₁ : f₁ = f₂) (a : α) : congr h₁ (eq.refl a) = congr_fun h₁ a := begin refl, end @[simp] lemma {u v} congr_refl_fun {α : Sort u} {f : α → Prop} (a b : α) (h : a = b) : congr (eq.refl f) h = congr_arg f h := begin refl, end @[simp] lemma symm_propext {a b : Prop} (p : a ↔ b) : eq.symm (propext p) = propext (p.symm) := by refl @[simp] lemma {u} symm_refl {α : Sort u} (a : α) : eq.symm (eq.refl a) = eq.refl a := by refl @[simp] lemma {u v} symm_congr {α : Sort u} {β : Sort v} {f g : α → β} (h : f = g) {a b : α} (h' : a = b) : eq.symm (congr h h') = congr (eq.symm h) (eq.symm h') := begin refl, end @[simp] lemma {u v} symm_congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : eq.symm (congr_fun h a) = congr_fun (eq.symm h) a := begin refl, end @[simp] lemma {u v} symm_congr_arg {α : Sort u} {β : Sort v} {f : α → β} (a b : α) (h : a = b) : eq.symm (congr_arg f h) = congr_arg f (eq.symm h) := begin refl, end @[simp] lemma {u} symm_trans (a b c : Prop) (p : a = b) (q : b = c) : @eq.symm Prop a c (eq.trans p q) = @eq.trans Prop c b a (eq.symm q) (eq.symm p) := by refl @[simp] lemma {u v w} eq.rec.congr_arg {α : Sort u} {β : Sort v} (f : α → β) {x y : α} {C : β → Sort w} (p : C (f x)) (w : x = y): @eq.rec β (f x) C p _ (congr_arg f w) = @eq.rec α x (λ z, C (f z)) p _ w := begin induction w, refl, end @[simp] lemma {u v} parallel_transport_for_trivial_bundles {α : Sort u} {a b : α} {β : Sort v} (p : a = b) (x : β) : @eq.rec α a (λ a, β) x b p = x := begin induction p, refl, end @[simp] lemma {u l} eq.rec.trans {a b c : Prop} {C : Prop → Sort l} (z : C a) (p : a = b) (q : b = c) : @eq.rec _ a C z c (eq.trans p q) = @eq.rec _ b C (@eq.rec _ a C z b p) c q := begin induction p, induction q, refl, end @[simp] lemma {u} eq.rec.refl {α : Sort u} (a : α) (p : true = (a = a)): @eq.rec Prop true (λ (_x : Prop), _x) trivial (@eq α a a) p = eq.refl a := by refl @[simp] lemma eq.mpr.trans {α β γ: Prop} (p : α = β) (q : β = γ) (g : γ) : eq.mpr (eq.trans p q) g = eq.mpr p (eq.mpr q g) := begin induction p, induction q, refl, end @[simp] lemma {u} eq.mpr.propext {α : Sort u} (a : α) : eq.mpr (propext (eq_self_iff_true a)) trivial = eq.refl a := begin refl, end @[simp] lemma {u} eq.mpr.refl {α : Sort u} (a b : α) (p : a = b) : (eq.mpr (congr_fun (congr_arg eq p) b) (eq.refl b)) = p := begin induction p, refl, end
59d70962eced3e4cedeeba89ff85c2e649e77555
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/Kenny/sandbox.lean
316901ebdcbfee6ec86526134d3b046c5cb1ca59
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
68,536
lean
import sheaves.locally_ringed_space import instances.affine_scheme universes u v w def opens.indefinite_description {α : Type u} [topological_space α] (p : topological_space.opens α → Prop) (hp : ∃ U, p U) : {U // p U} := ⟨⟨↑(classical.some hp), subtype.property _⟩, by rw subtype.coe_eta; exact classical.some_spec hp⟩ def opens.some {α : Type u} [topological_space α] {p : topological_space.opens α → Prop} (hp : ∃ U, p U) : topological_space.opens α := (opens.indefinite_description p hp).1 theorem opens.some_spec {α : Type u} [topological_space α] {p : topological_space.opens α → Prop} (hp : ∃ U, p U) : p (opens.some hp) := (opens.indefinite_description p hp).2 section presheaf_of_rings variables {α : Type u} [topological_space α] variables (F : presheaf_of_rings α) variables (U V : topological_space.opens α) (HVU : V ⊆ U) variables (x y : F U) @[simp] lemma res_add : F.res U V HVU (x + y) = F.res U V HVU x + F.res U V HVU y := is_ring_hom.map_add _ @[simp] lemma res_zero : F.res U V HVU 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma res_neg : F.res U V HVU (-x) = -F.res U V HVU x := is_ring_hom.map_neg _ @[simp] lemma res_sub : F.res U V HVU (x - y) = F.res U V HVU x - F.res U V HVU y := is_ring_hom.map_sub _ @[simp] lemma res_mul : F.res U V HVU (x * y) = F.res U V HVU x * F.res U V HVU y := is_ring_hom.map_mul _ @[simp] lemma res_one : F.res U V HVU 1 = 1 := is_ring_hom.map_one _ end presheaf_of_rings section presheaf_of_rings_on_basis variables {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) variables (F : presheaf_of_rings_on_basis α HB) variables (U V : topological_space.opens α) (HUB : U ∈ B) (HVB : V ∈ B) (HVU : V ⊆ U) variables (x y : F.F HUB) @[simp] lemma bres_add : F.res HUB HVB HVU (x + y) = F.res HUB HVB HVU x + F.res HUB HVB HVU y := is_ring_hom.map_add _ @[simp] lemma bres_zero : F.res HUB HVB HVU 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma bres_neg : F.res HUB HVB HVU (-x) = -F.res HUB HVB HVU x := is_ring_hom.map_neg _ @[simp] lemma bres_sub : F.res HUB HVB HVU (x - y) = F.res HUB HVB HVU x - F.res HUB HVB HVU y := is_ring_hom.map_sub _ @[simp] lemma bres_mul : F.res HUB HVB HVU (x * y) = F.res HUB HVB HVU x * F.res HUB HVB HVU y := is_ring_hom.map_mul _ @[simp] lemma bres_one : F.res HUB HVB HVU 1 = 1 := is_ring_hom.map_one _ end presheaf_of_rings_on_basis theorem is_unit.map {α : Type u} [monoid α] {β : Type v} [monoid β] (f : α → β) [is_monoid_hom f] {x : α} (hx : is_unit x) : is_unit (f x) := let ⟨y, hxy⟩ := hx in ⟨y.map f, by rw [units.coe_map, hxy]⟩ theorem is_unit.map' {α : Type u} [monoid α] {β : Type v} [monoid β] {y : β} (f : α → β) [is_monoid_hom f] (x : α) (hx : is_unit x) (hxy : f x = y) : is_unit y := hxy ▸ hx.map f section opens_comap open topological_space lattice lattice.lattice variables {α : Type u} [topological_space α] variables {β : Type v} [topological_space β] variables {f : α → β} (Hf : continuous f) @[mono] theorem opens.comap_mono' (U V : opens β) (HUV : U ≤ V) : opens.comap Hf U ≤ opens.comap Hf V := set.preimage_mono HUV @[simp] lemma opens.comap_top : opens.comap Hf ⊤ = ⊤ := opens.ext set.preimage_univ end opens_comap namespace topological_space namespace opens variables {X : Type u} [topological_space X] {B : set (opens X)} (HB : is_basis B) def covering_of_is_basis (U : opens X) : covering U := ⟨λ V : { V : opens X // V ∈ B ∧ V ⊆ U }, V, opens.ext $ set.subset.antisymm (set.sUnion_subset $ λ s ⟨t, ⟨V, hVt⟩, hts⟩, hts ▸ hVt ▸ V.2.2) $ let ⟨S, HSB, HUS⟩ := is_basis_iff_cover.1 HB U in HUS.symm ▸ set.sUnion_subset (λ s ⟨V, HVS, HVs⟩, HVs ▸ set.subset_sUnion_of_mem ⟨V, ⟨⟨V, HSB HVS, set.subset_sUnion_of_mem ⟨V, HVS, rfl⟩⟩, rfl⟩, rfl⟩)⟩ variables (B) def of_is_basis (U : opens X) (i : U) : opens X := ⟨@classical.epsilon (opens X) ⟨⊥⟩ (λ V, i.1 ∈ V ∧ V ∈ B ∧ V ⊆ U), subtype.property _⟩ variables {B} theorem of_is_basis_spec {U : opens X} {i : U} : i.1 ∈ of_is_basis B U i ∧ of_is_basis B U i ∈ B ∧ of_is_basis B U i ⊆ U := have ∀ i : U, ∃ V : opens X, i.1 ∈ V ∧ V ∈ B ∧ V ⊆ U, from let ⟨S, HSB, HUS⟩ := is_basis_iff_cover.1 HB U in HUS.symm ▸ λ i, let ⟨t, ⟨V, HVS, rfl⟩, hiV⟩ := set.mem_sUnion.1 i.2 in ⟨V, hiV, HSB HVS, set.subset_sUnion_of_mem ⟨V, HVS, rfl⟩⟩, by rw [of_is_basis, subtype.coe_eta]; exact classical.epsilon_spec (this i) theorem mem_of_is_basis {U : opens X} {i : U} : i.1 ∈ of_is_basis B U i := (of_is_basis_spec HB).1 theorem of_is_basis_mem_basis {U : opens X} {i : U} : of_is_basis B U i ∈ B:= (of_is_basis_spec HB).2.1 theorem of_is_basis_subset {U : opens X} {i : U} : of_is_basis B U i ⊆ U := (of_is_basis_spec HB).2.2 def covering_of_is_basis' (U : opens X) : covering U := ⟨λ i : U, of_is_basis B U i, opens.ext $ set.subset.antisymm (set.sUnion_subset $ λ s ⟨t, ⟨i, hit⟩, hts⟩, hts ▸ hit ▸ (of_is_basis_subset HB)) $ λ i hiu, set.mem_sUnion.2 ⟨of_is_basis B U ⟨i, hiu⟩, set.mem_image_of_mem _ $ set.mem_range_self _, mem_of_is_basis HB⟩⟩ def covering_of_opens (U : opens X) (f : Π i : U, opens X) (hf : ∀ i : U, i.1 ∈ f i) : covering U := ⟨λ i, f i ∩ U, opens.ext $ set.subset.antisymm (set.sUnion_subset $ λ s ⟨t, ⟨i, hit⟩, hts⟩, hts ▸ hit ▸ set.inter_subset_right (f i) U) $ λ i hiu, set.mem_sUnion.2 ⟨f ⟨i, hiu⟩ ∩ U, set.mem_image_of_mem _ $ set.mem_range_self _, hf ⟨i, hiu⟩, hiu⟩⟩ def covering_comap {Y : Type u} [topological_space Y] {f : X → Y} (Hf : continuous f) (V : opens Y) (OC : covering V) : covering (opens.comap Hf V) := { γ := OC.γ, Uis := λ i, opens.comap Hf (OC.Uis i), Hcov := opens.ext $ set.subset.antisymm (set.sUnion_subset $ λ t ⟨U, ⟨V, hVU⟩, hUt⟩, hUt ▸ hVU ▸ set.preimage_mono (subset_covering V)) $ λ i hi, let ⟨V, ⟨U, ⟨j, hjU⟩, hUV⟩, hfiV⟩ := set.mem_sUnion.1 (((set.ext_iff _ _).1 (congr_arg subtype.val OC.Hcov) (f i)).2 hi) in set.mem_sUnion.2 ⟨f ⁻¹' V, ⟨opens.comap Hf ⟨V, hUV ▸ U.2⟩, ⟨j, congr_arg (opens.comap Hf) $ hjU.trans $ by exact subtype.eq hUV⟩, rfl⟩, hfiV⟩ } end opens end topological_space instance presheaf_of_rings.comm_ring {α : Type u} [topological_space α] (f : presheaf_of_rings α) (U : topological_space.opens α) : comm_ring (f U) := f.Fring U instance sheaf_of_rings.comm_ring {α : Type u} [topological_space α] (f : sheaf_of_rings α) (U : topological_space.opens α) : comm_ring (f U) := f.F.Fring U attribute [instance] to_stalk.is_ring_hom attribute [instance] locally_ringed_space.Hstalks attribute [irreducible] sheaf_on_standard_basis.is_sheaf_on_standard_basis def to_Spec_top (R : Type v) [comm_ring R] : R → (Spec.locally_ringed_space R).O ⊤ := to_presheaf_of_rings_extension (D_fs_standard_basis R) (structure_presheaf_on_basis R) (D_fs_standard_basis R).1 ∘ localization.of instance (R : Type v) [comm_ring R] : is_ring_hom (to_Spec_top R) := @@is_ring_hom.comp _ _ _ _ _ _ $ to_presheaf_of_rings_extension.is_ring_hom _ _ structure_presheaf_on_basis_is_sheaf_on_basis _ instance is_maximal_nonunits_ideal {R : Type v} [comm_ring R] (h : is_local_ring R) : (nonunits_ideal h).is_maximal := ideal.is_maximal_iff.2 ⟨one_not_mem_nonunits, λ J x hJ hx hxJ, J.eq_top_iff_one.1 $ J.eq_top_of_is_unit_mem hxJ $ classical.by_contradiction $ hx ∘ mem_nonunits_iff.2⟩ namespace locally_ringed_space variables {X : Type u} [topological_space X] (OX : locally_ringed_space X) def D' (f : OX.O ⊤) : set X := { x | is_unit (to_stalk OX.O.F x ⊤ trivial f) } theorem is_open_D' (f : OX.O ⊤) : is_open (OX.D' f) := begin refine is_open_iff_forall_mem_open.2 (λ x hxf, _), cases is_unit_iff_exists_inv.1 hxf with y hxy, refine quotient.induction_on y (λ g hfg, _) hxy, cases g with U hxU g, rcases quotient.exact hfg with ⟨V, hxV, HVU', HVtop, hfgV⟩, exact ⟨V, λ y hyV, is_unit_iff_exists_inv.2 ⟨to_stalk ((OX.O).F) y U (HVU' hyV).2 g, quotient.sound ⟨V, hyV, HVU', HVtop, hfgV⟩⟩, V.2, hxV⟩ end def D (f : OX.O ⊤) : topological_space.opens X := ⟨OX.D' f, OX.is_open_D' f⟩ theorem is_unit_res_D (f : OX.O ⊤) : is_unit (OX.O.F.res ⊤ (OX.D f) (set.subset_univ _) f) := begin rw is_unit_iff_exists_inv, have : ∀ i : OX.D f, ∃ U : topological_space.opens X, ∃ H : i.1 ∈ U, ∃ g : OX.O U, OX.O.F.res ⊤ U (set.subset_univ U.1) f * g = 1, { refine λ ⟨i, hi⟩, exists.elim (is_unit_iff_exists_inv.1 hi) (λ gq, quotient.induction_on gq $ λ ⟨U, hiU, g⟩ H, let ⟨V, hiV, HVU, HVtop, hfgV⟩ := quotient.exact H in ⟨V, hiV, OX.O.F.res U V (λ j hjv, (HVU hjv).2) g, begin dsimp only at hfgV, rw [res_mul, ← presheaf.Hcomp', ← presheaf.Hcomp'] at hfgV, convert hfgV.trans (res_one _ _ _ _) end⟩), }, choose U hu g hg, have, refine OX.O.gluing (topological_space.opens.covering_of_opens (OX.D f) U hu) _ _, { exact (λ i, OX.O.F.res _ _ (set.inter_subset_left _ _) (g i)) }, { intros j k, dsimp only [res_to_inter_left, res_to_inter_right, topological_space.opens.covering_of_opens], iterate 2 { rw ← presheaf.Hcomp' }, have hj : (U j ∩ D OX f) ∩ (U k ∩ D OX f) ⊆ U j := set.subset.trans (set.inter_subset_left _ _) (set.inter_subset_left _ _), have : set.subset.trans (res_to_inter_left._proof_1 (U j ∩ D OX f) (U k ∩ D OX f)) (set.inter_subset_left ((U j).val) ((D OX f).val)) = hj := rfl, rw this at *, clear this, have hk : (U j ∩ D OX f) ∩ (U k ∩ D OX f) ⊆ U k := set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_left _ _), have : set.subset.trans (res_to_inter_right._proof_1 (U j ∩ D OX f) (U k ∩ D OX f)) (set.inter_subset_left ((U k).val) ((D OX f).val)) = hk := rfl, rw this at *, clear this, have := congr_arg (OX.O.F.res (U k) ((U j ∩ D OX f) ∩ (U k ∩ D OX f)) hk) (hg k), rw [res_mul, res_one] at this, rw [← presheaf.Hcomp', presheaf.Hcomp' _ ⊤ (U j) _ hj (set.subset_univ _)] at this, rw [← mul_one (OX.O.F.res (U j) ((U j ∩ D OX f) ∩ (U k ∩ D OX f)) _ (g j)), ← this], rw [← mul_assoc, ← res_mul, mul_comm (g j), hg j, res_one, one_mul] }, cases this with S hS, use S, apply OX.O.locality (topological_space.opens.covering_of_opens (D OX f) U hu), intros i, specialize hS i, rw [res_mul, hS, ← presheaf.Hcomp'], rw [presheaf.Hcomp' _ ⊤ (U i) ((topological_space.opens.covering_of_opens (D OX f) U hu).Uis i) (set.inter_subset_left ((U i).val) ((D OX f).val)) (set.subset_univ _)], rw [← res_mul, hg, res_one, res_one] end end locally_ringed_space namespace sheaf_of_rings open topological_space variables {X : Type u} [topological_space X] variables {B : set (opens X)} (HB : opens.is_basis B) (Bstd : opens.univ ∈ B ∧ ∀ {U V}, U ∈ B → V ∈ B → U ∩ V ∈ B) variables (O : sheaf_of_rings X) include HB set_option pp.universes true theorem ext (U : opens X) (f g : O U) (hfg : ∀ x ∈ U, to_stalk O.F x U H f = to_stalk O.F x U H g) : f = g := begin have := λ x : U, quotient.exact (hfg x.1 x.2), choose C hc1 hc2 hc3 hc4, refine O.locality (opens.covering_of_opens U C hc1) f g (λ i, _), calc O.F.res U (C i ∩ U) _ f = O.F.res (C i) (C i ∩ U) (set.inter_subset_left _ _) (O.F.res U (C i) _ f) : presheaf.Hcomp' _ _ _ _ _ _ _ ... = O.F.res (C i) (C i ∩ U) _ (O.F.res U (C i) _ g) : congr_arg _ (hc4 i) ... = O.F.res U (C i ∩ U) _ g : (presheaf.Hcomp' _ _ _ _ _ _ _).symm end theorem is_sheaf_on_standard_basis_presheaf_of_rings_to_presheaf_of_rings_on_basis : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd (presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F : presheaf_of_rings_on_basis X HB).to_presheaf_on_basis := begin dsimp only [sheaf_on_standard_basis.is_sheaf_on_standard_basis], intros U HUB OC, exact ⟨O.locality OC.to_covering, O.gluing OC.to_covering⟩ end noncomputable def of_extension_basis (U : opens X) (HUB : U ∈ B) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) : O U := classical.some $ to_presheaf_of_rings_extension.surjective Bstd (presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F) (is_sheaf_on_standard_basis_presheaf_of_rings_to_presheaf_of_rings_on_basis HB Bstd O) HUB f def of_extension.aux1 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) : opens X := opens.some $ f.2 i.1 i.2 theorem of_extension.aux2 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) : of_extension.aux1 HB Bstd U f i ∈ B := classical.some $ opens.some_spec $ f.2 i.1 i.2 theorem of_extension.aux3 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) : i.1 ∈ of_extension.aux1 HB Bstd U f i := classical.some $ classical.some_spec $ opens.some_spec $ f.2 i.1 i.2 noncomputable def of_extension.aux4 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) : F.to_presheaf_on_basis (of_extension.aux2 HB Bstd U f i) := classical.some $ classical.some_spec $ classical.some_spec $ opens.some_spec $ f.2 i.1 i.2 theorem of_extension.aux5 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) : ∀ (y : X) (H : y ∈ U ∩ of_extension.aux1 HB Bstd U f i), f.1 y = λ (_x : y ∈ U), ⟦{U := of_extension.aux1 HB Bstd U f i, BU := _, Hx := H.2, s := of_extension.aux4 HB Bstd U f i}⟧ := classical.some_spec $ classical.some_spec $ classical.some_spec $ opens.some_spec $ f.2 i.1 i.2 theorem of_extension.aux6 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) (y : X) (hyU : y ∈ U) (hyi : y ∈ of_extension.aux1 HB Bstd U f i) : ⟦quotient.out (f.1 y hyU)⟧ = ⟦{U := of_extension.aux1 HB Bstd U f i, BU := _, Hx := hyi, s := of_extension.aux4 HB Bstd U f i}⟧ := by rw [of_extension.aux5 HB Bstd U f i y ⟨hyU, hyi⟩, quotient.out_eq] theorem of_extension.aux7 {F : presheaf_of_rings_on_basis X HB} (U : opens X) (f : (F ᵣₑₓₜ Bstd) U) (i : U) (y : X) (hyU : y ∈ U) (hyi : y ∈ of_extension.aux1 HB Bstd U f i) : quotient.out (f.1 y hyU) ≈ {U := of_extension.aux1 HB Bstd U f i, BU := _, Hx := hyi, s := of_extension.aux4 HB Bstd U f i} := quotient.exact $ of_extension.aux6 HB Bstd U f i y hyU hyi lemma of_extension.aux8 (U : opens X) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) : ∃ f' : O U, ∀ i : U, O.F.res U ((opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) (of_extension.aux3 HB Bstd U f)).Uis i) (subset_covering i) f' = O.F.res (of_extension.aux1 HB Bstd U f i) _ (set.inter_subset_left _ _) (of_extension.aux4 HB Bstd U f i) := begin refine quotient.induction_on (quotient.choice (λ i:U, (f.1 i.1 i.2 : stalk_on_basis ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd (O.F)).to_presheaf_on_basis) i.1))) (λ f', _), have, refine (O.gluing (opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) (of_extension.aux3 HB Bstd U f)) _ _), { exact (λ i, O.F.res _ _ (set.inter_subset_left _ _) $ of_extension.aux4 HB Bstd U f i) }, { have := of_extension.aux7 HB Bstd U f, choose g hg1 hg2 hg3 hg4 hg5, refine (λ j k : U, O.locality (opens.covering_of_opens _ (λ i, g j i.1 i.2.1.2 i.2.1.1 ∩ g k i.1 i.2.2.2 i.2.2.1) (λ i, ⟨hg2 _ _ _ _, hg2 _ _ _ _⟩)) _ _ _), intros i, dsimp only [opens.covering_of_opens, res_to_inter_left, res_to_inter_right], iterate 4 { rw ← presheaf.Hcomp' }, have hg5j := hg5 j i.1 i.2.1.2 i.2.1.1, have hg5k := hg5 k i.1 i.2.2.2 i.2.2.1, dsimp only [presheaf_of_rings_to_presheaf_of_rings_on_basis] at hg5j hg5k, rw [O.F.to_presheaf.Hcomp' (of_extension.aux1 HB Bstd U f j) (g j i.1 i.2.1.2 i.2.1.1), ← hg5j], rw [O.F.to_presheaf.Hcomp' (of_extension.aux1 HB Bstd U f k) (g k i.1 i.2.2.2 i.2.2.1), ← hg5k], iterate 2 { rw ← presheaf.Hcomp' }, { exact set.subset.trans (set.inter_subset_left _ _) (set.inter_subset_right _ _) }, { exact set.subset.trans (set.inter_subset_left _ _) (set.inter_subset_left _ _) } }, exact this end noncomputable def of_extension (U : opens X) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) : O U := classical.some $ of_extension.aux8 HB Bstd O U f lemma of_extension_spec' (U : opens X) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) : ∀ i : U, O.F.res U ((opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) (of_extension.aux3 HB Bstd U f)).Uis i) (subset_covering i) (of_extension HB Bstd O U f) = O.F.res (of_extension.aux1 HB Bstd U f i) _ (set.inter_subset_left _ _) (of_extension.aux4 HB Bstd U f i) := classical.some_spec $ of_extension.aux8 HB Bstd O U f lemma of_extension_spec (U : opens X) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) (x : X) (hxU : x ∈ U) : ∃ (V : opens X) (HVB : V ∈ B) (hxV : x ∈ V) (HVU : V ⊆ U), f.1 x hxU = ⟦⟨V, HVB, hxV, O.F.res U V HVU (of_extension HB Bstd O U f)⟩⟧ := begin have hx : x ∈ of_extension.aux1 HB Bstd U f ⟨x, hxU⟩ ∩ U := ⟨of_extension.aux3 HB Bstd U f ⟨x, hxU⟩, hxU⟩, rcases opens.is_basis_iff_nbhd.1 HB hx with ⟨V, HVB, hxV, HV⟩, refine ⟨V, HVB, hxV, set.subset.trans HV (set.inter_subset_right _ _), _⟩, rw [congr_fun (of_extension.aux5 HB Bstd U f ⟨x, hxU⟩ x ⟨hxU, of_extension.aux3 HB Bstd U f ⟨x, hxU⟩⟩) hxU], refine quotient.sound ⟨V, HVB, hxV, set.subset.trans HV (set.inter_subset_left _ _), set.subset.refl _, _⟩, dsimp only [presheaf_of_rings_to_presheaf_of_rings_on_basis], rw [← presheaf.Hcomp'], calc O.F.res (of_extension.aux1 HB Bstd U f ⟨x, hxU⟩) V _ (of_extension.aux4 HB Bstd U f ⟨x, hxU⟩) = O.F.res ((opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) _).Uis ⟨x, hxU⟩) V _ (O.F.res (of_extension.aux1 HB Bstd U f ⟨x, hxU⟩) ((opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) _).Uis ⟨x, hxU⟩) _ (of_extension.aux4 HB Bstd U f ⟨x, hxU⟩)) : presheaf.Hcomp' _ _ _ _ _ _ _ ... = O.F.res ((opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) _).Uis ⟨x, hxU⟩) V HV (O.F.res U ((opens.covering_of_opens U (of_extension.aux1 HB Bstd U f) _).Uis ⟨x, hxU⟩) _ (of_extension HB Bstd O U f)) : congr_arg _ (of_extension_spec' HB Bstd O U f ⟨x, hxU⟩).symm ... = O.F.res U V _ (of_extension HB Bstd O U f) : (presheaf.Hcomp' _ _ _ _ _ _ _).symm end theorem of_extension_res (U V : opens X) (HVU : V ⊆ U) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) : of_extension HB Bstd O V (presheaf.res _ U V HVU f) = O.F.res U V HVU (of_extension HB Bstd O U f) := begin apply sheaf_of_rings.ext, { exact HB }, intros x hxV, apply quotient.sound, rcases of_extension_spec HB Bstd O U f x (HVU hxV) with ⟨W1, HWB1, hxW1, HWU1, hw1⟩, rcases of_extension_spec HB Bstd O V (presheaf.res _ U V HVU f) x hxV with ⟨W2, HWB2, hxW2, HWV2, hw2⟩, rcases quotient.exact (hw1.symm.trans hw2) with ⟨W3, HWB3, hxW3, HW31, HW32, hw3⟩, refine ⟨W3, hxW3, set.subset.trans HW32 HWV2, set.subset.trans HW32 HWV2, _⟩, change O.F.res W1 W3 HW31 (O.F.res U W1 HWU1 (of_extension HB Bstd O U f)) = O.F.res W2 W3 HW32 (O.F.res V W2 HWV2 (of_extension HB Bstd O V $ presheaf.res _ U V HVU f)) at hw3, change O.F.res V W3 _ (of_extension HB Bstd O V $ presheaf.res _ U V HVU f) = (O.F.res V W3 _ (O.F.res U V HVU (of_extension HB Bstd O U f))), rw [← presheaf.Hcomp', ← presheaf.Hcomp'] at hw3, rw [← presheaf.Hcomp'], exact hw3.symm end set_option pp.proofs true def to_extension (U : opens X) (f : O U) : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F : presheaf_of_rings_on_basis X HB)ᵣₑₓₜ Bstd) U := { val := λ x hxU, ⟦{ U := opens.some (opens.is_basis_iff_nbhd.1 HB hxU), BU := classical.some $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hxU), Hx := (classical.some_spec $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hxU)).1, s := O.F.res _ _ (classical.some_spec $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hxU)).2 f }⟧, property := λ x hxU, ⟨opens.some (opens.is_basis_iff_nbhd.1 HB hxU), classical.some $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hxU), (classical.some_spec $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hxU)).1, O.F.res _ _ (classical.some_spec $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hxU)).2 f, λ y hy, funext $ λ hyU, have y ∈ opens.some (opens.is_basis_iff_nbhd.1 HB hxU) ∩ opens.some (opens.is_basis_iff_nbhd.1 HB hyU), from ⟨hy.2, (classical.some_spec $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB hyU)).1⟩, let ⟨V, HVB, hyV, HV⟩ := opens.is_basis_iff_nbhd.1 HB this in quotient.sound $ ⟨V, HVB, hyV, set.subset.trans HV (set.inter_subset_right _ _), set.subset.trans HV (set.inter_subset_left _ _), show O.F.res _ _ _ (O.F.res _ _ _ _) = O.F.res _ _ _ (O.F.res _ _ _ _), by rw [← presheaf.Hcomp', ← presheaf.Hcomp']⟩⟩ } theorem of_to_extension (U : opens X) (f : O U) : of_extension HB Bstd O U (to_extension HB Bstd O U f) = f := begin apply sheaf_of_rings.ext, { exact HB }, intros x hxU, rcases of_extension_spec HB Bstd O U (to_extension HB Bstd O U f) x hxU with ⟨V, HVB, hsV, HVU, hv⟩, rcases quotient.exact hv with ⟨W, HWB, hxW, HW1, HW2, hw⟩, refine quotient.sound ⟨W, hxW, set.subset.trans HW2 HVU, set.subset.trans HW2 HVU, _⟩, change O.F.res _ _ _ (O.F.res _ _ _ _) = O.F.res _ _ _ (O.F.res _ _ _ _) at hw, rw [← presheaf.Hcomp', ← presheaf.Hcomp'] at hw, exact hw.symm end theorem to_of_extension (U : opens X) (f : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) : to_extension HB Bstd O U (of_extension HB Bstd O U f) = f := subtype.eq $ funext $ λ x, funext $ λ hxU, eq.symm $ let ⟨V, HVB, hxV, HVU, hv⟩ := of_extension_spec HB Bstd O U f x hxU in have x ∈ V ∩ classical.some (to_extension._proof_1 HB U x hxU) := ⟨hxV, to_extension._proof_3 HB U x hxU⟩, let ⟨W, HWB, hxW, HWV⟩ := opens.is_basis_iff_nbhd.1 HB this in hv.trans $ quotient.sound ⟨W, HWB, hxW, set.subset.trans HWV (set.inter_subset_left _ _), set.subset.trans HWV (set.inter_subset_right _ _), show O.F.res _ _ _ (O.F.res _ _ _ _) = O.F.res _ _ _ (O.F.res _ _ _ _), by rw [← presheaf.Hcomp', ← presheaf.Hcomp']⟩ instance is_ring_hom_to_extension (U : opens X) : is_ring_hom (to_extension HB Bstd O U) := { map_one := subtype.eq $ funext $ λ x, funext $ λ hxU, quotient.sound ⟨opens.some (to_extension._proof_1 HB U x hxU), to_extension._proof_2 HB U x hxU, to_extension._proof_3 HB U x hxU, set.subset.refl _, set.subset_univ _, show O.F.res _ _ _ (O.F.res _ _ _ 1) = O.F.res _ _ _ 1, by rw [res_one, res_one, res_one]⟩, map_mul := λ s1 s2, subtype.eq $ funext $ λ x, funext $ λ hxU, quotient.sound ⟨opens.some (to_extension._proof_1 HB U x hxU), to_extension._proof_2 HB U x hxU, to_extension._proof_3 HB U x hxU, set.subset.refl _, set.subset_inter (set.subset.refl _) (set.subset.refl _), show O.F.res _ _ _ (O.F.res _ _ _ (s1 * s2)) = O.F.res _ _ _ (O.F.res _ _ _ (O.F.res _ _ _ _) * O.F.res _ _ _ (O.F.res _ _ _ _)), by iterate 3 { rw res_mul }; iterate 6 { rw ← presheaf.Hcomp' }⟩, map_add := λ s1 s2, subtype.eq $ funext $ λ x, funext $ λ hxU, quotient.sound ⟨opens.some (to_extension._proof_1 HB U x hxU), to_extension._proof_2 HB U x hxU, to_extension._proof_3 HB U x hxU, set.subset.refl _, set.subset_inter (set.subset.refl _) (set.subset.refl _), show O.F.res _ _ _ (O.F.res _ _ _ (s1 + s2)) = O.F.res _ _ _ (O.F.res _ _ _ (O.F.res _ _ _ _) + O.F.res _ _ _ (O.F.res _ _ _ _)), by iterate 3 { rw res_add }; iterate 6 { rw ← presheaf.Hcomp' }⟩ } noncomputable def ring_equiv_extension (U : opens X) : O U ≃r ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U := { to_fun := to_extension HB Bstd O U, inv_fun := of_extension HB Bstd O U, left_inv := of_to_extension HB Bstd O U, right_inv := to_of_extension HB Bstd O U, hom := sheaf_of_rings.is_ring_hom_to_extension HB Bstd O U } instance is_ring_hom_of_extension (U : opens X) : is_ring_hom (of_extension HB Bstd O U) := (ring_equiv_extension HB Bstd O U).symm.hom def stalk_on_basis_to_stalk (F : presheaf_of_rings X) (U : opens X) (p : X) (hpU : p ∈ U) (σ : stalk_on_basis (presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd F : presheaf_of_rings_on_basis X HB).to_presheaf_on_basis p) : stalk_of_rings F p := quotient.lift_on σ (λ e, to_stalk F p e.U e.Hx e.s) $ λ e₁ e₂ ⟨V, HVB, hpV, HV1, HV2, HV⟩, quotient.sound ⟨V, hpV, HV1, HV2, HV⟩ def stalk_to_stalk_on_basis (F : presheaf_of_rings.{u v} X) (U : opens X) (p : X) (hpU : p ∈ U) (σ : stalk_of_rings F p) : stalk_on_basis (presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd F : presheaf_of_rings_on_basis X HB).to_presheaf_on_basis p := quotient.lift_on σ (λ e, (⟦⟨opens.some (opens.is_basis_iff_nbhd.1 HB e.HxU), Exists.fst $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB e.HxU), and.left $ Exists.snd $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB e.HxU), presheaf.res _ _ _ (and.right $ Exists.snd $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB e.HxU)) e.s⟩⟧ : stalk_on_basis (presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd F : presheaf_of_rings_on_basis X HB).to_presheaf_on_basis p)) $ λ e₁ e₂ ⟨V, hpV, HV1, HV2, HV⟩, have p ∈ V ∩ (opens.some (opens.is_basis_iff_nbhd.1 HB e₁.HxU) ∩ opens.some (opens.is_basis_iff_nbhd.1 HB e₂.HxU)), from ⟨hpV, and.left $ Exists.snd $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB e₁.HxU), and.left $ Exists.snd $ opens.some_spec (opens.is_basis_iff_nbhd.1 HB e₂.HxU)⟩, let ⟨W, HWB, hpW, HWV⟩ := opens.is_basis_iff_nbhd.1 HB this in quotient.sound ⟨W, HWB, hpW, set.subset.trans HWV (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_left _ _)), set.subset.trans HWV (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_right _ _)), have _ := congr_arg (F.res _ W (set.subset.trans HWV (set.inter_subset_left _ _))) HV, show F.res _ _ _ (F.res _ _ _ _) = F.res _ _ _ (F.res _ _ _ _), by rw [← presheaf.Hcomp', ← presheaf.Hcomp'] at this ⊢; exact this⟩ theorem to_stalk_of_extension (U : opens X) (F : ((presheaf_of_rings_to_presheaf_of_rings_on_basis Bstd O.F)ᵣₑₓₜ Bstd) U) (p : X) (hpU : p ∈ U) : to_stalk O.F p U hpU (of_extension HB Bstd O U F) = stalk_on_basis_to_stalk _ _ _ U _ hpU (F.1 p hpU) := let ⟨V, HVB, hpV, HVU, hv⟩ := of_extension_spec HB Bstd O U F p hpU in hv.symm ▸ quotient.sound ⟨V, hpV, HVU, set.subset.refl V, presheaf.Hcomp' _ _ _ _ _ _ _⟩ end sheaf_of_rings namespace sheaf_of_rings variables {α : Type u} [topological_space α] variables {β : Type u} [topological_space β] variables {f : α → β} (Hf : continuous f) def pushforward (O : sheaf_of_rings α) : sheaf_of_rings β := { F := O.F.pushforward Hf, locality := λ U OC s t H, O.locality (topological_space.opens.covering_comap Hf U OC) _ _ (λ i, by convert H i), gluing := λ U OC s H, by convert O.gluing (topological_space.opens.covering_comap Hf U OC) s H } end sheaf_of_rings theorem presheaf.fmap.commutes' {α : Type u} [topological_space α] {β : Type v} [topological_space β] {f : α → β} {hf : continuous f} {F : presheaf α} {G : presheaf β} (m : presheaf.fmap hf F G) (U V : topological_space.opens β) (HVU : V ⊆ U) (s : G U) (h : opens.comap hf V ⊆ opens.comap hf U) : F.res (opens.comap hf U) (opens.comap hf V) h (m.map U s) = m.map V (G.res U V HVU s) := (congr_fun (m.commutes U V HVU) s).symm def presheaf.fmap.stalk {α : Type u} [topological_space α] {β : Type v} [topological_space β] {f : α → β} {hf : continuous f} {F : presheaf α} {G : presheaf β} (m : presheaf.fmap hf F G) (x : α) : stalk G (f x) → stalk F x := quotient.lift (λ s : stalk.elem G (f x), (⟦⟨opens.comap hf s.U, s.HxU, m.map s.U s.s⟩⟧ : stalk F x)) $ λ s1 s2 ⟨U, hfxU, HUs1, HUs2, HU⟩, quotient.sound ⟨opens.comap hf U, hfxU, opens.comap_mono _ _ _ HUs1, opens.comap_mono _ _ _ HUs2, show F.res (opens.comap hf s1.U) (opens.comap hf U) _ (m.map s1.U s1.s) = F.res (opens.comap hf s2.U) (opens.comap hf U) _ (m.map s2.U s2.s), by rw [m.commutes', m.commutes', HU]⟩ def presheaf.fmap.stalk_of_rings {α : Type u} [topological_space α] {β : Type v} [topological_space β] {f : α → β} {hf : continuous f} {F : presheaf_of_rings α} {G : presheaf_of_rings β} (m : presheaf_of_rings.fmap hf F G) (x : α) (s : stalk_of_rings G (f x)) : stalk_of_rings F x := m.stalk x s theorem is_ring_hom_stalk_of_rings {α : Type u} [topological_space α] {β : Type v} [topological_space β] {f : α → β} {hf : continuous f} {F : presheaf_of_rings α} {G : presheaf_of_rings β} (m : presheaf_of_rings.fmap hf F G) [hm : ∀ U, is_ring_hom (m.map U)] (x : α) : is_ring_hom (presheaf.fmap.stalk_of_rings m x) := { map_one := quotient.sound ⟨⊤, trivial, set.subset.refl _, set.subset.refl _, congr_arg _ (is_ring_hom.map_one (m.map ⊤))⟩, map_mul := λ s1 s2, quotient.induction_on₂ s1 s2 $ λ e1 e2, quotient.sound ⟨opens.comap hf (e1.U ∩ e2.U), ⟨e1.HxU, e2.HxU⟩, set.subset.refl _, set.subset_inter (opens.comap_mono _ _ _ (set.inter_subset_left _ _)) (opens.comap_mono _ _ _ (set.inter_subset_right _ _)), show F.res (opens.comap hf (e1.U ∩ e2.U)) (opens.comap hf (e1.U ∩ e2.U)) _ (m.map (e1.U ∩ e2.U) (G.res _ _ _ e1.s * G.res _ _ _ e2.s)) = F.res (opens.comap hf e1.U ∩ opens.comap hf e2.U) (opens.comap hf (e1.U ∩ e2.U)) _ (F.res _ _ _ (m.map e1.U e1.s) * F.res _ _ _ (m.map e2.U e2.s)), by rw [m.commutes' _ _ (set.subset.refl _), res_mul, is_ring_hom.map_mul (F.res (opens.comap hf e1.U ∩ opens.comap hf e2.U) (opens.comap hf (e1.U ∩ e2.U)) (set.subset_inter (opens.comap_mono _ _ _ (set.inter_subset_left _ _)) (opens.comap_mono _ _ _ (set.inter_subset_right _ _)))), ← presheaf.Hcomp', ← presheaf.Hcomp', ← presheaf.Hcomp', ← presheaf.Hcomp', m.commutes' e1.U (e1.U ∩ e2.U) (set.inter_subset_left _ _), m.commutes' e2.U (e1.U ∩ e2.U) (set.inter_subset_right _ _), is_ring_hom.map_mul (m.map (e1.U ∩ e2.U))]; refl⟩, map_add := λ s1 s2, quotient.induction_on₂ s1 s2 $ λ e1 e2, quotient.sound ⟨opens.comap hf (e1.U ∩ e2.U), ⟨e1.HxU, e2.HxU⟩, set.subset.refl _, set.subset_inter (opens.comap_mono _ _ _ (set.inter_subset_left _ _)) (opens.comap_mono _ _ _ (set.inter_subset_right _ _)), show F.res (opens.comap hf (e1.U ∩ e2.U)) (opens.comap hf (e1.U ∩ e2.U)) _ (m.map (e1.U ∩ e2.U) (G.res _ _ _ e1.s + G.res _ _ _ e2.s)) = F.res (opens.comap hf e1.U ∩ opens.comap hf e2.U) (opens.comap hf (e1.U ∩ e2.U)) _ (F.res _ _ _ (m.map e1.U e1.s) + F.res _ _ _ (m.map e2.U e2.s)), by rw [m.commutes' _ _ (set.subset.refl _), is_ring_hom.map_add (G.res (e1.U ∩ e2.U) (e1.U ∩ e2.U) (set.subset.refl _)), is_ring_hom.map_add (F.res (opens.comap hf e1.U ∩ opens.comap hf e2.U) (opens.comap hf (e1.U ∩ e2.U)) (set.subset_inter (opens.comap_mono _ _ _ (set.inter_subset_left _ _)) (opens.comap_mono _ _ _ (set.inter_subset_right _ _)))), ← presheaf.Hcomp', ← presheaf.Hcomp', ← presheaf.Hcomp', ← presheaf.Hcomp', m.commutes' e1.U (e1.U ∩ e2.U) (set.inter_subset_left _ _), m.commutes' e2.U (e1.U ∩ e2.U) (set.inter_subset_right _ _), is_ring_hom.map_add (m.map (e1.U ∩ e2.U))]; refl⟩ } namespace locally_ringed_space structure morphism {X : Type u} [topological_space X] (OX : locally_ringed_space X) {Y : Type v} [topological_space Y] (OY : locally_ringed_space Y) extends morphism OX OY := (hom : ∀ U, is_ring_hom (fO.map U)) (hlocal : ∀ x s, is_unit (presheaf.fmap.stalk_of_rings fO x s) → is_unit s) attribute [instance] morphism.hom end locally_ringed_space section tag01I1 variables {X : Type u} [topological_space X] (OX : locally_ringed_space X) variables (R : Type v) [comm_ring R] /- https://stacks.math.columbia.edu/tag/01I1 -/ def mor_to_hom (f : OX.morphism (Spec.locally_ringed_space R)) : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤ := OX.O.F.res (opens.comap f.Hf ⊤) ⊤ (opens.comap_top f.Hf ▸ set.subset.refl _) ∘ f.fO.map ⊤ instance mor_to_hom.is_ring_hom (f : OX.morphism (Spec.locally_ringed_space R)) : is_ring_hom (mor_to_hom OX R f) := by unfold mor_to_hom; apply_instance variables (f : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤) [is_ring_hom f] def induced (x : X) : Spec R := ⟨ideal.comap (to_stalk OX.O.F x ⊤ trivial ∘ f ∘ to_Spec_top R) (nonunits_ideal $ OX.Hstalks x), @ideal.is_prime.comap _ _ _ _ _ _ _ $ (is_maximal_nonunits_ideal _).is_prime⟩ @[simp] lemma Spec.DO.val (g : R) : (Spec.DO R g).val = Spec.D' g := congr_fun (Spec.DO.val_eq_D' R) g @[simp] lemma induced_preimage_D' (g : R) : induced OX R f ⁻¹' Spec.D' g = OX.D (f $ to_Spec_top R g) := set.ext $ λ x, classical.not_not lemma induced_continuous : continuous (induced OX R f) := λ U HU, let ⟨Us, HUs, HUUs⟩ := topological_space.sUnion_basis_of_is_open (D_fs_basis R) HU in by rw [HUUs, set.preimage_sUnion]; exact is_open_Union (λ S, is_open_Union $ λ HSUs, let ⟨p, ⟨g, hp⟩, hpS⟩ := HUs HSUs in by rw [← hpS, hp, Spec.DO.val, induced_preimage_D']; exact OX.is_open_D' _) @[simp] lemma comap_induced_DO (g : R) : opens.comap (induced_continuous OX R f) (Spec.DO R g) = OX.D (f $ to_Spec_top R g) := topological_space.opens.ext $ induced_preimage_D' OX R f g noncomputable def induced_basis (U : topological_space.opens $ Spec R) (HUB : U ∈ D_fs R) : (structure_presheaf_on_basis R).F HUB → OX.O (opens.comap (induced_continuous OX R f) U) := localization.lift (OX.O.F.res ⊤ _ (set.subset_univ _) ∘ f ∘ to_Spec_top R) $ λ r hrSU, is_unit.map' (OX.O.F.res (opens.comap (induced_continuous OX R f) (Spec.DO R r)) (opens.comap (induced_continuous OX R f) U) (set.preimage_mono hrSU)) (OX.O.F.res ⊤ _ (set.subset_univ _) (f $ to_Spec_top R r)) (by rw comap_induced_DO; exact locally_ringed_space.is_unit_res_D _ _) (presheaf.Hcomp' _ _ _ _ _ _ _).symm noncomputable def induced_stalk_elem (p : Spec R) (s : stalk_on_basis.elem (structure_presheaf_on_basis R).to_presheaf_on_basis p) : stalk_on_basis.elem (presheaf_of_rings_to_presheaf_of_rings_on_basis (D_fs_standard_basis R) (presheaf_of_rings.pushforward (induced_continuous OX R f) OX.O.F) : presheaf_of_rings_on_basis (Spec R) (D_fs_basis R)).to_presheaf_on_basis p := ⟨s.1, s.2, s.3, induced_basis OX R f s.1 s.2 s.4⟩ noncomputable def induced_stalk (p : Spec R) : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis R) (structure_presheaf_on_basis R) p → stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis R) (presheaf_of_rings_to_presheaf_of_rings_on_basis (D_fs_standard_basis R) (presheaf_of_rings.pushforward (induced_continuous OX R f) OX.O.F) : presheaf_of_rings_on_basis (Spec R) (D_fs_basis R)) p := quotient.lift (λ s, ⟦induced_stalk_elem OX R f p s⟧) $ begin rintros s1 s2 ⟨U, HUB, hpU, hUs1, hUs2, hs⟩, refine quotient.sound ⟨U, HUB, hpU, hUs1, hUs2, _⟩, cases s1 with U1 HUB1 Hx1 s1, cases s2 with U2 HUB2 Hx2 s2, dsimp only at hUs1 hUs2, dsimp only [induced_stalk_elem, induced_basis], revert hs, refine localization.induction_on s1 (λ r1 s1, localization.induction_on s2 (λ r2 s2, _)), intros hs, rcases quotient.exact hs with ⟨t, htSU, ht⟩, simp only [subtype.coe_mk] at ht, dsimp only [induced_stalk_elem, induced_basis, localization.lift, localization.lift'_mk, function.comp_apply, presheaf_of_rings_to_presheaf_of_rings_on_basis, presheaf_of_rings.pushforward, presheaf.pushforward], rw [is_ring_hom.map_mul (OX.O.F.res (opens.comap (induced_continuous OX R f) U1) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono (induced_continuous OX R f) U U1 hUs1))], rw [is_ring_hom.map_mul (OX.O.F.res (opens.comap (induced_continuous OX R f) U2) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono (induced_continuous OX R f) U U2 hUs2))], generalize : localization.lift._proof_1 _ _ _ = hu1, generalize : localization.lift._proof_1 _ _ _ = hu2, dsimp only [function.comp_apply] at hu1 hu2, have := classical.some_spec hu2, revert this, have := classical.some_spec hu1, revert this, cases classical.some hu1 with v1 i1 hvi1 hiv1, cases classical.some hu2 with v2 i2 hvi2 hiv2, rintros h1 h2, change _ = v1 at h1, subst h1, change _ = v2 at h2, subst h2, change _ * OX.O.F.res _ _ _ i1 = _ * OX.O.F.res _ _ _ i2, replace ht := congr_arg (λ x, OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _) (f (to_Spec_top R x))) ht, dsimp only at ht, rw [is_ring_hom.map_mul (to_Spec_top R)] at ht, rw [is_ring_hom.map_sub (to_Spec_top R)] at ht, rw [is_ring_hom.map_mul (to_Spec_top R)] at ht, rw [is_ring_hom.map_mul (to_Spec_top R)] at ht, rw [is_ring_hom.map_zero (to_Spec_top R)] at ht, rw [is_ring_hom.map_mul f] at ht, rw [is_ring_hom.map_sub f] at ht, rw [is_ring_hom.map_mul f] at ht, rw [is_ring_hom.map_mul f] at ht, rw [is_ring_hom.map_zero f] at ht, rw [is_ring_hom.map_mul (OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _))] at ht, rw [is_ring_hom.map_sub (OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _))] at ht, rw [is_ring_hom.map_mul (OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _))] at ht, rw [is_ring_hom.map_mul (OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _))] at ht, change _ = OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _) 0 at ht, rw [is_ring_hom.map_zero (OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ _))] at ht, have := OX.is_unit_res_D (f (to_Spec_top R t)), rw ← comap_induced_DO at this, replace this := this.map (OX.O.F.res (opens.comap (induced_continuous OX R f) (Spec.DO R t)) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ htSU)), rw ← presheaf.Hcomp' at this, cases this with u hut, change (((OX.O).F).to_presheaf).res ⊤ (opens.comap (induced_continuous OX R f) U) (set.subset_univ ((opens.comap (induced_continuous OX R f) U).val)) (f (to_Spec_top R t)) = _ at hut, rw hut at ht, replace ht := congr_arg (λ z : OX.O (opens.comap (induced_continuous OX R f) U), z * (↑(u⁻¹ : units (OX.O (opens.comap (induced_continuous OX R f) U))) : OX.O _)) ht, dsimp only at ht, change _ = (0 : OX.O (opens.comap (induced_continuous OX R f) U)) * _ at ht, rw [mul_assoc, zero_mul, units.mul_inv, mul_one, sub_eq_zero_iff_eq] at ht, rw [← presheaf.Hcomp', presheaf.Hcomp' _ ⊤ (opens.comap (induced_continuous OX R f) U2) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs2) (set.subset_univ _)], rw [← mul_one (OX.O.F.res ⊤ (opens.comap (induced_continuous OX R f) U2) (set.subset_univ _) (f (to_Spec_top R r1)))], change (OX.O.F.res _ _ _ (_ * (1 : OX.O (opens.comap _ U2)))) * _ = _, rw [← hvi2, ← mul_assoc, mul_comm (OX.O.F.res _ _ _ (f _))], rw [is_ring_hom.map_mul (OX.O.F.res (opens.comap (induced_continuous OX R f) U2) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs2))], rw [is_ring_hom.map_mul (OX.O.F.res (opens.comap (induced_continuous OX R f) U2) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs2))], rw [← presheaf.Hcomp', ← presheaf.Hcomp', show set.subset.trans (opens.comap_mono (induced_continuous OX R f) U U2 hUs2) (induced_basis._proof_1 OX R f U2) = set.subset_univ _, from rfl, ← ht], rw [mul_assoc, mul_assoc, mul_comm, mul_assoc, mul_assoc], replace hiv1 := congr_arg (OX.O.F.res (opens.comap (induced_continuous OX R f) U1) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs1)) hiv1, rw [is_ring_hom.map_mul (OX.O.F.res (opens.comap (induced_continuous OX R f) U1) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs1))] at hiv1, change _ = OX.O.F.res (opens.comap (induced_continuous OX R f) U1) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs1) 1 at hiv1, rw [is_ring_hom.map_one (OX.O.F.res (opens.comap (induced_continuous OX R f) U1) (opens.comap (induced_continuous OX R f) U) (opens.comap_mono _ _ _ hUs1))] at hiv1, rw [← presheaf.Hcomp', show set.subset.trans (opens.comap_mono (induced_continuous OX R f) U U1 hUs1) (induced_basis._proof_1 OX R f U1) = set.subset_univ _, from rfl] at hiv1, rw [hiv1, mul_one, ← presheaf.Hcomp'], refl end noncomputable def induced_sheafification {X : Type u} [topological_space X] (OX : locally_ringed_space X) (R : Type u) [comm_ring R] (f : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤) [is_ring_hom f] (U : topological_space.opens (Spec R)) (s : (Spec.locally_ringed_space R).O U) : ((presheaf_of_rings_to_presheaf_of_rings_on_basis (D_fs_standard_basis R) (OX.O.pushforward (induced_continuous OX R f)).F : presheaf_of_rings_on_basis (Spec R) (D_fs_basis R))ᵣₑₓₜ (D_fs_standard_basis R)) U := ⟨λ x hxU, induced_stalk OX R f x (s.1 x hxU), λ x hxU, let ⟨V, HVB, hxV, s1, hs1⟩ := s.2 x hxU in ⟨V, HVB, hxV, induced_basis OX R f V HVB s1, λ g hg, funext $ λ hgU, by rw hs1 g hg; refl⟩⟩ theorem induced_sheafification_to_presheaf_of_rings_extension {X : Type u} [topological_space X] (OX : locally_ringed_space X) (R : Type u) [comm_ring R] (f : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤) [is_ring_hom f] (U : topological_space.opens (Spec R)) (HUB : U ∈ D_fs R) (σ : (structure_presheaf_on_basis R).F HUB) : induced_sheafification OX R f U (to_presheaf_of_rings_extension (D_fs_standard_basis R) _ HUB σ) = sheaf_of_rings.to_extension _ _ _ _ (induced_basis OX R _ _ HUB σ) := subtype.eq $ funext $ λ p, funext $ λ hpU, quotient.sound ⟨U ∩ opens.some (sheaf_of_rings.to_extension._proof_1 (D_fs_basis R) U p hpU), (D_fs_standard_basis R).2 HUB (sheaf_of_rings.to_extension._proof_2 (D_fs_basis R) U p hpU), ⟨hpU, (sheaf_of_rings.to_extension._proof_3 (D_fs_basis R) U p hpU)⟩, set.inter_subset_left _ _, set.inter_subset_right _ _, presheaf.Hcomp' _ _ _ _ _ _ _⟩ instance is_ring_hom_induced_basis (U : topological_space.opens $ Spec R) (HUB : U ∈ D_fs R) : is_ring_hom (induced_basis OX R f U HUB) := localization.lift.is_ring_hom _ _ theorem induced_basis_res (U V : topological_space.opens $ Spec R) (HUB : U ∈ D_fs R) (HVB : V ∈ D_fs R) (HVU : V ⊆ U) (s : ((structure_presheaf_on_basis R).to_presheaf_on_basis).F HUB) : induced_basis OX R f V HVB (presheaf_on_basis.res _ HUB HVB HVU s) = OX.O.F.res (opens.comap (induced_continuous OX R f) U) (opens.comap (induced_continuous OX R f) V) (opens.comap_mono _ _ _ HVU) (induced_basis OX R f U HUB s) := suffices induced_basis OX R f V HVB ∘ presheaf_on_basis.res _ HUB HVB HVU = OX.O.F.res (opens.comap (induced_continuous OX R f) U) (opens.comap (induced_continuous OX R f) V) (opens.comap_mono _ _ _ HVU) ∘ induced_basis OX R f U HUB, from congr_fun this s, localization.funext _ _ $ λ x, show localization.lift (OX.O.F.res ⊤ (opens.comap _ V) _ ∘ f ∘ to_Spec_top R) _ ↑x = OX.O.F.res (opens.comap _ U) (opens.comap _ V) _ (localization.lift (OX.O.F.res ⊤ (opens.comap _ U) _ ∘ f ∘ to_Spec_top R) _ ↑x), by rw [localization.lift_coe, localization.lift_coe, ← presheaf.Hcomp']; refl instance is_ring_hom_induced_stalk (p : Spec R) : is_ring_hom (induced_stalk OX R f p) := { map_one := congr_arg quotient.mk (congr_arg (stalk_on_basis.elem.mk _ _ _) (by exact is_ring_hom.map_one (induced_basis _ _ _ _ _))), map_mul := λ x y, quotient.induction_on₂ x y $ λ s t, congr_arg quotient.mk (congr_arg (stalk_on_basis.elem.mk _ _ _) (by exact (is_ring_hom.map_mul (induced_basis _ _ _ _ _)).trans (by rw [induced_basis_res, induced_basis_res]; refl))), map_add := λ x y, quotient.induction_on₂ x y $ λ s t, congr_arg quotient.mk (congr_arg (stalk_on_basis.elem.mk _ _ _) (by exact (is_ring_hom.map_add (induced_basis _ _ _ _ _)).trans (by rw [induced_basis_res, induced_basis_res]; refl))) } instance is_ring_hom_induced_sheafification {X : Type u} [topological_space X] (OX : locally_ringed_space X) (R : Type u) [comm_ring R] (f : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤) [is_ring_hom f] (U : topological_space.opens (Spec R)) : is_ring_hom (induced_sheafification OX R f U) := { map_one := subtype.eq $ funext $ λ x, funext $ λ hxU, by exact is_ring_hom.map_one (induced_stalk OX R f x), map_mul := λ x y, subtype.eq $ funext $ λ p, funext $ λ hpU, by change induced_stalk _ _ _ _ _ = _ * _; rw [Fext_mul.eq, is_ring_hom.map_mul (induced_stalk OX R f p)], map_add := λ x y, subtype.eq $ funext $ λ p, funext $ λ hpU, by change induced_stalk _ _ _ _ _ = _ + _; rw [Fext_add.eq, is_ring_hom.map_add (induced_stalk OX R f p)] } theorem to_stalk_res {X : Type u} [topological_space X] (F : presheaf_of_rings X) (x : X) (U V : topological_space.opens X) (hxU : x ∈ U) (hxV : x ∈ V) (HVU : V ⊆ U) (s : F U) : to_stalk F x V hxV (F.res U V HVU s) = to_stalk F x U hxU s := quotient.sound ⟨V, hxV, set.subset.refl V, HVU, (presheaf.Hcomp' _ _ _ _ _ _ _).symm⟩ theorem is_unit_to_stalk {X : Type u} [topological_space X] (F : presheaf_of_rings X) (x : X) (U : topological_space.opens X) (hxU : x ∈ U) (s : F U) : is_unit (to_stalk F x U hxU s) ↔ ∃ V : topological_space.opens X, ∃ hxV : x ∈ V, ∃ HVU : V ⊆ U, is_unit (F.res U V HVU s) := ⟨λ hu, let ⟨t, ht⟩ := is_unit_iff_exists_inv.1 hu in quotient.induction_on t (λ ⟨V, hxV, τ⟩ H, let ⟨W, hxW, HWUV, HWtop, HW⟩ := quotient.exact H in ⟨W, hxW, set.subset.trans HWUV (set.inter_subset_left _ _), is_unit_iff_exists_inv.2 ⟨F.res V W (set.subset.trans HWUV (set.inter_subset_right _ _)) τ, by dsimp only at HW; rw [res_mul, ← presheaf.Hcomp', ← presheaf.Hcomp'] at HW; exact HW.trans (res_one _ _ _ _)⟩⟩) ht, λ ⟨V, hxV, HVU, hv⟩, hv.map' (to_stalk F x V hxV) _ (to_stalk_res _ _ _ _ _ _ _ _)⟩ section presheaf_of_rings_extension instance to_presheaf_of_rings_extension.is_ring_hom' {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) {U : topological_space.opens α} (BU : U ∈ B) : is_ring_hom (to_presheaf_of_rings_extension Bstd F BU) := { map_one := begin apply subtype.eq, funext x Hx, apply quotient.sound, use [U, BU, Hx, set.subset.refl _, set.subset_univ _], iterate 2 { erw (F.res_is_ring_hom _ _ _).map_one, }, end, map_mul := begin intros x y, apply subtype.eq, funext z Hz, apply quotient.sound, use [U, BU, Hz], use [set.subset.refl _, set.subset_inter (set.subset.refl _) (set.subset.refl _)], erw ←(F.res_is_ring_hom _ _ _).map_mul, erw ←presheaf_on_basis.Hcomp', refl end, map_add := begin intros x y, apply subtype.eq, funext z Hz, apply quotient.sound, use [U, BU, Hz], use [set.subset.refl _, set.subset_inter (set.subset.refl _) (set.subset.refl _)], erw ←(F.res_is_ring_hom _ _ _).map_add, erw ←presheaf_on_basis.Hcomp', refl end, } theorem res_to_presheaf_of_rings_extension {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) (U V : topological_space.opens α) (HUB : U ∈ B) (HVB : V ∈ B) (HVU : V ⊆ U) (σ : F.F HUB) : presheaf.res _ U V HVU (to_presheaf_of_rings_extension Bstd F HUB σ) = to_presheaf_of_rings_extension Bstd F HVB (F.res HUB HVB HVU σ) := subtype.eq $ funext $ λ x, funext $ λ hxV, quotient.sound ⟨V, HVB, hxV, HVU, set.subset.refl V, presheaf_on_basis.Hcomp' _ _ _ _ _ _ _⟩ noncomputable def to_presheaf_of_rings_extension.ring_equiv {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : topological_space.opens α} (HUB : U ∈ B) : F.F HUB ≃r (F ᵣₑₓₜ Bstd).F U := ring_equiv.mk (equiv.of_bijective (to_presheaf_of_rings_extension.bijective Bstd F HF HUB)) (to_presheaf_of_rings_extension.is_ring_hom Bstd F HF HUB) noncomputable def of_presheaf_of_rings_extension {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : topological_space.opens α} (HUB : U ∈ B) : (F ᵣₑₓₜ Bstd).F U → F.F HUB := (to_presheaf_of_rings_extension.ring_equiv HB Bstd F HF HUB).symm.to_fun instance of_presheaf_of_rings_extension.is_ring_hom {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : topological_space.opens α} (HUB : U ∈ B) : is_ring_hom (of_presheaf_of_rings_extension HB Bstd F HF HUB) := (to_presheaf_of_rings_extension.ring_equiv HB Bstd F HF HUB).symm.hom theorem of_to_presheaf_of_rings_extension {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : topological_space.opens α} (HUB : U ∈ B) (σ : F.F HUB) : of_presheaf_of_rings_extension HB Bstd F HF HUB (to_presheaf_of_rings_extension Bstd F HUB σ) = σ := equiv.symm_apply_apply _ _ theorem to_of_presheaf_of_rings_extension {α : Type u} [topological_space α] {B : set (topological_space.opens α)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis α HB) (HF : sheaf_on_standard_basis.is_sheaf_on_standard_basis Bstd F.to_presheaf_on_basis) {U : topological_space.opens α} (HUB : U ∈ B) (σ : (F ᵣₑₓₜ Bstd) U) : to_presheaf_of_rings_extension Bstd F HUB (of_presheaf_of_rings_extension HB Bstd F HF HUB σ) = σ := equiv.apply_symm_apply (to_presheaf_of_rings_extension.ring_equiv HB Bstd F HF HUB).to_equiv σ end presheaf_of_rings_extension theorem is_unit_localization_mk {R : Type u} [comm_ring R] {S : set R} [is_submonoid S] (r : R) (s : S) : is_unit (localization.mk r s) ↔ ∃ t, r * t ∈ S := begin rw is_unit_iff_exists_inv, split, { intros hu, cases hu with w hu, revert hu, refine localization.induction_on w (λ r2 s2 hu, _), rcases quotient.exact hu with ⟨t, hts, ht⟩, change (s.1 * s2.1 * 1 - 1 * (r * r2)) * t = 0 at ht, rw [mul_one, one_mul, sub_mul, sub_eq_zero_iff_eq] at ht, refine ⟨r2 * t, _⟩, rw [← mul_assoc, ← ht], exact (s * s2 * ⟨t, hts⟩).2 }, { rintros ⟨t, hrt⟩, refine ⟨localization.mk (s.1 * t) ⟨r * t, hrt⟩, quotient.sound $ localization.r_of_eq _⟩, change (s.1 * (r * t)) * 1 = 1 * (r * (s.val * t)), rw [mul_one, one_mul, mul_left_comm] } end theorem is_unit_to_stalk_affine (p : Spec R) (U : topological_space.opens (Spec R)) (HUB : U ∈ D_fs R) (hpU : p ∈ U) (σ : (structure_presheaf_on_basis R).F HUB) : is_unit (to_stalk (Spec.locally_ringed_space R).O.F p U hpU (to_presheaf_of_rings_extension _ _ HUB σ)) ↔ ∃ r : R, ∃ s : S U, p ∈ Spec.D' r ∧ localization.mk r s = σ := begin rw is_unit_to_stalk, split, { rintros ⟨V, hpV, HVU, hv⟩, rcases topological_space.opens.is_basis_iff_nbhd.1 (D_fs_basis R) hpV with ⟨W, HWB, hpW, HWV⟩, have := hv.map (presheaf.res _ V W HWV), rw ← presheaf.Hcomp' at this, dsimp only [Spec.locally_ringed_space, structure_sheaf, structure_sheaf.presheaf] at this, rw [res_to_presheaf_of_rings_extension _ _ _ _ _ HUB HWB] at this, replace this := this.map (of_presheaf_of_rings_extension (D_fs_basis R) (D_fs_standard_basis R) (structure_presheaf_on_basis R) structure_presheaf_on_basis_is_sheaf_on_basis HWB), rw of_to_presheaf_of_rings_extension at this, revert this, refine localization.induction_on σ (λ r s this, _), change is_unit (localization.mk r ⟨s.1, _⟩) at this, rw is_unit_localization_mk at this, cases this with t hrt, change W.1 ⊆ Spec.D' (r * t) at hrt, rw Spec.D'.product_eq_inter at hrt, refine ⟨r, s, (hrt hpW).1, rfl⟩ }, { rintros ⟨r, s, hrp, rfl⟩, refine ⟨U ∩ Spec.DO R r, ⟨hpU, hrp⟩, set.inter_subset_left _ _, _⟩, dsimp only [Spec.locally_ringed_space, structure_sheaf, structure_sheaf.presheaf], rw res_to_presheaf_of_rings_extension _ _ _ _ _ _ ((D_fs_standard_basis R).2 HUB (D_fs.mem R r)), refine is_unit.map _ _, rw is_unit_iff_exists_inv, refine ⟨localization.mk s.1 ⟨r, set.inter_subset_right _ _⟩, _⟩, change localization.mk r ⟨s.1, _⟩ * localization.mk s.1 ⟨r, _⟩ = _, rw [localization.mk_mul_mk, mul_comm], exact localization.mk_self } end theorem is_unit_to_stalk_affine' (p : Spec R) (U : topological_space.opens (Spec R)) (HUB : U ∈ D_fs R) (hpU : p ∈ U) (σ : (structure_presheaf_on_basis R).F HUB) : is_unit (to_stalk (Spec.locally_ringed_space R).O.F p U hpU (to_presheaf_of_rings_extension _ _ HUB σ)) ↔ ∀ r : R, ∀ s : S U, localization.mk r s = σ → p ∈ Spec.D' r := begin rw is_unit_to_stalk_affine, split, { rintros ⟨r1, s1, hp1, hrs⟩ r2 s2 rfl, rcases quotient.exact hrs with ⟨t, hts, ht⟩, change (s1.1 * r2 - s2.1 * r1) * t = 0 at ht, rw [sub_mul, sub_eq_zero_iff_eq] at ht, suffices : p ∈ Spec.D' (s1.1 * r2 * t), { rw [Spec.D'.product_eq_inter, Spec.D'.product_eq_inter] at this, exact this.1.2 }, rw ht, rw [Spec.D'.product_eq_inter, Spec.D'.product_eq_inter], exact ⟨⟨s2.2 hpU, hp1⟩, hts hpU⟩ }, { refine localization.induction_on σ (λ r s h, ⟨r, s, h r s rfl, rfl⟩) } end theorem is_unit_to_stalk_on_basis {X : Type u} [topological_space X] {B : set (topological_space.opens X)} (HB : topological_space.opens.is_basis B) (Bstd) (F : presheaf_of_rings_on_basis X HB) (p : X) (U : topological_space.opens X) (hpU : p ∈ U) (σ : (F ᵣₑₓₜ Bstd) U) : is_unit (to_stalk (F ᵣₑₓₜ Bstd) p U hpU σ) ↔ @is_unit (stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis Bstd F p) _ (σ.1 p hpU) := begin rw is_unit_to_stalk, split, { rintros ⟨W, hpW, HWU, HW⟩, rcases is_unit_iff_exists_inv.1 HW with ⟨τ, hστ⟩, refine is_unit_iff_exists_inv.2 ⟨τ.1 p hpW, _⟩, replace hστ := congr_arg subtype.val hστ, replace hστ := congr_fun (congr_fun hστ p) hpW, rwa Fext_mul.eq at hστ }, { rcases σ.2 p hpU with ⟨V, HVB, hpV, σ2, HV⟩, rw HV p ⟨hpU, hpV⟩, dsimp only, rintros hu, rcases is_unit_iff_exists_inv.1 hu with ⟨e, he⟩, revert he, refine quotient.induction_on e (λ τ hστ, _), rcases quotient.exact hστ with ⟨S, HSB, hpS, HSVτ, HStop, HS⟩, dsimp only at HS, rcases topological_space.opens.is_basis_iff_nbhd.1 HB (show p ∈ S ∩ U, from ⟨hpS, hpU⟩) with ⟨T, HTB, hpT, HTSU⟩, have HTS : T ⊆ S := set.subset.trans HTSU (set.inter_subset_left _ _), have HTτ : T ⊆ τ.U := set.subset.trans HTS (set.subset.trans HSVτ (set.inter_subset_right _ _)), refine ⟨T, hpT, set.subset.trans HTSU (set.inter_subset_right _ _), is_unit_iff_exists_inv.2 ⟨⟨λ q hqT, ⟦⟨T, HTB, hqT, F.res τ.BU HTB HTτ τ.s⟩⟧, λ q hqT, ⟨T, HTB, hqT, F.res τ.BU HTB HTτ τ.s, λ _ _, rfl⟩⟩, _⟩⟩, replace HS := congr_arg (F.res HSB HTB HTS) HS, refine subtype.eq (funext $ λ x, funext $ λ hxT, _), rw Fext_mul.eq, change (σ.1 x _ * _ : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis Bstd F x) = 1, rw HV x ⟨(HTSU hxT).2, (HSVτ $ HTS hxT).1⟩, refine quotient.sound ⟨T, HTB, hxT, set.subset_inter (set.subset.trans HTS (set.subset.trans HSVτ (set.inter_subset_left _ _))) (set.subset.refl T), set.subset_univ _, _⟩, dsimp only, rw bres_mul at HS ⊢, rw bres_mul at HS, repeat { rw ← presheaf_on_basis.Hcomp' at HS }, repeat { rw ← presheaf_on_basis.Hcomp' }, exact HS } end def of_pushforward_stalk {α : Type u} [topological_space α] {β : Type u} [topological_space β] {f : α → β} (hf : continuous f) (F : presheaf_of_rings α) (p : α) : stalk_of_rings (presheaf_of_rings.pushforward hf F) (f p) → stalk_of_rings F p := presheaf.fmap.stalk_of_rings ⟨λ U, id, λ U V HVU, rfl⟩ p instance is_ring_hom_of_pushforward_stalk {α : Type u} [topological_space α] {β : Type u} [topological_space β] {f : α → β} (hf : continuous f) (F : presheaf_of_rings α) (p : α) : is_ring_hom (of_pushforward_stalk hf F p) := is_ring_hom_stalk_of_rings _ _ theorem presheafasdf {α : Type u} [topological_space α] {β : Type u} [topological_space β] {f : α → β} (hf : continuous f) (F : presheaf_of_rings α) (G : presheaf_of_rings β) (m : presheaf_of_rings.fmap hf F G) (p : α) (σ) : presheaf.fmap.stalk_of_rings m p σ = of_pushforward_stalk hf F p (presheaf.fmap.stalk_of_rings (⟨m.map, m.commutes⟩ : presheaf_of_rings.fmap continuous_id (presheaf_of_rings.pushforward hf F) G) (f p) σ) := quotient.induction_on σ $ λ e, rfl @[simp] lemma localization.lift_mul {α : Type u} [comm_ring α] {S : set α} [is_submonoid S] {β : Type v} [comm_ring β] (f : α → β) [is_ring_hom f] (H) (x y : localization α S) : localization.lift f H (x * y) = localization.lift f H x * localization.lift f H y := is_ring_hom.map_mul _ /- https://stacks.math.columbia.edu/tag/01I1 -/ noncomputable def hom_to_mor {X : Type u} [topological_space X] (OX : locally_ringed_space X) (R : Type u) [comm_ring R] (f : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤) [is_ring_hom f] : OX.morphism (Spec.locally_ringed_space R) := { f := induced OX R f, Hf := induced_continuous OX R f, fO := { map := λ U s, (sheaf_of_rings.of_extension (D_fs_basis R) (D_fs_standard_basis R) _ _ (induced_sheafification OX R f U s) : OX.O.pushforward (induced_continuous OX R f) U), commutes := λ U V HVU, funext $ λ s, begin dsimp only [function.comp_apply], change _ = (sheaf_of_rings.pushforward _ (OX.O)).F.res _ _ _ _, rw ← sheaf_of_rings.of_extension_res, refl end }, hom := λ U, @is_ring_hom.comp _ _ _ _ _ (is_ring_hom_induced_sheafification OX R f U) _ _ _ _, hlocal := λ p s, quotient.induction_on s $ λ e he, begin cases e with U hpU σ, generalize hσ : σ.1 (induced OX R f p) hpU = t, revert hσ, refine quotient.induction_on t (λ τ, _), cases τ with V HVB hpV τ, refine localization.induction_on τ (λ r s hu, _), rw presheafasdf at he, change is_unit (of_pushforward_stalk (induced_continuous OX R f) OX.O.F p (to_stalk (OX.O.pushforward (induced_continuous OX R f)).F (induced OX R f p) U hpU (sheaf_of_rings.of_extension _ _ (OX.O.pushforward (induced_continuous OX R f)) U (induced_sheafification OX R f U σ) : OX.O.pushforward (induced_continuous OX R f) U))) at he, rw sheaf_of_rings.to_stalk_of_extension at he, dsimp only [induced_sheafification] at he, change σ.val (induced OX R f p) hpU = _ at hu, rw hu at he, change is_unit (of_pushforward_stalk (induced_continuous OX R f) OX.O.F p (to_stalk (OX.O.pushforward (induced_continuous OX R f)).F (induced OX R f p) V hpV (localization.lift (OX.O.F.to_presheaf.res ⊤ (opens.comap (induced_continuous OX R f) V) (set.subset_univ _) ∘ f ∘ to_Spec_top R) (induced_basis._proof_3 OX R f V) (localization.mk r s)))) at he, rw [localization.mk_eq, localization.lift_mul, localization.lift_coe, is_ring_hom.map_mul (to_stalk (OX.O.pushforward (induced_continuous OX R f)).F (induced OX R f p) V hpV), is_ring_hom.map_mul (of_pushforward_stalk (induced_continuous OX R f) OX.O.F p)] at he, replace he := is_unit_of_mul_is_unit_left he, change is_unit (to_stalk OX.O.F p (opens.comap (induced_continuous OX R f) V) hpV (OX.O.F.to_presheaf.res ⊤ (opens.comap (induced_continuous OX R f) V) (set.subset_univ _) (f (to_Spec_top R r)))) at he, rw to_stalk_res _ p ⊤ _ trivial at he, change p ∈ (OX.D (f (to_Spec_top R r)) : set X) at he, rw ← induced_preimage_D' at he, refine (is_unit_to_stalk_on_basis _ _ _ _ _ _ _).2 _, rw hu, refine is_unit_iff_exists_inv.2 ⟨⟦⟨V ∩ Spec.DO R r, (D_fs_standard_basis R).2 HVB (D_fs.mem _ _), ⟨hpV, he⟩, localization.mk s.1 ⟨r, set.inter_subset_right _ _⟩⟩⟧, quotient.sound ⟨V ∩ Spec.DO R r, (D_fs_standard_basis R).2 HVB (D_fs.mem _ _), ⟨hpV, he⟩, set.subset_inter (set.inter_subset_left _ _) (set.subset.refl _), set.subset_univ _, _⟩⟩, change localization.mk (r * s.1) ⟨s.1 * r, _⟩ = 1, rw mul_comm, exact localization.mk_self end } theorem cast_eq_of_heq : ∀ {α β : Sort u} {a : α} {b : β} (H : a == b), cast (type_eq_of_heq H) a = b | α _ a _ heq.rfl := rfl @[extensionality] theorem locally_ringed_space.morphism.ext {X : Type u} [topological_space X] {OX : locally_ringed_space X} {Y : Type v} [topological_space Y] {OY : locally_ringed_space Y} {m₁ m₂ : OX.morphism OY} (H1 : ∀ x, m₁.f x = m₂.f x) (H2 : ∀ U σ, OX.O.F.res (opens.comap m₁.Hf U) (opens.comap m₂.Hf U) (show m₂.f⁻¹' U ⊆ m₁.f⁻¹' U, from (funext H1 : m₁.f = m₂.f) ▸ set.subset.refl _) (m₁.fO.map U σ) = m₂.fO.map U σ) : m₁ = m₂ := begin rcases m₁ with ⟨⟨f, hf, ⟨mf, hmf⟩⟩, hf1, hf2⟩, rcases m₂ with ⟨⟨g, hg, ⟨mg, hmg⟩⟩, hg1, hg2⟩, have : f = g := funext H1, subst this, congr' 3, funext U σ, exact (presheaf.Hid' _ _ _).symm.trans (H2 U σ) end /- https://stacks.math.columbia.edu/tag/01I1 -/ theorem mor_to_hom_to_mor {X : Type u} [topological_space X] (OX : locally_ringed_space X) (R : Type u) [comm_ring R] (f : OX.morphism (Spec.locally_ringed_space R)) : hom_to_mor OX R (mor_to_hom OX R f) = f := begin have : ((hom_to_mor OX R (mor_to_hom OX R f)).to_morphism).f = (f.to_morphism).f, { funext x, apply subtype.eq, ext s, change ¬ is_unit (to_stalk _ _ _ _ (OX.O.F.res _ _ _ _)) ↔ f.f x ∈ Spec.V' s, rw to_stalk_res _ x (opens.comap f.Hf ⊤) _ trivial, split, { rintros hu, classical, by_contradiction hfxs, apply hu, change is_unit (presheaf.fmap.stalk_of_rings f.fO x (to_stalk _ _ ⊤ trivial (to_Spec_top R s))), haveI := is_ring_hom_stalk_of_rings f.fO, refine is_unit.map _ _, refine (is_unit_to_stalk_affine _ _ _ _ _ _).2 ⟨s, 1, hfxs, rfl⟩ }, { exact λ hsfx HV, (is_unit_to_stalk_affine' _ _ _ _ _ _).1 (f.hlocal x (to_stalk _ _ ⊤ trivial (to_Spec_top R s)) HV) _ _ rfl hsfx } }, fapply locally_ringed_space.morphism.ext, { intros, rw this }, intros U σ, refine @sheaf_of_rings.ext (Spec R) _ _ (D_fs_basis R) (OX.O.pushforward f.Hf) U _ _ (λ p hpU, _), rcases topological_space.opens.is_basis_iff_nbhd.1 (D_fs_basis R) hpU with ⟨V, HVB, hpV, HVU⟩, refine quotient.sound ⟨V, hpV, HVU, HVU, _⟩, change OX.O.F.res _ _ _ (OX.O.F.res _ _ _ _) = OX.O.F.res _ _ _ _, rw presheaf.fmap.commutes' f.fO U V HVU, rw ← presheaf.Hcomp', rw presheaf.Hcomp' _ (opens.comap (hom_to_mor OX R (mor_to_hom OX R f)).Hf U) (opens.comap (hom_to_mor OX R (mor_to_hom OX R f)).Hf V) (opens.comap f.Hf V) (show f.f ⁻¹' V ⊆ (hom_to_mor OX R (mor_to_hom OX R f)).f ⁻¹' V, by rw this) (opens.comap_mono _ _ _ HVU), rw presheaf.fmap.commutes' _ U V HVU, generalize : ((((Spec.locally_ringed_space R).O).F).to_presheaf).res U V HVU σ = τ, rcases to_presheaf_of_rings_extension.surjective _ _ structure_presheaf_on_basis_is_sheaf_on_basis HVB τ with ⟨x, rfl⟩, haveI := (hom_to_mor OX R (mor_to_hom OX R f)).hom, refine congr_fun (localization.funext (OX.O.F.res (opens.comap (hom_to_mor OX R (mor_to_hom OX R f)).Hf V) (opens.comap f.Hf V) _ ∘ (hom_to_mor OX R (mor_to_hom OX R f)).fO.map V ∘ to_presheaf_of_rings_extension _ (structure_presheaf_on_basis R) HVB) (f.fO.map V ∘ to_presheaf_of_rings_extension _ (structure_presheaf_on_basis R) HVB) _) x, intros r, dsimp only [function.comp_apply], rw [show ((r : localization R (S V)) : (structure_presheaf_on_basis R).F HVB) = (structure_presheaf_on_basis R).res (D_fs_standard_basis R).1 _ _ (localization.of r), from rfl, ← res_to_presheaf_of_rings_extension _ _ _ _ _ (D_fs_standard_basis R).1 _ (set.subset_univ _)], change (((OX.O).F).to_presheaf).res (opens.comap _ V) (opens.comap _ V) _ ((((hom_to_mor OX R (mor_to_hom OX R f)).to_morphism).fO).map V (((Spec.locally_ringed_space R).O.F.to_presheaf).res opens.univ V _ (to_presheaf_of_rings_extension _ (structure_presheaf_on_basis R) _ (localization.of r)))) = ((f.to_morphism).fO).map V (((Spec.locally_ringed_space R).O.F.to_presheaf).res opens.univ V _ (to_presheaf_of_rings_extension _ (structure_presheaf_on_basis R) _ (localization.of r))), rw [← presheaf.fmap.commutes', ← presheaf.fmap.commutes'], swap, { exact opens.comap_mono _ _ _ (set.subset_univ _) }, swap, { exact opens.comap_mono _ _ _ (set.subset_univ _) }, dsimp only [hom_to_mor], rw ← presheaf.Hcomp', rw presheaf.Hcomp' OX.O.F.to_presheaf (opens.comap (induced_continuous OX R (mor_to_hom OX R f)) opens.univ) (opens.comap f.Hf ⊤) (opens.comap f.Hf V) (opens.comap_mono _ _ _ (set.subset_univ _)) (λ _ _, trivial), congr' 1, rw [induced_sheafification_to_presheaf_of_rings_extension, sheaf_of_rings.of_to_extension], dsimp only [induced_basis], simp only [localization.lift_of, function.comp_apply], dsimp only [mor_to_hom], rw [← presheaf.Hcomp', ← presheaf.Hcomp'], exact presheaf.Hid' _ _ _, end /- https://stacks.math.columbia.edu/tag/01I1 -/ theorem hom_to_mor_to_hom {X : Type u} [topological_space X] (OX : locally_ringed_space X) (R : Type u) [comm_ring R] (f : (Spec.locally_ringed_space R).O ⊤ → OX.O ⊤) [is_ring_hom f] : mor_to_hom OX R (hom_to_mor OX R f) = f := begin funext x, rcases to_presheaf_of_rings_extension.surjective (D_fs_standard_basis R) _ structure_presheaf_on_basis_is_sheaf_on_basis (D_fs_standard_basis R).1 x with ⟨r, rfl⟩, suffices : mor_to_hom OX R (hom_to_mor OX R f) ∘ to_presheaf_of_rings_extension (D_fs_standard_basis R) (structure_presheaf_on_basis R) (D_fs_standard_basis R).1 = f ∘ to_presheaf_of_rings_extension (D_fs_standard_basis R) (structure_presheaf_on_basis R) (D_fs_standard_basis R).1, { convert congr_fun this r }, refine localization.funext _ _ (λ r, _), dsimp only [function.comp_apply, mor_to_hom, hom_to_mor], rw [induced_sheafification_to_presheaf_of_rings_extension, sheaf_of_rings.of_to_extension], dsimp only [induced_basis], rw [localization.lift_coe], dsimp only [function.comp_apply], rw ← presheaf.Hcomp', exact presheaf.Hid' _ _ _ end end tag01I1
e329b557a3d5a013a37031cf99278b3e3d2ce359
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/regular/basic.lean
231870d1342e786b02ed584bc367126514f9cff8
[ "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
14,537
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.order.monoid_lemmas import algebra.group_with_zero.basic import logic.embedding /-! # Regular elements We introduce left-regular, right-regular and regular elements, along with their `to_additive` analogues add-left-regular, add-right-regular and add-regular elements. By definition, a regular element in a commutative ring is a non-zero divisor. Lemma `is_regular_of_ne_zero` implies that every non-zero element of an integral domain is regular. Since it assumes that the ring is a `cancel_monoid_with_zero` it applies also, for instance, to `ℕ`. The lemmas in Section `mul_zero_class` show that the `0` element is (left/right-)regular if and only if the `mul_zero_class` is trivial. This is useful when figuring out stopping conditions for regular sequences: if `0` is ever an element of a regular sequence, then we can extend the sequence by adding one further `0`. The final goal is to develop part of the API to prove, eventually, results about non-zero-divisors. -/ variables {R : Type*} section has_mul variables [has_mul R] /-- A left-regular element is an element `c` such that multiplication on the left by `c` is injective. -/ @[to_additive "An add-left-regular element is an element `c` such that addition on the left by `c` is injective. -/ "] def is_left_regular (c : R) := ((*) c).injective /-- A right-regular element is an element `c` such that multiplication on the right by `c` is injective. -/ @[to_additive "An add-right-regular element is an element `c` such that addition on the right by `c` is injective."] def is_right_regular (c : R) := (* c).injective /-- An add-regular element is an element `c` such that addition by `c` both on the left and on the right is injective. -/ structure is_add_regular {R : Type*} [has_add R] (c : R) : Prop := (left : is_add_left_regular c) (right : is_add_right_regular c) /-- A regular element is an element `c` such that multiplication by `c` both on the left and on the right is injective. -/ structure is_regular (c : R) : Prop := (left : is_left_regular c) (right : is_right_regular c) attribute [to_additive] is_regular @[to_additive] protected lemma mul_le_cancellable.is_left_regular [partial_order R] {a : R} (ha : mul_le_cancellable a) : is_left_regular a := ha.injective lemma is_left_regular.right_of_commute {a : R} (ca : ∀ b, commute a b) (h : is_left_regular a) : is_right_regular a := λ x y xy, h $ (ca x).trans $ xy.trans $ (ca y).symm lemma commute.is_regular_iff {a : R} (ca : ∀ b, commute a b) : is_regular a ↔ is_left_regular a := ⟨λ h, h.left, λ h, ⟨h, h.right_of_commute ca⟩⟩ end has_mul section semigroup variables [semigroup R] {a b : R} /-- In a semigroup, the product of left-regular elements is left-regular. -/ @[to_additive "In an additive semigroup, the sum of add-left-regular elements is add-left.regular."] lemma is_left_regular.mul (lra : is_left_regular a) (lrb : is_left_regular b) : is_left_regular (a * b) := show function.injective ((*) (a * b)), from (comp_mul_left a b) ▸ lra.comp lrb /-- In a semigroup, the product of right-regular elements is right-regular. -/ @[to_additive "In an additive semigroup, the sum of add-right-regular elements is add-right-regular."] lemma is_right_regular.mul (rra : is_right_regular a) (rrb : is_right_regular b) : is_right_regular (a * b) := show function.injective (* (a * b)), from (comp_mul_right b a) ▸ rrb.comp rra /-- If an element `b` becomes left-regular after multiplying it on the left by a left-regular element, then `b` is left-regular. -/ @[to_additive "If an element `b` becomes add-left-regular after adding to it on the left a add-left-regular element, then `b` is add-left-regular."] lemma is_left_regular.of_mul (ab : is_left_regular (a * b)) : is_left_regular b := function.injective.of_comp (by rwa comp_mul_left a b) /-- An element is left-regular if and only if multiplying it on the left by a left-regular element is left-regular. -/ @[simp, to_additive "An element is add-left-regular if and only if adding to it on the left a add-left-regular element is add-left-regular."] lemma mul_is_left_regular_iff (b : R) (ha : is_left_regular a) : is_left_regular (a * b) ↔ is_left_regular b := ⟨λ ab, is_left_regular.of_mul ab, λ ab, is_left_regular.mul ha ab⟩ /-- If an element `b` becomes right-regular after multiplying it on the right by a right-regular element, then `b` is right-regular. -/ @[to_additive "If an element `b` becomes add-right-regular after adding to it on the right a add-right-regular element, then `b` is add-right-regular."] lemma is_right_regular.of_mul (ab : is_right_regular (b * a)) : is_right_regular b := begin refine λ x y xy, ab (_ : x * (b * a) = y * (b * a)), rw [← mul_assoc, ← mul_assoc], exact congr_fun (congr_arg (*) xy) a, end /-- An element is right-regular if and only if multiplying it on the right with a right-regular element is right-regular. -/ @[simp, to_additive "An element is add-right-regular if and only if adding it on the right to a add-right-regular element is add-right-regular."] lemma mul_is_right_regular_iff (b : R) (ha : is_right_regular a) : is_right_regular (b * a) ↔ is_right_regular b := ⟨λ ab, is_right_regular.of_mul ab, λ ab, is_right_regular.mul ab ha⟩ /-- Two elements `a` and `b` are regular if and only if both products `a * b` and `b * a` are regular. -/ @[to_additive "Two elements `a` and `b` are add-regular if and only if both sums `a + b` and `b + a` are add-regular."] lemma is_regular_mul_and_mul_iff : is_regular (a * b) ∧ is_regular (b * a) ↔ is_regular a ∧ is_regular b := begin refine ⟨_, _⟩, { rintros ⟨ab, ba⟩, exact ⟨⟨is_left_regular.of_mul ba.left, is_right_regular.of_mul ab.right⟩, ⟨is_left_regular.of_mul ab.left, is_right_regular.of_mul ba.right⟩⟩ }, { rintros ⟨ha, hb⟩, exact ⟨⟨(mul_is_left_regular_iff _ ha.left).mpr hb.left, (mul_is_right_regular_iff _ hb.right).mpr ha.right⟩, ⟨(mul_is_left_regular_iff _ hb.left).mpr ha.left, (mul_is_right_regular_iff _ ha.right).mpr hb.right⟩⟩ } end /-- The "most used" implication of `mul_and_mul_iff`, with split hypotheses, instead of `∧`. -/ @[to_additive "The \"most used\" implication of `add_and_add_iff`, with split hypotheses, instead of `∧`."] lemma is_regular.and_of_mul_of_mul (ab : is_regular (a * b)) (ba : is_regular (b * a)) : is_regular a ∧ is_regular b := is_regular_mul_and_mul_iff.mp ⟨ab, ba⟩ end semigroup section mul_zero_class variables [mul_zero_class R] {a b : R} /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular.subsingleton (h : is_left_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (zero_mul a) (zero_mul b).symm⟩ /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular.subsingleton (h : is_right_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (mul_zero a) (mul_zero b).symm⟩ /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular.subsingleton (h : is_regular (0 : R)) : subsingleton R := h.left.subsingleton /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular_zero_iff_subsingleton : is_left_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.subsingleton, λ H a b h, @subsingleton.elim _ H a b⟩ /-- In a non-trivial `mul_zero_class`, the `0` element is not left-regular. -/ lemma not_is_left_regular_zero_iff : ¬ is_left_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_left_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular_zero_iff_subsingleton : is_right_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.subsingleton, λ H a b h, @subsingleton.elim _ H a b⟩ /-- In a non-trivial `mul_zero_class`, the `0` element is not right-regular. -/ lemma not_is_right_regular_zero_iff : ¬ is_right_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_right_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular_iff_subsingleton : is_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.left.subsingleton, λ h, ⟨is_left_regular_zero_iff_subsingleton.mpr h, is_right_regular_zero_iff_subsingleton.mpr h⟩⟩ /-- A left-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_left_regular.ne_zero [nontrivial R] (la : is_left_regular a) : a ≠ 0 := begin rintro rfl, rcases exists_pair_ne R with ⟨x, y, xy⟩, refine xy (la _), rw [zero_mul, zero_mul] end /-- A right-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_right_regular.ne_zero [nontrivial R] (ra : is_right_regular a) : a ≠ 0 := begin rintro rfl, rcases exists_pair_ne R with ⟨x, y, xy⟩, refine xy (ra (_ : x * 0 = y * 0)), rw [mul_zero, mul_zero] end /-- A regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_regular.ne_zero [nontrivial R] (la : is_regular a) : a ≠ 0 := la.left.ne_zero /-- In a non-trivial ring, the element `0` is not left-regular -- with typeclasses. -/ lemma not_is_left_regular_zero [nR : nontrivial R] : ¬ is_left_regular (0 : R) := not_is_left_regular_zero_iff.mpr nR /-- In a non-trivial ring, the element `0` is not right-regular -- with typeclasses. -/ lemma not_is_right_regular_zero [nR : nontrivial R] : ¬ is_right_regular (0 : R) := not_is_right_regular_zero_iff.mpr nR /-- In a non-trivial ring, the element `0` is not regular -- with typeclasses. -/ lemma not_is_regular_zero [nontrivial R] : ¬ is_regular (0 : R) := λ h, is_regular.ne_zero h rfl end mul_zero_class section mul_one_class variable [mul_one_class R] /-- If multiplying by `1` on either side is the identity, `1` is regular. -/ @[to_additive "If adding `0` on either side is the identity, `0` is regular."] lemma is_regular_one : is_regular (1 : R) := ⟨λ a b ab, (one_mul a).symm.trans (eq.trans ab (one_mul b)), λ a b ab, (mul_one a).symm.trans (eq.trans ab (mul_one b))⟩ end mul_one_class section comm_semigroup variables [comm_semigroup R] {a b : R} /-- A product is regular if and only if the factors are. -/ @[to_additive "A sum is add-regular if and only if the summands are."] lemma is_regular_mul_iff : is_regular (a * b) ↔ is_regular a ∧ is_regular b := begin refine iff.trans _ is_regular_mul_and_mul_iff, refine ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩ end end comm_semigroup section monoid variables [monoid R] {a b : R} /-- An element admitting a left inverse is left-regular. -/ @[to_additive "An element admitting a left additive opposite is add-left-regular."] lemma is_left_regular_of_mul_eq_one (h : b * a = 1) : is_left_regular a := @is_left_regular.of_mul R _ _ _ (by { rw h, exact is_regular_one.left }) /-- An element admitting a right inverse is right-regular. -/ @[to_additive "An element admitting a right additive opposite is add-right-regular."] lemma is_right_regular_of_mul_eq_one (h : a * b = 1) : is_right_regular a := is_right_regular.of_mul (by { rw h, exact is_regular_one.right }) /-- If `R` is a monoid, an element in `Rˣ` is regular. -/ @[to_additive "If `R` is an additive monoid, an element in `add_units R` is add-regular."] lemma units.is_regular (a : Rˣ) : is_regular (a : R) := ⟨is_left_regular_of_mul_eq_one a.inv_mul, is_right_regular_of_mul_eq_one a.mul_inv⟩ /-- A unit in a monoid is regular. -/ @[to_additive "An additive unit in an additive monoid is add-regular."] lemma is_unit.is_regular (ua : is_unit a) : is_regular a := begin rcases ua with ⟨a, rfl⟩, exact units.is_regular a, end end monoid section left_or_right_cancel_semigroup /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[to_additive "The embedding of a left cancellative additive semigroup into itself by left translation by a fixed element.", simps] def mul_left_embedding {G : Type*} [left_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, g * h, inj' := mul_right_injective g } /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ @[to_additive "The embedding of a right cancellative additive semigroup into itself by right translation by a fixed element.", simps] def mul_right_embedding {G : Type*} [right_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, h * g, inj' := mul_left_injective g } @[to_additive] lemma mul_left_embedding_eq_mul_right_embedding {G : Type*} [cancel_comm_monoid G] (g : G) : mul_left_embedding g = mul_right_embedding g := by { ext, exact mul_comm _ _ } /-- Elements of a left cancel semigroup are left regular. -/ @[to_additive "Elements of an add left cancel semigroup are add-left-regular."] lemma is_left_regular_of_left_cancel_semigroup [left_cancel_semigroup R] (g : R) : is_left_regular g := mul_right_injective g /-- Elements of a right cancel semigroup are right regular. -/ @[to_additive "Elements of an add right cancel semigroup are add-right-regular"] lemma is_right_regular_of_right_cancel_semigroup [right_cancel_semigroup R] (g : R) : is_right_regular g := mul_left_injective g end left_or_right_cancel_semigroup section cancel_monoid variables [cancel_monoid R] /-- Elements of a cancel monoid are regular. Cancel semigroups do not appear to exist. -/ @[to_additive "Elements of an add cancel monoid are regular. Add cancel semigroups do not appear to exist."] lemma is_regular_of_cancel_monoid (g : R) : is_regular g := ⟨mul_right_injective g, mul_left_injective g⟩ end cancel_monoid section cancel_monoid_with_zero variables [cancel_monoid_with_zero R] {a : R} /-- Non-zero elements of an integral domain are regular. -/ lemma is_regular_of_ne_zero (a0 : a ≠ 0) : is_regular a := ⟨λ b c, (mul_right_inj' a0).mp, λ b c, (mul_left_inj' a0).mp⟩ /-- In a non-trivial integral domain, an element is regular iff it is non-zero. -/ lemma is_regular_iff_ne_zero [nontrivial R] : is_regular a ↔ a ≠ 0 := ⟨is_regular.ne_zero, is_regular_of_ne_zero⟩ end cancel_monoid_with_zero
1ea282378c7187abf9fd19f56195ada2c67639c6
6094e25ea0b7699e642463b48e51b2ead6ddc23f
/library/init/nat.lean
70472ae961288da73460b7d1a194eb6a6366c689
[ "Apache-2.0" ]
permissive
gbaz/lean
a7835c4e3006fbbb079e8f8ffe18aacc45adebfb
a501c308be3acaa50a2c0610ce2e0d71becf8032
refs/heads/master
1,611,198,791,433
1,451,339,111,000
1,451,339,111,000
48,713,797
0
0
null
1,451,338,939,000
1,451,338,939,000
null
UTF-8
Lean
false
false
10,373
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.wf init.tactic init.num open eq.ops decidable or notation `ℕ` := nat namespace nat protected definition rec_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n := nat.rec H₁ H₂ n protected definition induction_on [recursor] {C : ℕ → Prop} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C a → C (succ a)) : C n := nat.rec H₁ H₂ n protected definition cases_on [reducible] [recursor] [unfold 2] {C : ℕ → Type} (n : ℕ) (H₁ : C 0) (H₂ : Π (a : ℕ), C (succ a)) : C n := nat.rec H₁ (λ a ih, H₂ a) n protected definition no_confusion_type [reducible] (P : Type) (v₁ v₂ : ℕ) : Type := nat.rec (nat.rec (P → P) (λ a₂ ih, P) v₂) (λ a₁ ih, nat.rec P (λ a₂ ih, (a₁ = a₂ → P) → P) v₂) v₁ protected definition no_confusion [reducible] [unfold 4] {P : Type} {v₁ v₂ : ℕ} (H : v₁ = v₂) : nat.no_confusion_type P v₁ v₂ := eq.rec (λ H₁ : v₁ = v₁, nat.rec (λ h, h) (λ a ih h, h (eq.refl a)) v₁) H H /- basic definitions on natural numbers -/ inductive le (a : ℕ) : ℕ → Prop := | nat_refl : le a a -- use nat_refl to avoid overloading le.refl | step : Π {b}, le a b → le a (succ b) definition nat_has_le [instance] [reducible] [priority nat.prio]: has_le nat := has_le.mk nat.le protected lemma le_refl [refl] : ∀ a : nat, a ≤ a := le.nat_refl protected definition lt [reducible] (n m : ℕ) := succ n ≤ m definition nat_has_lt [instance] [reducible] [priority nat.prio] : has_lt nat := has_lt.mk nat.lt definition pred [unfold 1] (a : nat) : nat := nat.cases_on a zero (λ a₁, a₁) -- add is defined in init.reserved_notation protected definition sub (a b : nat) : nat := nat.rec_on b a (λ b₁, pred) protected definition mul (a b : nat) : nat := nat.rec_on b zero (λ b₁ r, r + a) definition nat_has_sub [instance] [reducible] [priority nat.prio] : has_sub nat := has_sub.mk nat.sub definition nat_has_mul [instance] [reducible] [priority nat.prio] : has_mul nat := has_mul.mk nat.mul /- properties of ℕ -/ protected definition is_inhabited [instance] : inhabited nat := inhabited.mk zero protected definition has_decidable_eq [instance] [priority nat.prio] : ∀ x y : nat, decidable (x = y) | has_decidable_eq zero zero := inl rfl | has_decidable_eq (succ x) zero := inr (by contradiction) | has_decidable_eq zero (succ y) := inr (by contradiction) | has_decidable_eq (succ x) (succ y) := match has_decidable_eq x y with | inl xeqy := inl (by rewrite xeqy) | inr xney := inr (λ h : succ x = succ y, by injection h with xeqy; exact absurd xeqy xney) end /- properties of inequality -/ protected theorem le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ !nat.le_refl theorem le_succ (n : ℕ) : n ≤ succ n := le.step !nat.le_refl theorem pred_le (n : ℕ) : pred n ≤ n := by cases n;repeat constructor theorem le_succ_iff_true [simp] (n : ℕ) : n ≤ succ n ↔ true := iff_true_intro (le_succ n) theorem pred_le_iff_true [simp] (n : ℕ) : pred n ≤ n ↔ true := iff_true_intro (pred_le n) protected theorem le_trans {n m k : ℕ} (H1 : n ≤ m) : m ≤ k → n ≤ k := le.rec H1 (λp H2, le.step) theorem le_succ_of_le {n m : ℕ} (H : n ≤ m) : n ≤ succ m := nat.le_trans H !le_succ theorem le_of_succ_le {n m : ℕ} (H : succ n ≤ m) : n ≤ m := nat.le_trans !le_succ H protected theorem le_of_lt {n m : ℕ} (H : n < m) : n ≤ m := le_of_succ_le H theorem succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m := le.rec !nat.le_refl (λa b, le.step) theorem pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m := le.rec !nat.le_refl (nat.rec (λa b, b) (λa b c, le.step)) theorem le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n le.step (λa, succ_le_succ) theorem not_succ_le_zero (n : ℕ) : ¬succ n ≤ 0 := by intro H; cases H theorem succ_le_zero_iff_false (n : ℕ) : succ n ≤ 0 ↔ false := iff_false_intro !not_succ_le_zero theorem not_succ_le_self : Π {n : ℕ}, ¬succ n ≤ n := nat.rec !not_succ_le_zero (λa b c, b (le_of_succ_le_succ c)) theorem succ_le_self_iff_false [simp] (n : ℕ) : succ n ≤ n ↔ false := iff_false_intro not_succ_le_self theorem zero_le : ∀ (n : ℕ), 0 ≤ n := nat.rec !nat.le_refl (λa, le.step) theorem zero_le_iff_true [simp] (n : ℕ) : 0 ≤ n ↔ true := iff_true_intro !zero_le theorem lt.step {n m : ℕ} : n < m → n < succ m := le.step theorem zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ !zero_le theorem zero_lt_succ_iff_true [simp] (n : ℕ) : 0 < succ n ↔ true := iff_true_intro (zero_lt_succ n) protected theorem lt_trans {n m k : ℕ} (H1 : n < m) : m < k → n < k := nat.le_trans (le.step H1) protected theorem lt_of_le_of_lt {n m k : ℕ} (H1 : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ H1) protected theorem lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans protected theorem lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self theorem lt_self_iff_false (n : ℕ) : n < n ↔ false := iff_false_intro (λ H, absurd H (nat.lt_irrefl n)) theorem self_lt_succ (n : ℕ) : n < succ n := !nat.le_refl theorem self_lt_succ_iff_true [simp] (n : ℕ) : n < succ n ↔ true := iff_true_intro (self_lt_succ n) theorem lt.base (n : ℕ) : n < succ n := !nat.le_refl theorem le_lt_antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m < n) : false := !nat.lt_irrefl (nat.lt_of_le_of_lt H1 H2) protected theorem le_antisymm {n m : ℕ} (H1 : n ≤ m) : m ≤ n → n = m := le.cases_on H1 (λa, rfl) (λa b c, absurd (nat.lt_of_le_of_lt b c) !nat.lt_irrefl) theorem lt_le_antisymm {n m : ℕ} (H1 : n < m) (H2 : m ≤ n) : false := le_lt_antisymm H2 H1 protected theorem nat.lt_asymm {n m : ℕ} (H1 : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt H1) theorem not_lt_zero (a : ℕ) : ¬ a < 0 := !not_succ_le_zero theorem lt_zero_iff_false [simp] (a : ℕ) : a < 0 ↔ false := iff_false_intro (not_lt_zero a) protected theorem eq_or_lt_of_le {a b : ℕ} (H : a ≤ b) : a = b ∨ a < b := le.cases_on H (inl rfl) (λn h, inr (succ_le_succ h)) protected theorem le_of_eq_or_lt {a b : ℕ} (H : a = b ∨ a < b) : a ≤ b := or.elim H !nat.le_of_eq !nat.le_of_lt -- less-than is well-founded definition lt.wf [instance] : well_founded lt := well_founded.intro (nat.rec (!acc.intro (λn H, absurd H (not_lt_zero n))) (λn IH, !acc.intro (λm H, or.elim (nat.eq_or_lt_of_le (le_of_succ_le_succ H)) (λe, eq.substr e IH) (acc.inv IH)))) definition measure {A : Type} : (A → ℕ) → A → A → Prop := inv_image lt definition measure.wf {A : Type} (f : A → ℕ) : well_founded (measure f) := inv_image.wf f lt.wf theorem succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ theorem lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le theorem lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ definition decidable_le [instance] [priority nat.prio] : ∀ a b : nat, decidable (a ≤ b) := nat.rec (λm, (decidable.inl !zero_le)) (λn IH m, !nat.cases_on (decidable.inr (not_succ_le_zero n)) (λm, decidable.rec (λH, inl (succ_le_succ H)) (λH, inr (λa, H (le_of_succ_le_succ a))) (IH m))) definition decidable_lt [instance] [priority nat.prio] : ∀ a b : nat, decidable (a < b) := λ a b, decidable_le (succ a) b protected theorem lt_or_ge (a b : ℕ) : a < b ∨ a ≥ b := nat.rec (inr !zero_le) (λn, or.rec (λh, inl (le_succ_of_le h)) (λh, or.elim (nat.eq_or_lt_of_le h) (λe, inl (eq.subst e !nat.le_refl)) inr)) b protected definition lt_ge_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a ≥ b → P) : P := by_cases H1 (λh, H2 (or.elim !nat.lt_or_ge (λa, absurd a h) (λa, a))) protected definition lt_by_cases {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := nat.lt_ge_by_cases H1 (λh₁, nat.lt_ge_by_cases H3 (λh₂, H2 (nat.le_antisymm h₂ h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λH, inl H) (λH, inr (inl H)) (λH, inr (inr H)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := or.rec_on (nat.lt_trichotomy a b) (λ hlt, absurd hlt hnlt) (λ h, h) theorem lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ theorem lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h theorem succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h theorem succ_sub_succ_eq_sub [simp] (a b : ℕ) : succ a - succ b = a - b := nat.rec (by esimp) (λ b, congr_arg pred) b theorem sub_eq_succ_sub_succ (a b : ℕ) : a - b = succ a - succ b := eq.symm !succ_sub_succ_eq_sub theorem zero_sub_eq_zero [simp] (a : ℕ) : 0 - a = 0 := nat.rec rfl (λ a, congr_arg pred) a theorem zero_eq_zero_sub (a : ℕ) : 0 = 0 - a := eq.symm !zero_sub_eq_zero theorem sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b !nat.le_refl (λ b₁, nat.le_trans !pred_le) theorem sub_le_iff_true [simp] (a b : ℕ) : a - b ≤ a ↔ true := iff_true_intro (sub_le a b) theorem sub_lt {a b : ℕ} (H1 : 0 < a) (H2 : 0 < b) : a - b < a := !nat.cases_on (λh, absurd h !nat.lt_irrefl) (λa h, succ_le_succ (!nat.cases_on (λh, absurd h !nat.lt_irrefl) (λb c, eq.substr !succ_sub_succ_eq_sub !sub_le) H2)) H1 theorem sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le !sub_le theorem sub_lt_succ_iff_true [simp] (a b : ℕ) : a - b < succ a ↔ true := iff_true_intro !sub_lt_succ end nat
81ef392dbc2c5af16c6c900031c58bdac3b0fd6b
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/Mbar/Mbar_le.lean
4b8e0b0f99669239b45cba7d39c99fc7b736ce38
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,726
lean
import for_mathlib.Profinite.extend import for_mathlib.Profinite.product import data.fintype.card import category_theory.limits.functor_category import category_theory.limits.shapes.binary_products import category_theory.currying import facts import hacks_and_tricks.type_pow import Mbar.basic import pseudo_normed_group.profinitely_filtered /-! # $\overline{\mathcal{M}}_{r'}(S)_{≤ c}$ In this file we put a profinite topology on the subspace `Mbar_le r' S c` of `Mbar r' S` consisting of power series `F_s = ∑ a_{n,s}T^n ∈ Tℤ⟦T⟧` such that `∑_{n,s} |a_{n,s}|r'^n ≤ c`. -/ universe u noncomputable theory open_locale big_operators nnreal open pseudo_normed_group category_theory category_theory.limits local attribute [instance] type_pow variables {r' : ℝ≥0} {S : Type u} [fintype S] {c c₁ c₂ c₃ : ℝ≥0} /-- `Mbar_le r' S c` is the set of power series `F_s = ∑ a_{n,s}T^n ∈ Tℤ[[T]]` such that `∑_{n,s} |a_{n,s}|r'^n ≤ c` -/ def Mbar_le (r' : ℝ≥0) (S : Type u) [fintype S] (c : ℝ≥0) := { F : Mbar r' S // F ∈ filtration (Mbar r' S) c } namespace Mbar_le instance has_coe : has_coe (Mbar_le r' S c) (Mbar r' S) := ⟨subtype.val⟩ instance has_coe_to_fun : has_coe_to_fun (Mbar_le r' S c) := ⟨λ F, S → ℕ → ℤ, λ F, F.1⟩ @[simp] lemma coe_coe_to_fun (F : Mbar_le r' S c) : ⇑(F : Mbar r' S) = F := rfl @[simp] lemma coe_mk (x h) : ((⟨x, h⟩ : Mbar_le r' S c) : S → ℕ → ℤ) = x := rfl @[simp] protected lemma coeff_zero (x : Mbar_le r' S c) (s : S) : x s 0 = 0 := x.1.coeff_zero' s protected lemma summable (x : Mbar_le r' S c) (s : S) : summable (λ n, (↑(x s n).nat_abs * r'^n)) := x.1.summable' s protected lemma mem_filtration (x : Mbar_le r' S c) : x.1 ∈ filtration (Mbar r' S) c := x.property /-- The inclusion map `Mbar_le r' S c₁ → Mbar_le r' S c₂` for `c₁ ≤ c₂`. -/ protected def cast_le [hc : fact (c₁ ≤ c₂)] (x : Mbar_le r' S c₁) : Mbar_le r' S c₂ := ⟨⟨x, x.coeff_zero, x.summable⟩, filtration_mono hc.out x.mem_filtration⟩ @[simp] lemma coe_cast_le [hc : fact (c₁ ≤ c₂)] (x : Mbar_le r' S c₁) : ((x.cast_le : Mbar_le r' S c₂) : Mbar r' S) = x := by { ext, refl } @[simp] lemma cast_le_apply [hc : fact (c₁ ≤ c₂)] (x : Mbar_le r' S c₁) (s : S) (i : ℕ) : (x.cast_le : Mbar_le r' S c₂) s i = x s i := rfl lemma injective_cast_le [fact (c₁ ≤ c₂)] : function.injective (Mbar_le.cast_le : Mbar_le r' S c₁ → Mbar_le r' S c₂) := λ x y h, begin ext s n, change x.cast_le s n = y.cast_le s n, rw h, end @[ext] lemma ext (x y : Mbar_le r' S c) (h : ⇑x = y) : x = y := by { ext:2, exact h } instance : has_zero (Mbar_le r' S c) := ⟨⟨0, zero_mem_filtration _⟩⟩ instance : inhabited (Mbar_le r' S c) := ⟨0⟩ end Mbar_le variables (c₃) /-- The addition on `Mbar_le`. This addition is not homogeneous, but has type `(Mbar_le r' S c₁) → (Mbar_le r' S c₂) → (Mbar_le r' S c₃)` for `c₁ + c₂ ≤ c₃`. -/ def Mbar_le.add [h : fact (c₁ + c₂ ≤ c₃)] (F : Mbar_le r' S c₁) (G : Mbar_le r' S c₂) : Mbar_le r' S c₃ := subtype.mk (F + G) $ filtration_mono h.out $ add_mem_filtration F.mem_filtration G.mem_filtration /-- An uncurried version of addition on `Mbar_le`, meaning that it takes only 1 input, coming from a product type. -/ def Mbar_le.add' [fact (c₁ + c₂ ≤ c₃)] : Mbar_le r' S c₁ × Mbar_le r' S c₂ → Mbar_le r' S c₃ := λ x, Mbar_le.add c₃ x.1 x.2 -- TODO: register this as an instance?? /-- The negation on `Mbar_le`. -/ def Mbar_le.neg (F : Mbar_le r' S c) : Mbar_le r' S c := subtype.mk (-F) $ neg_mem_filtration F.mem_filtration namespace Mbar_le /-- The truncation map from Mbar_le to `Mbar_bdd`. -/ @[simps] def truncate (M : ℕ) (F : Mbar_le r' S c) : Mbar_bdd r' ⟨S⟩ c M := { to_fun := λ s n, F s n, coeff_zero' := by simp, sum_le' := begin refine le_trans _ F.mem_filtration, apply finset.sum_le_sum, rintros (s : S) -, rw fin.sum_univ_eq_sum_range (λ i, (↑(F s i).nat_abs * r' ^i)) (M+1), exact sum_le_tsum _ (λ _ _, subtype.property (_ : ℝ≥0)) (F.summable s), end } lemma truncate_surjective (M : ℕ) : function.surjective (truncate M : Mbar_le r' S c → Mbar_bdd r' ⟨S⟩ c M) := begin intro x, have aux : _ := _, let F : Mbar_le r' S c := ⟨{ to_fun := λ s n, if h : n < M + 1 then x s ⟨n, h⟩ else 0, summable' := aux, .. }, _⟩, { use F, ext s i, simp only [truncate_to_fun], dsimp, rw dif_pos i.is_lt, simp only [fin.eta] }, { intro s, rw dif_pos (nat.zero_lt_succ _), exact x.coeff_zero s }, { apply le_trans _ x.sum_le, apply finset.sum_le_sum, rintro s -, rw [← sum_add_tsum_nat_add' (M + 1), tsum_eq_zero, add_zero], { rw ← fin.sum_univ_eq_sum_range, apply finset.sum_le_sum, rintro i -, simp only [dif_pos i.is_lt, fin.eta, Mbar.coe_mk] }, { intro i, dsimp, rw [dif_neg, int.nat_abs_zero, nat.cast_zero, zero_mul], linarith }, { dsimp, apply aux } }, { intro s, apply @summable_of_ne_finset_zero _ _ _ _ _ (finset.range (M+1)), intros i hi, rw finset.mem_range at hi, simp only [hi, zero_mul, dif_neg, not_false_iff, nat.cast_zero, int.nat_abs_zero] } end /-- Injectivity of the map `Mbar_le` to the limit of the `Mbar_bdd`. -/ lemma eq_iff_truncate_eq (x y : Mbar_le r' S c) (cond : ∀ M, truncate M x = truncate M y) : x = y := begin ext s n, change (truncate n x).1 s ⟨n, by linarith⟩ = (truncate n y).1 s ⟨n,_⟩, rw cond, end lemma truncate_cast_le (M : ℕ) [hc : fact (c₁ ≤ c₂)] (x : Mbar_le r' S c₁) : truncate M (Mbar_le.cast_le x : Mbar_le r' S c₂) = Mbar_bdd.cast_le (truncate M x) := rfl /-- Underlying function of the element of `Mbar_le r' S c` associated to a sequence of elements of the truncated Mbars. -/ def mk_seq (T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M) : S → ℕ → ℤ := λ s n, (T n).1 s ⟨n, lt_add_one n⟩ @[simp] lemma mk_seq_zero {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (s : S) : mk_seq T s 0 = 0 := (T 0).coeff_zero s lemma mk_seq_eq_of_compat {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) {s : S} {n : ℕ} {M : ℕ} (hnM : n < M + 1) : mk_seq T s n = (T M).1 s ⟨n, hnM⟩ := begin have hnM : n ≤ M := nat.lt_succ_iff.mp hnM, unfold mk_seq, rw ← compat n M hnM, apply Mbar_bdd.transition_eq, end lemma mk_seq_sum_range_eq (T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M) (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) (s : S) (n) : ∑ i in finset.range (n+1), (↑(mk_seq T s i).nat_abs * r'^i) = ∑ i : fin (n+1), (↑((T n).1 s i).nat_abs * r'^(i:ℕ)) := begin rw ← fin.sum_univ_eq_sum_range, congr', ext ⟨i, hi⟩, congr', exact mk_seq_eq_of_compat compat _, end lemma mk_seq_summable {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) (s : S) : summable (λ (n : ℕ), (↑(mk_seq T s n).nat_abs * r' ^ n)) := begin apply @nnreal.summable_of_sum_range_le _ c, rintro (_|n), { simp only [finset.sum_empty, finset.range_zero, zero_le'] }, { rw mk_seq_sum_range_eq T compat s n, refine le_trans _ (T n).sum_le, refine finset.single_le_sum (λ _ _, _) (finset.mem_univ s), apply zero_le' }, end open filter lemma mk_seq_tendsto {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) : tendsto (λ (n : ℕ), ∑ (s : S), ∑ i in finset.range n, (↑(mk_seq T s i).nat_abs * r'^i)) at_top (nhds $ ∑ (s : S), ∑' n, (↑(mk_seq T s n).nat_abs * r'^n)) := tendsto_finset_sum _ $ λ s _, has_sum.tendsto_sum_nat $ summable.has_sum $ mk_seq_summable compat s lemma mk_seq_sum_le {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) : (∑ s, ∑' (n : ℕ), (↑(mk_seq T s n).nat_abs * r' ^ n)) ≤ c := begin refine le_of_tendsto (mk_seq_tendsto compat) (eventually_of_forall _), rintro (_|n), { simp only [finset.sum_empty, finset.range_zero, finset.sum_const_zero, zero_le'] }, { convert (T n).sum_le, funext, rw mk_seq_sum_range_eq T compat s n, refl } end lemma truncate_mk_seq {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) (M : ℕ) : truncate M ⟨⟨mk_seq T, mk_seq_zero, mk_seq_summable compat⟩, mk_seq_sum_le compat⟩ = T M := begin ext s ⟨i, hi⟩, exact mk_seq_eq_of_compat compat _, end /-- `of_compat hT` is the limit of a compatible family `T M : Mbar_bdd r' ⟨S⟩ c M`. This realizes `Mbar_le` as the profinite limit of the spaces `Mbar_bdd`, see also `Mbar_le.eqv`. -/ def of_compat {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) : Mbar_le r' S c := ⟨⟨mk_seq T, mk_seq_zero, mk_seq_summable compat⟩, mk_seq_sum_le compat⟩ @[simp] lemma truncate_of_compat {T : Π (M : ℕ), Mbar_bdd r' ⟨S⟩ c M} (compat : ∀ (M N : ℕ) (h : M ≤ N), Mbar_bdd.transition r' h (T N) = T M) (M : ℕ) : truncate M (of_compat compat) = T M := begin ext s ⟨i, hi⟩, exact mk_seq_eq_of_compat compat _, end /-- The equivalence (as types) between `Mbar_le r' S c` and the profinite limit of the spaces `Mbar_bdd r' ⟨S⟩ c M`. -/ def eqv : Mbar_le r' S c ≃ Mbar_bdd.limit r' ⟨S⟩ c := { to_fun := λ F, ⟨λ N, truncate _ F, by { intros, refl }⟩, inv_fun := λ F, of_compat F.2, left_inv := λ x, by { ext, refl }, right_inv := by { rintro ⟨x, hx⟩, simp only [truncate_of_compat], } } section topological_structure instance : topological_space (Mbar_le r' S c) := topological_space.induced eqv (by apply_instance) lemma is_open_iff {U : set (Mbar_bdd.limit r' ⟨S⟩ c)} : is_open (eqv ⁻¹' U) ↔ is_open U := begin rw is_open_induced_iff, have := function.surjective.preimage_injective (equiv.surjective (eqv : Mbar_le r' S c ≃ _)), simp only [iff_self, this.eq_iff], simp only [exists_eq_right], end /-- The homeomorphism between `Mbar_le r' S c` and the profinite limit of the spaces `Mbar_bdd r' ⟨S⟩ c M`. This is `Mbar_le.eqv`, lifted to a homeomorphism by transporting the topology from the profinite limit to `Mbar_le`. -/ def homeo : Mbar_le r' S c ≃ₜ Mbar_bdd.limit r' ⟨S⟩ c := { continuous_to_fun := begin simp only [equiv.to_fun_as_coe, continuous_def], intros U hU, rwa is_open_iff end, continuous_inv_fun := begin simp only [equiv.to_fun_as_coe, continuous_def], intros U hU, erw [← eqv.image_eq_preimage, ← is_open_iff], rwa eqv.preimage_image U, end, ..eqv } lemma truncate_eq (M : ℕ) : (truncate M : Mbar_le r' S c → Mbar_bdd r' ⟨S⟩ c M) = (Mbar_bdd.proj M) ∘ homeo := rfl instance : t2_space (Mbar_le r' S c) := ⟨λ x y h, separated_by_continuous homeo.continuous (λ c, h $ homeo.injective c)⟩ instance [fact (0 < r')] : compact_space (Mbar_le r' S c) := begin constructor, rw homeo.embedding.is_compact_iff_is_compact_image, simp only [set.image_univ, homeomorph.range_coe], obtain ⟨h⟩ := (by apply_instance : compact_space (Mbar_bdd.limit r' ⟨S⟩ c)), exact h, end instance : totally_disconnected_space (Mbar_le r' S c) := { is_totally_disconnected_univ := begin rintros A - hA, suffices subsing : (homeo '' A).subsingleton, { intros x hx y hy, apply_rules [homeo.injective, subsing, set.mem_image_of_mem] }, obtain ⟨h⟩ := (by apply_instance : totally_disconnected_space (Mbar_bdd.limit r' ⟨S⟩ c)), exact h _ (by tauto) (is_preconnected.image hA _ homeo.continuous.continuous_on) end } lemma continuous_iff {α : Type*} [topological_space α] (f : α → Mbar_le r' S c) : continuous f ↔ (∀ M, continuous ((truncate M) ∘ f)) := begin split, { intros hf M, rw [truncate_eq, function.comp.assoc], revert M, rw ← Mbar_bdd.continuous_iff, refine continuous.comp homeo.continuous hf }, { intro h, suffices : continuous (homeo ∘ f), by rwa homeo.comp_continuous_iff at this, rw Mbar_bdd.continuous_iff, exact h } end lemma continuous_truncate {M} : continuous (@truncate r' S _ c M) := (continuous_iff id).mp continuous_id _ lemma continuous_add' : continuous (Mbar_le.add' (c₁ + c₂) : Mbar_le r' S c₁ × Mbar_le r' S c₂ → Mbar_le r' S (c₁+c₂)) := begin rw continuous_iff, intros M, have : truncate M ∘ (λ x : Mbar_le r' S c₁ × Mbar_le r' S c₂, Mbar_le.add _ x.1 x.2) = (λ x : (Mbar_le r' S c₁ × Mbar_le r' S c₂), Mbar_bdd.add (truncate M x.1) (truncate M x.2)) := by {ext; refl}, erw this, suffices : continuous (λ x : Mbar_bdd r' ⟨S⟩ c₁ M × Mbar_bdd r' ⟨S⟩ c₂ M, Mbar_bdd.add x.1 x.2), { have claim : (λ x : (Mbar_le r' S c₁ × Mbar_le r' S c₂), Mbar_bdd.add (truncate M x.1) (truncate M x.2)) = (λ x : Mbar_bdd r' ⟨S⟩ c₁ M × Mbar_bdd r' ⟨S⟩ c₂ M, Mbar_bdd.add x.1 x.2) ∘ (λ x : Mbar_le r' S c₁ × Mbar_le r' S c₂, (truncate M x.1, truncate M x.2)), by {ext, refl}, rw claim, refine continuous.comp this _, refine continuous.prod_map continuous_truncate continuous_truncate }, exact continuous_of_discrete_topology, end lemma continuous_neg : continuous (Mbar_le.neg : Mbar_le r' S c → Mbar_le r' S c) := begin rw continuous_iff, intro M, change continuous (λ x : Mbar_le r' S c, Mbar_bdd.neg (truncate M x)), exact continuous.comp continuous_of_discrete_topology continuous_truncate, end end topological_structure lemma continuous_cast_le (r' : ℝ≥0) (S : Type u) [fintype S] (c₁ c₂ : ℝ≥0) [hc : fact (c₁ ≤ c₂)] : continuous (@Mbar_le.cast_le r' S _ c₁ c₂ _) := begin rw continuous_iff, intro M, simp only [function.comp, truncate_cast_le], exact continuous_bot.comp continuous_truncate end /-! We now prove some scaffolding lemmas in order to prove that the action of `T⁻¹` is continuous. -/ lemma continuous_of_normed_group_hom (f : (Mbar r' S) →+ (Mbar r' S)) (g : Mbar_le r' S c₁ → Mbar_le r' S c₂) (h : ∀ x, ↑(g x) = f x) (H : ∀ M, ∃ N, ∀ (F : Mbar r' S), (∀ s i, i < N + 1 → F s i = 0) → (∀ s i, i < M + 1 → f F s i = 0)) : continuous g := begin rw continuous_iff, intros M, rcases H M with ⟨N, hN⟩, let φ : Mbar_bdd r' ⟨S⟩ c₁ N → Mbar_le r' S c₁ := classical.some (truncate_surjective N).has_right_inverse, have hφ : function.right_inverse φ (truncate N) := classical.some_spec (truncate_surjective N).has_right_inverse, suffices : truncate M ∘ g = truncate M ∘ g ∘ φ ∘ truncate N, { rw [this, ← function.comp.assoc, ← function.comp.assoc], apply continuous_bot.comp continuous_truncate }, ext1 x, suffices : ∀ s i, i < M + 1 → (g x) s i = (g (φ (truncate N x))) s i, { ext s i, dsimp [function.comp], apply this, exact i.property }, intros s i hi, rw [← coe_coe_to_fun, h, ← coe_coe_to_fun, h, ← sub_eq_zero], show ((f x) - f (φ (truncate N x))) s i = 0, rw [← f.map_sub], apply hN _ _ _ _ hi, clear hi i s, intros s i hi, simp only [Mbar.coe_sub, pi.sub_apply, sub_eq_zero], suffices : ∀ s i, (truncate N x) s i = truncate N (φ (truncate N x)) s i, { exact this s ⟨i, hi⟩ }, intros s i, congr' 1, rw hφ (truncate N x) end /-- Construct a map between `Mbar_le r' S c₁` and `Mbar_le r' S c₂` from a bounded group homomorphism `Mbar r' S → Mbar r' S`. If `f` satisfies a suitable criterion, then the constructed map is continuous for the profinite topology; see `continuous_of_normed_group_hom`. -/ def hom_of_normed_group_hom {C : ℝ≥0} (c₁ c₂ : ℝ≥0) [hc : fact (C * c₁ ≤ c₂)] (f : Mbar r' S →+ Mbar r' S) (h : f ∈ filtration (Mbar r' S →+ Mbar r' S) C) (F : Mbar_le r' S c₁) : Mbar_le r' S c₂ := ⟨{ to_fun := λ s i, f F s i, coeff_zero' := Mbar.coeff_zero _, summable' := Mbar.summable _ }, filtration_mono hc.out (h F.mem_filtration)⟩ lemma continuous_hom_of_normed_group_hom {C : ℝ≥0} (c₁ c₂ : ℝ≥0) [hc : fact (C * c₁ ≤ c₂)] (f : Mbar r' S →+ Mbar r' S) (h : f ∈ filtration (Mbar r' S →+ Mbar r' S) C) (H : ∀ M, ∃ N, ∀ (F : Mbar r' S), (∀ s i, i < N + 1 → F s i = 0) → (∀ s i, i < M + 1 → f F s i = 0)) : continuous (hom_of_normed_group_hom c₁ c₂ f h) := continuous_of_normed_group_hom f _ (λ F, by { ext, refl }) H @[simp] lemma coe_hom_of_normed_group_hom_apply {C : ℝ≥0} (c₁ c₂ : ℝ≥0) [hc : fact (C * c₁ ≤ c₂)] (f : Mbar r' S →+ Mbar r' S) (h : f ∈ filtration (Mbar r' S →+ Mbar r' S) C) (F : (Mbar_le r' S c₁)) (s : S) (i : ℕ) : (hom_of_normed_group_hom c₁ c₂ f h) F s i = f F s i := rfl section Tinv /-! ### The action of T⁻¹ -/ /-- The action of `T⁻¹` as map `Mbar_le r S c₁ → Mbar_le r S c₂`. This action is induced by the action of `T⁻¹` on power series modulo constants: `ℤ⟦T⟧/ℤ`. So `T⁻¹` sends `T^(n+1)` to `T^n`, but `T^0 = 0`. -/ def Tinv {r : ℝ≥0} {S : Type u} [fintype S] {c₁ c₂ : ℝ≥0} [fact (0 < r)] [fact (r⁻¹ * c₁ ≤ c₂)] : Mbar_le r S c₁ → Mbar_le r S c₂ := hom_of_normed_group_hom c₁ c₂ Mbar.Tinv Mbar.Tinv_mem_filtration @[simp] lemma Tinv_apply {r : ℝ≥0} {S : Type u} [fintype S] {c₁ c₂ : ℝ≥0} [fact (0 < r)] [fact (r⁻¹ * c₁ ≤ c₂)] (F : Mbar_le r S c₁) (s : S) (i : ℕ) : (Tinv F : Mbar_le r S c₂) s i = Mbar.Tinv (F : Mbar r S) s i := rfl lemma continuous_Tinv (r : ℝ≥0) (S : Type u) [fintype S] (c₁ c₂ : ℝ≥0) [fact (0 < r)] [fact (r⁻¹ * c₁ ≤ c₂)] : continuous (@Tinv r S _ c₁ c₂ _ _) := continuous_hom_of_normed_group_hom c₁ c₂ _ Mbar.Tinv_mem_filtration $ begin intros M, use M+1, rintro F hF s (_|i) hi, { simp only [Mbar.Tinv, add_monoid_hom.mk'_apply, Mbar.coe_mk, Mbar.Tinv_aux_zero] }, { simp only [Mbar.Tinv, Mbar.Tinv_aux_succ, add_monoid_hom.mk'_apply, Mbar.coe_mk], apply hF, exact nat.succ_lt_succ hi }, end end Tinv section map /-- TODO -/ def map {S T : Fintype} (f : S ⟶ T) : Mbar_le r' S c → Mbar_le r' T c := λ F, ⟨(F : Mbar r' S).map f, Mbar.nnnorm_map_le_of_nnnorm_le _ _ F.2⟩ lemma map_truncate {S T : Fintype} (f : S ⟶ T) (F : Mbar_le r' S c) (M : ℕ) : ((F.truncate M).map f) = (F.map f).truncate M := rfl lemma map_continuous {S T : Fintype} (f : S ⟶ T) : continuous (map f : Mbar_le r' S c → Mbar_le r' T c) := begin rw continuous_iff, intros M, have : truncate M ∘ (map f : Mbar_le r' S c → Mbar_le r' T c) = Mbar_bdd.map f ∘ truncate M, { ext, refl }, rw this, refine continuous.comp _ continuous_truncate, continuity, end end map variables (r' c) /-- A version of `Mbar_le` which is functorial in `S`. -/ @[simps] def Fintype_functor [fact (0 < r')]: Fintype ⥤ Profinite := { obj := λ S, Profinite.of $ Mbar_le r' S c, map := λ S T f, { to_fun := map f, continuous_to_fun := map_continuous _ }, map_id' := λ S, begin ext1, exact subtype.ext x.1.map_id, end, map_comp' := λ S T U f g, begin ext1, exact subtype.ext (x.1.map_comp f g), end } variables (c₁ c₂) /-- The functor sending S to the (categorical) product of `Mbar_le r' S c₁` and `Mbar_le r' S c₂`. -/ @[simps] def Fintype_functor_prod [fact (0 < r')] : Fintype ⥤ Profinite := { obj := λ S, (S,S), map := λ _ _ f, (f,f) } ⋙ (Fintype_functor r' c₁).prod (Fintype_functor r' c₂) ⋙ (uncurry.obj prod.functor) /-- This is a functorial version of `add'`. -/ @[simps] def Fintype_add_functor [fact (0 < r')] : Fintype_functor_prod r' c₁ c₂ ⟶ Fintype_functor r' (c₁ + c₂) := { app := λ S, (Profinite.prod_iso _ _).hom ≫ ⟨add' _, continuous_add'⟩, naturality' := begin intros S T f, ext, dsimp only [functor.prod, Profinite.prod_iso, Fintype_functor_prod, uncurry, prod.functor, functor.comp_map], rw [category_theory.limits.prod.map_map, category.comp_id, category.id_comp], dsimp [map, Mbar.map, add', add, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso], rw finset.sum_add_distrib, -- annoying have useful : ∀ {A B C : Profinite} (f : A ⟶ B) (g : B ⟶ C) (a : A), (f ≫ g) a = g (f a) := λ _ _ _ _ _ _, rfl, congr, { have : binary_fan.fst (limit.cone (pair (Profinite.of (Mbar_le r' ↥T c₁)) (Profinite.of (Mbar_le r' ↥T c₂)))) = category_theory.limits.prod.fst := rfl, rw [this, ← useful, category_theory.limits.prod.map_fst], refl }, { have : binary_fan.snd (limit.cone (pair (Profinite.of (Mbar_le r' ↥T c₁)) (Profinite.of (Mbar_le r' ↥T c₂)))) = category_theory.limits.prod.snd := rfl, rw [this, ← useful, category_theory.limits.prod.map_snd], refl }, end} /-- Negation on `Mbar_le` as a functor in `S`. -/ def Fintype_neg_functor [fact (0 < r')] : Fintype_functor r' c ⟶ Fintype_functor r' c := { app := λ S, ⟨Mbar_le.neg, Mbar_le.continuous_neg⟩, naturality' := begin intros A B f, ext, dsimp [map, neg], simp, end } variables {c₁ c₂} open category_theory /-- A bifunctor version of `Fintype_functor`, where `c` can vary. -/ @[simps] def Fintype_bifunctor [fact (0 < r')] : ℝ≥0 ⥤ Fintype ⥤ Profinite := { obj := λ c, Fintype_functor r' c, map := λ c₁ c₂ f, { app := λ S, { to_fun := @Mbar_le.cast_le r' S _ c₁ c₂ ⟨le_of_hom f⟩, continuous_to_fun := by apply continuous_cast_le } }, map_id' := λ c, by { ext, refl }, map_comp' := λ a b c f g, by { ext, refl } } /-- The extension of `Fintype_functor` to `Profinite` obtained by taking limits. -/ @[simps] def functor [fact (0 < r')] : Profinite ⥤ Profinite := Profinite.extend (Fintype_functor r' c) variables (c₁ c₂) /-- The profinite variant of `Fintype_functor_prod`. -/ @[simps] def functor_prod [fact (0 < r')] : Profinite ⥤ Profinite := { obj := λ S, (S,S), map := λ _ _ f, (f, f) } ⋙ (functor r' c₁).prod (functor r' c₂) ⋙ (uncurry.obj prod.functor) /-- A cone over `(S.fintype_diagram ⋙ Fintype_functor_prod r' c₁ c₂)` used in the definition of `add_functor`. -/ def functor_prod_cone [fact (0 < r')] (S : Profinite) : cone (S.fintype_diagram ⋙ Fintype_functor_prod r' c₁ c₂) := { X := (functor_prod r' c₁ c₂).obj S, π := { app := λ I, category_theory.limits.prod.map (limit.π _ I) (limit.π _ I), naturality' := begin intros I J f, dsimp [Fintype_functor_prod], simp [← limit.w _ f], end } } -- TODO: this proof is SLOW. /-- The profinite variant of `Fintype_add_functor`. -/ def add_functor [fact (0 < r')] : functor_prod r' c₁ c₂ ⟶ functor r' (c₁ + c₂) := -- Why doesn't this work without the "by apply ..."? { app := λ S, by apply limit.lift _ (functor_prod_cone r' c₁ c₂ S) ≫ category_theory.limits.lim.map (whisker_left _ (Fintype_add_functor _ _ _)), naturality' := begin intros S T f, erw [limits.limit.lift_map, limits.limit.lift_map], dsimp only [whisker_left, limits.cones.postcompose], apply limit.hom_ext, intros I, dsimp only [nat_trans.comp_app, functor, Profinite.extend, Profinite.change_cone], simp_rw [category.assoc, limits.limit.lift_π], change _ = _ ≫ limit.π _ _ ≫ _, simp_rw [← category.assoc, limits.limit.lift_π], dsimp only [nat_trans.comp_app, functor_prod_cone, functor_prod, functor.comp_map, uncurry, limits.prod.functor], simp only [limits.prod.map_map, category.id_comp, category.comp_id, category.assoc], let e : Fintype.of (I.comap f.continuous) ⟶ Fintype.of I := discrete_quotient.map (le_refl _), erw ← (Fintype_add_functor r' c₁ c₂).naturality e, simp_rw ← category.assoc, dsimp only [Fintype_functor_prod, functor.comp_map, uncurry, limits.prod.functor, functor.prod, functor, Profinite.extend], simp only [limits.prod.map_map, category.id_comp, category.comp_id, limits.limit.lift_π], refl, end } /-- The profinite functorial variant of negation on `Mbar_le`. -/ def neg_functor [fact (0 < r')] : functor r' c ⟶ functor r' c := { app := λ X, limits.lim.map $ whisker_left _ $ Fintype_neg_functor _ _, naturality' := begin intros A B f, apply limit.hom_ext, intros S, dsimp, simp, end } variables {c₁ c₂} /-- A bifunctor version of `functor`, where `c` can vary. -/ @[simps] def bifunctor [fact (0 < r')] : ℝ≥0 ⥤ Profinite ⥤ Profinite := { obj := λ c, functor r' c, map := λ a b f, Profinite.extend_nat_trans $ (Fintype_bifunctor r').map f, map_id' := begin intros c, rw (Fintype_bifunctor r').map_id, exact Profinite.extend_nat_trans_id _, end, map_comp' := begin intros a b c α β, rw (Fintype_bifunctor r').map_comp, exact Profinite.extend_nat_trans_comp _ _, end } /-- `Mbar_le.functor r' c` is indeed an extension of `Mbar_le.Fintype_functor r' c`. -/ @[simps] def functor_extends [fact (0 < r')] : Fintype.to_Profinite ⋙ functor r' c ≅ Fintype_functor r' c := Profinite.extend_extends _ . variables {r' c} end Mbar_le instance [fact (0 < r')] : profinitely_filtered_pseudo_normed_group (Mbar r' S) := { topology := λ c, show topological_space (Mbar_le r' S c), by apply_instance, t2 := λ c, show t2_space (Mbar_le r' S c), by apply_instance, td := λ c, show totally_disconnected_space (Mbar_le r' S c), by apply_instance, compact := λ c, show compact_space (Mbar_le r' S c), by apply_instance, continuous_add' := λ c₁ c₂, Mbar_le.continuous_add', continuous_neg' := λ c, Mbar_le.continuous_neg, continuous_cast_le := λ c₁ c₂, begin introI h, rw show pseudo_normed_group.cast_le = (Mbar_le.cast_le : Mbar_le r' S c₁ → Mbar_le r' S c₂), by {ext, refl}, exact Mbar_le.continuous_cast_le r' S c₁ c₂, end, .. Mbar.pseudo_normed_group } namespace Mbar variable r' /-- The diagram whose colimit yields `Mbar.profinite`. -/ def profinite_diagram [fact (0 < r')] : ℝ≥0 ⥤ Profinite.{u} ⥤ Type u := let E := (whiskering_right Profinite _ _).obj (forget Profinite) in ((whiskering_right _ _ _).obj E).obj (Mbar_le.bifunctor.{u u} r') /-- The functor `Mbar : Profinite ⥤ Type*`. -/ def profinite [fact (0 < r')] : Profinite ⥤ Type* := (as_small.down ⋙ profinite_diagram r').flip ⋙ colim -- TODO: Move this to the condensed folder, once it's more stable! /-- The representable presheaf associated to a profinite set. -/ def representable : Profinite.{u} ⥤ (as_small.{u+1} Profinite.{u})ᵒᵖ ⥤ Type (u+1) := let Y := @yoneda (as_small.{u+1} Profinite.{u}) _ in ((whiskering_right Profinite.{u} _ _).obj Y).obj as_small.up /-- The diagram whose colimit yields `Mbar.precondensed`. -/ def precondensed_diagram [fact (0 < r')] : ℝ≥0 ⥤ Profinite.{u} ⥤ (as_small.{u+1} Profinite.{u})ᵒᵖ ⥤ Type (u+1) := let E := (whiskering_right Profinite _ _).obj representable in ((whiskering_right _ _ _).obj E).obj $ Mbar_le.bifunctor.{u u} r' /-- A functor associating to every `S : Profinite` the presheaf associated to the condensed set `Mbar(S)`. -/ -- TODO: Prove that it is a condensed set! def precondensed [fact (0 < r')] : Profinite.{u} ⥤ (as_small.{u+1} Profinite.{u})ᵒᵖ ⥤ Type (u+1) := (as_small.down.{_ _ (u+1)} ⋙ precondensed_diagram.{u} r').flip ⋙ colim end Mbar #lint-
2ea938fdac5c2f6161d240b329b33da88c2fe65c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/nat/prime.lean
dccb25533a6cf5a15ba0fab21b2ee23608db1b28
[ "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
46,581
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.list.prime import data.list.sort import data.nat.gcd import data.nat.sqrt import tactic.norm_num import tactic.wlog /-! # Prime numbers This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations - `nat.prime`: the predicate that expresses that a natural number `p` is prime - `nat.primes`: the subtype of natural numbers that are prime - `nat.min_fac n`: the minimal prime factor of a natural number `n ≠ 1` - `nat.exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers - `nat.factors n`: the prime factorization of `n` - `nat.factors_unique`: uniqueness of the prime factorisation * `nat.prime_iff`: `nat.prime` coincides with the general definition of `prime` * `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime -/ open bool subtype open_locale nat namespace nat /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ @[pp_nodot] def prime (p : ℕ) := _root_.irreducible p theorem _root_.irreducible_iff_nat_prime (a : ℕ) : irreducible a ↔ nat.prime a := iff.rfl theorem not_prime_zero : ¬ prime 0 | h := h.ne_zero rfl theorem not_prime_one : ¬ prime 1 | h := h.ne_one rfl theorem prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := irreducible.ne_zero h theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := nat.pos_of_ne_zero pp.ne_zero theorem prime.two_le : ∀ {p : ℕ}, prime p → 2 ≤ p | 0 h := (not_prime_zero h).elim | 1 h := (not_prime_one h).elim | (n+2) _ := le_add_self theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le instance prime.one_lt' (p : ℕ) [hp : _root_.fact p.prime] : _root_.fact (1 < p) := ⟨hp.1.one_lt⟩ lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := hp.one_lt.ne' lemma two_le_iff (n : ℕ) : 2 ≤ n ↔ n ≠ 0 ∧ ¬is_unit n := begin rw nat.is_unit_iff, rcases n with _|_|m; norm_num [one_lt_succ_succ, succ_le_iff] end lemma prime.eq_one_or_self_of_dvd {p : ℕ} (pp : p.prime) (m : ℕ) (hm : m ∣ p) : m = 1 ∨ m = p := begin obtain ⟨n, hn⟩ := hm, have := pp.is_unit_or_is_unit hn, rw [nat.is_unit_iff, nat.is_unit_iff] at this, apply or.imp_right _ this, rintro rfl, rw [hn, mul_one] end theorem prime_def_lt'' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p := begin refine ⟨λ h, ⟨h.two_le, h.eq_one_or_self_of_dvd⟩, λ h, _⟩, have h1 := one_lt_two.trans_le h.1, refine ⟨mt nat.is_unit_iff.mp h1.ne', λ a b hab, _⟩, simp only [nat.is_unit_iff], apply or.imp_right _ (h.2 a _), { rintro rfl, rw [←nat.mul_right_inj (pos_of_gt h1), ←hab, mul_one] }, { rw hab, exact dvd_mul_right _ _ } end theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 := prime_def_lt''.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (le_of_dvd (le_of_succ_le p2) d).lt_or_eq_dec.imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ nat.mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ theorem prime_of_coprime (n : ℕ) (h1 : 1 < n) (h : ∀ m < n, m ≠ 0 → n.coprime m) : prime n := begin refine prime_def_lt.mpr ⟨h1, λ m mlt mdvd, _⟩, have hm : m ≠ 0, { rintro rfl, rw zero_dvd_iff at mdvd, exact mlt.ne' mdvd }, exact (h m mlt hm).symm.eq_one_of_dvd mdvd, end section /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel for small values. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ local attribute [instance] def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' theorem prime_two : prime 2 := dec_trivial end theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.eq_one_or_self_of_dvd m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_rfl)⟩ theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.prime) (qp : q.prime) : p ∣ q ↔ p = q := dvd_prime_two_le qp (prime.two_le pp) theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.one_lt) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _) lemma not_prime_mul' {a b n : ℕ} (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ prime n := by { rw ← h, exact not_prime_mul h₁ h₂ } section min_fac lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) : sqrt n - k < sqrt n + 2 - k := (tsub_lt_tsub_iff_right $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial /-- If `n < k * k`, then `min_fac_aux n k = n`, if `k | n`, then `min_fac_aux n k = k`. Otherwise, `min_fac_aux n k = min_fac_aux n (k+2)` using well-founded recursion. If `n` is odd and `1 < n`, then then `min_fac_aux n 3` is the smallest prime factor of `n`. -/ def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := by simp | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := 2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) : ∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_rfl, λ m m2 d, le_of_eq ((dvd_prime_two_le pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := a _ le_rfl (dvd_of_mul_right_dvd d), rw e at this, exact absurd this dec_trivial } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_rfl, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := if n1 : n = 1 then by simp [n1] else (min_fac_has_prop n1).2.1 theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (d.trans fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : 0 < min_fac n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem le_min_fac {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, prime p → p ∣ n → m ≤ p := ⟨λ h p pp d, h.elim (by rintro rfl; cases pp.not_dvd_one d) (λ h, le_trans h $ min_fac_le_of_dvd pp.two_le d), λ H, or_iff_not_imp_left.2 $ λ n1, H _ (min_fac_prime n1) (min_fac_dvd _)⟩ theorem le_min_fac' {m n : ℕ} : n = 1 ∨ m ≤ min_fac n ↔ ∀ p, 2 ≤ p → p ∣ n → m ≤ p := ⟨λ h p (pp:1<p) d, h.elim (by rintro rfl; cases not_le_of_lt pp (le_of_dvd dec_trivial d)) (λ h, le_trans h $ min_fac_le_of_dvd pp d), λ H, le_min_fac.2 (λ p pp d, H p pp.two_le d)⟩ theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p := ⟨λ pp, ⟨pp.two_le, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ @[simp] lemma prime.min_fac_eq {p : ℕ} (hp : prime p) : min_fac p = p := (prime_def_min_fac.1 hp).2 /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n := match min_fac_dvd n with | ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial | ⟨1, h1⟩ := begin rw mul_one at h1, rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false, not_le] at np, rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one] end | ⟨(x+2), hx⟩ := begin conv_rhs { congr, rw hx }, rw [nat.mul_div_cancel_left _ (min_fac_pos _)], exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩ end end /-- The square of the smallest prime factor of a composite number `n` is at most `n`. -/ lemma min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬ prime n) : (min_fac n)^2 ≤ n := have t : (min_fac n) ≤ (n/min_fac n) := min_fac_le_div w h, calc (min_fac n)^2 = (min_fac n) * (min_fac n) : sq (min_fac n) ... ≤ (n/min_fac n) * (min_fac n) : nat.mul_le_mul_right (min_fac n) t ... ≤ n : div_mul_le_self n (min_fac n) @[simp] lemma min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 := begin split, { intro h, by_contradiction hn, have := min_fac_prime hn, rw h at this, exact not_prime_one this, }, { rintro rfl, refl, } end @[simp] lemma min_fac_eq_two_iff (n : ℕ) : min_fac n = 2 ↔ 2 ∣ n := begin split, { intro h, convert min_fac_dvd _, rw h, }, { intro h, have ub := min_fac_le_of_dvd (le_refl 2) h, have lb := min_fac_pos n, apply ub.eq_or_lt.resolve_right (λ h', _), have := le_antisymm (nat.succ_le_of_lt lb) (lt_succ_iff.mp h'), rw [eq_comm, nat.min_fac_eq_one_iff] at this, subst this, exact not_lt_of_le (le_of_dvd zero_lt_one h) one_lt_two } end end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : 2 ≤ n) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ /-- Euclid's theorem on the **infinitude of primes**. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p := let p := min_fac (n! + 1) in have f1 : n! + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ factorial_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ n!, from dvd_factorial (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := p.mod_two_eq_zero_or_one.imp_left (λ h, ((hp.eq_one_or_self_of_dvd 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, prime k → k ∣ m → ¬ k ∣ n) : coprime m n := begin have g1 : 1 ≤ gcd m n, { refine nat.succ_le_of_lt (pos_iff_ne_zero.mpr (λ g0, _)), rw [eq_zero_of_gcd_eq_zero_left g0, eq_zero_of_gcd_eq_zero_right g0] at H, exact H 2 prime_two (dvd_zero _) (dvd_zero _) }, rw [coprime_iff_gcd_eq_one, eq_comm], refine g1.lt_or_eq.resolve_left (λ g2, _), obtain ⟨p, hp, hpdvd⟩ := exists_prime_and_dvd (succ_le_of_lt g2), apply H p hp; apply dvd_trans hpdvd, { exact gcd_dvd_left _ _ }, { exact gcd_dvd_right _ _ } end theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, prime k → k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd $ λk kp km kn, not_le_of_gt kp.one_lt $ le_of_dvd zero_lt_one $ H k kp km kn theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) @[simp] lemma factors_zero : factors 0 = [] := by rw factors @[simp] lemma factors_one : factors 1 = [] := by rw factors lemma prime_of_mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := by simp | 1 := by simp | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 (by rwa [factors] at h), or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) prime_of_mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := by simp | 1 := by simp | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show (factors n).prod = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [factors, list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] := begin have : p = (p - 2) + 2 := (tsub_eq_iff_eq_add_of_le hp.two_le).mp rfl, rw [this, nat.factors], simp only [eq.symm this], have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2, split, { exact this, }, { simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], }, end lemma factors_chain : ∀ {n a}, (∀ p, prime p → p ∣ n → a ≤ p) → list.chain (≤) a (factors n) | 0 := λ a h, by simp | 1 := λ a h, by simp | n@(k+2) := λ a h, let m := min_fac n in have n / m < n := factors_lemma, begin rw factors, refine list.chain.cons ((le_min_fac.2 h).resolve_left dec_trivial) (factors_chain _), exact λ p pp d, min_fac_le_of_dvd pp.two_le (d.trans $ div_dvd_of_dvd $ min_fac_dvd _), end lemma factors_chain_2 (n) : list.chain (≤) 2 (factors n) := factors_chain $ λ p pp _, pp.two_le lemma factors_chain' (n) : list.chain' (≤) (factors n) := @list.chain'.tail _ _ (_::_) (factors_chain_2 _) lemma factors_sorted (n : ℕ) : list.sorted (≤) (factors n) := (list.chain'_iff_pairwise (@le_trans _ _)).1 (factors_chain' _) /-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/ lemma factors_add_two (n : ℕ) : factors (n+2) = min_fac (n+2) :: factors ((n+2) / min_fac (n+2)) := by rw factors @[simp] lemma factors_eq_nil (n : ℕ) : n.factors = [] ↔ n = 0 ∨ n = 1 := begin split; intro h, { rcases n with (_ | _ | n), { exact or.inl rfl }, { exact or.inr rfl }, { rw factors at h, injection h }, }, { rcases h with (rfl | rfl), { exact factors_zero }, { exact factors_one }, } end lemma eq_of_perm_factors {a b : ℕ} (ha : 0 < a) (hb : 0 < b) (h : a.factors ~ b.factors) : a = b := by simpa [prod_factors ha, prod_factors hb] using list.perm.prod_eq h lemma eq_of_count_factors_eq {a b : ℕ} (ha : 0 < a) (hb : 0 < b) (h : ∀ p : ℕ, list.count p a.factors = list.count p b.factors) : a = b := eq_of_perm_factors ha hb (list.perm_iff_count.mpr h) theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((prime_dvd_prime_iff_eq m2 pp).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.not_coprime_iff_dvd {m n : ℕ} : ¬ coprime m n ↔ ∃p, prime p ∧ p ∣ m ∧ p ∣ n := begin apply iff.intro, { intro h, exact ⟨min_fac (gcd m n), min_fac_prime h, ((min_fac_dvd (gcd m n)).trans (gcd_dvd_left m n)), ((min_fac_dvd (gcd m n)).trans (gcd_dvd_right m n))⟩ }, { intro h, cases h with p hp, apply nat.not_coprime_of_dvd_of_dvd (prime.one_lt hp.1) hp.2.1 hp.2.2 } end theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h : p ∣ m, h.mul_right _) (λ h : p ∣ n, h.mul_left _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime_iff {p : ℕ} : p.prime ↔ _root_.prime p := ⟨λ h, ⟨h.ne_zero, h.not_unit, λ a b, h.dvd_mul.mp⟩, prime.irreducible⟩ theorem irreducible_iff_prime {p : ℕ} : irreducible p ↔ _root_.prime p := by rw [←prime_iff, prime] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := begin induction n with n IH, { exact pp.not_dvd_one.elim h }, { rw pow_succ at h, exact (pp.dvd_mul.1 h).elim id IH } end lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime := λ hp, (hp.eq_one_or_self_of_dvd x $ dvd_trans ⟨x, sq _⟩ (pow_dvd_pow _ hn)).elim (λ hx1, hp.ne_one $ hx1.symm ▸ one_pow _) (λ hxn, lt_irrefl x $ calc x = x ^ 1 : (pow_one _).symm ... < x ^ n : nat.pow_right_strict_mono (hxn.symm ▸ hp.two_le) hn ... = x : hxn.symm) lemma prime.pow_not_prime' {x : ℕ} : ∀ {n : ℕ}, n ≠ 1 → ¬ (x ^ n).prime | 0 := λ _, not_prime_one | 1 := λ h, (h rfl).elim | (n+2) := λ _, prime.pow_not_prime le_add_self lemma prime.eq_one_of_pow {x n : ℕ} (h : (x ^ n).prime) : n = 1 := not_imp_not.mp prime.pow_not_prime' h lemma prime.pow_eq_iff {p a k : ℕ} (hp : p.prime) : a ^ k = p ↔ a = p ∧ k = 1 := begin refine ⟨λ h, _, λ h, by rw [h.1, h.2, pow_one]⟩, rw ←h at hp, rw [←h, hp.eq_one_of_pow, eq_self_iff_true, and_true, pow_one], end lemma pow_min_fac {n k : ℕ} (hk : k ≠ 0) : (n^k).min_fac = n.min_fac := begin rcases eq_or_ne n 1 with rfl | hn, { simp }, have hnk : n ^ k ≠ 1 := λ hk', hn ((pow_eq_one_iff hk).1 hk'), apply (min_fac_le_of_dvd (min_fac_prime hn).two_le ((min_fac_dvd n).pow hk)).antisymm, apply min_fac_le_of_dvd (min_fac_prime hnk).two_le ((min_fac_prime hnk).dvd_of_dvd_pow (min_fac_dvd _)), end lemma prime.pow_min_fac {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) : (p^k).min_fac = p := by rw [pow_min_fac hk, hp.min_fac_eq] lemma prime.mul_eq_prime_sq_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := ⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [sq], begin wlog := hp.dvd_mul.1 pdvdxy using x y, cases case with a ha, have hap : a ∣ p, from ⟨y, by rwa [ha, sq, mul_assoc, nat.mul_right_inj hp.pos, eq_comm] at h⟩, exact ((nat.dvd_prime hp).1 hap).elim (λ _, by clear_aux_decl; simp [*, sq, nat.mul_right_inj hp.pos] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, sq, mul_comm, mul_assoc, nat.mul_right_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at * {contextual := tt}) end, λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (sq _).symm⟩ lemma prime.dvd_factorial : ∀ {n p : ℕ} (hp : prime p), p ∣ n! ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [factorial_succ, hp.dvd_mul, prime.dvd_factorial hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em lemma coprime_of_lt_prime {n p} (n_pos : 0 < n) (hlt : n < p) (pp : prime p) : coprime p n := (coprime_or_dvd_of_prime pp n).resolve_right $ λ h, lt_le_antisymm hlt (le_of_dvd n_pos h) lemma eq_or_coprime_of_le_prime {n p} (n_pos : 0 < n) (hle : n ≤ p) (pp : prime p) : p = n ∨ coprime p n := hle.eq_or_lt.imp eq.symm (λ h, coprime_of_lt_prime n_pos h pp) theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, { simp }, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [e, pow_succ]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, rw [← pow_zero, ← e], apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ', nat.mul_left_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, (pow_zero p).symm⟩ }, { rcases d with ⟨k, l, rfl⟩, exact pow_dvd_pow _ l } } end lemma prime.dvd_mul_of_dvd_ne {p1 p2 n : ℕ} (h_neq : p1 ≠ p2) (pp1 : prime p1) (pp2 : prime p2) (h1 : p1 ∣ n) (h2 : p2 ∣ n) : (p1 * p2 ∣ n) := coprime.mul_dvd_of_dvd_of_dvd ((coprime_primes pp1 pp2).mpr h_neq) h1 h2 /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ lemma eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : prime p) (h₁ : ¬(a ∣ p^k)) (h₂ : a ∣ p^(k+1)) : a = p^(k+1) := begin obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂, congr, exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (prime.one_lt pp))).1 h₁)), end lemma ne_one_iff_exists_prime_dvd : ∀ {n}, n ≠ 1 ↔ ∃ p : ℕ, p.prime ∧ p ∣ n | 0 := by simpa using (Exists.intro 2 nat.prime_two) | 1 := by simp [nat.not_prime_one] | (n+2) := let a := n+2 in let ha : a ≠ 1 := nat.succ_succ_ne_one n in begin simp only [true_iff, ne.def, not_false_iff, ha], exact ⟨a.min_fac, nat.min_fac_prime ha, a.min_fac_dvd⟩, end lemma eq_one_iff_not_exists_prime_dvd {n : ℕ} : n = 1 ↔ ∀ p : ℕ, p.prime → ¬p ∣ n := by simpa using not_iff_not.mpr ne_one_iff_exists_prime_dvd section open list lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod (prime_iff.mp hp) (λ p h, prime_iff.mp (prime_of_mem_factors h)) ((prod_factors hn).symm ▸ h)⟩ lemma dvd_of_mem_factors {n p : ℕ} (h : p ∈ n.factors) : p ∣ n := begin rcases n.eq_zero_or_pos with rfl | hn, { exact dvd_zero p }, { rwa ←mem_factors_iff_dvd hn (prime_of_mem_factors h) } end lemma mem_factors {n p} (hn : n ≠ 0) : p ∈ factors n ↔ prime p ∧ p ∣ n := ⟨λ h, ⟨prime_of_mem_factors h, (mem_factors_iff_dvd hn.bot_lt $ prime_of_mem_factors h).mp h⟩, λ ⟨hprime, hdvd⟩, (mem_factors_iff_dvd hn.bot_lt hprime).mpr hdvd⟩ /-- **Fundamental theorem of arithmetic**-/ lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := begin refine perm_of_prod_eq_prod _ _ _, { rw h₁, refine (prod_factors (nat.pos_of_ne_zero _)).symm, rintro rfl, rw prod_eq_zero_iff at h₁, exact prime.ne_zero (h₂ 0 h₁) rfl }, { simp_rw ←prime_iff, exact h₂ }, { simp_rw ←prime_iff, exact (λ p, prime_of_mem_factors) }, end lemma prime.factors_pow {p : ℕ} (hp : p.prime) (n : ℕ) : (p ^ n).factors = list.repeat p n := begin symmetry, rw ← list.repeat_perm, apply nat.factors_unique (list.prod_repeat p n), intros q hq, rwa eq_of_mem_repeat hq, end /-- For positive `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ lemma perm_factors_mul_of_pos {a b : ℕ} (ha : 0 < a) (hb : 0 < b) : (a * b).factors ~ a.factors ++ b.factors := begin refine (factors_unique _ _).symm, { rw [list.prod_append, prod_factors ha, prod_factors hb] }, { intros p hp, rw list.mem_append at hp, cases hp; exact prime_of_mem_factors hp }, end /-- For coprime `a` and `b`, the prime factors of `a * b` are the union of those of `a` and `b` -/ lemma perm_factors_mul_of_coprime {a b : ℕ} (hab : coprime a b) : (a * b).factors ~ a.factors ++ b.factors := begin rcases a.eq_zero_or_pos with rfl | ha, { simp [(coprime_zero_left _).mp hab] }, rcases b.eq_zero_or_pos with rfl | hb, { simp [(coprime_zero_right _).mp hab] }, exact perm_factors_mul_of_pos ha hb, end /-- For positive `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ lemma count_factors_mul_of_pos {p a b : ℕ} (ha : 0 < a) (hb : 0 < b) : list.count p (a * b).factors = list.count p a.factors + list.count p b.factors := by rw [perm_iff_count.mp (perm_factors_mul_of_pos ha hb) p, count_append] /-- For coprime `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ lemma count_factors_mul_of_coprime {p a b : ℕ} (hab : coprime a b) : list.count p (a * b).factors = list.count p a.factors + list.count p b.factors := by rw [perm_iff_count.mp (perm_factors_mul_of_coprime hab) p, count_append] lemma factors_sublist_right {n k : ℕ} (h : k ≠ 0) : n.factors <+ (n * k).factors := begin cases n, { rw zero_mul }, apply list.sublist_of_subperm_of_sorted _ (factors_sorted _) (factors_sorted _), rw (perm_factors_mul_of_pos nat.succ_pos' (nat.pos_of_ne_zero h)).subperm_left, exact (list.sublist_append_left _ _).subperm, end lemma factors_sublist_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors <+ k.factors := begin obtain ⟨a, rfl⟩ := h, exact factors_sublist_right (right_ne_zero_of_mul h'), end lemma factors_subset_right {n k : ℕ} (h : k ≠ 0) : n.factors ⊆ (n * k).factors := (factors_sublist_right h).subset lemma factors_subset_of_dvd {n k : ℕ} (h : n ∣ k) (h' : k ≠ 0) : n.factors ⊆ k.factors := (factors_sublist_of_dvd h h').subset /-- For any `p`, the power of `p` in `n^k` is `k` times the power in `n` -/ lemma factors_count_pow {n k p : ℕ} : count p (n ^ k).factors = k * count p n.factors := begin induction k with k IH, { simp }, rcases n.eq_zero_or_pos with rfl | hn, { simp [zero_pow (succ_pos k), count_nil, factors_zero, mul_zero] }, rw [pow_succ n k, perm_iff_count.mp (perm_factors_mul_of_pos hn (pow_pos hn k)) p], rw [list.count_append, IH, add_comm, mul_comm, ←mul_succ (count p n.factors) k, mul_comm], end lemma dvd_of_factors_subperm {a b : ℕ} (ha : a ≠ 0) (h : a.factors <+~ b.factors) : a ∣ b := begin rcases b.eq_zero_or_pos with rfl | hb, { exact dvd_zero _ }, rcases a with (_|_|a), { exact (ha rfl).elim }, { exact one_dvd _ }, use (b.factors.diff a.succ.succ.factors).prod, nth_rewrite 0 ←nat.prod_factors ha.bot_lt, rw [←list.prod_append, list.perm.prod_eq $ list.subperm_append_diff_self_of_count_le $ list.subperm_ext_iff.mp h, nat.prod_factors hb] end lemma pow_factors_count_dvd (n p : ℕ) : p ^ n.factors.count p ∣ n := begin by_cases hp : p.prime, { apply dvd_of_factors_subperm (pow_ne_zero _ hp.ne_zero), rw [hp.factors_pow, list.subperm_ext_iff], intros q hq, simp [list.eq_of_mem_repeat hq] }, { rw count_eq_zero_of_not_mem (mt prime_of_mem_factors hp), simp }, end end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l)*p ∣ m*n, by rwa pow_succ' at hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, suffices p^k*p ∣ m ∨ p^l*p ∣ n, by rwa [pow_succ', pow_succ'], hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) /-- The type of prime numbers -/ def primes := {p : ℕ // p.prime} namespace primes instance : has_repr nat.primes := ⟨λ p, repr p.val⟩ instance inhabited_primes : inhabited primes := ⟨⟨2, prime_two⟩⟩ instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩ theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) → p = q := λ h, subtype.eq h end primes instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^p.val⟩ end nat /-! ### Primality prover -/ open norm_num namespace tactic namespace norm_num lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] /-- A predicate representing partial progress in a proof of `min_fac`. -/ def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := begin rw bit0_eq_two_mul, refine (λ e, absurd ((nat.dvd_add_iff_right _).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) _); simp end lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, rw nat.succ_le_iff, refine lt_of_le_of_ne (nat.min_fac_pos _) (λ e, nat.not_prime_one _), rw e, exact nat.min_fac_prime (nat.bit1_lt h).ne', end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' c : ℕ) (e : k + 1 = k') (nc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, refine mt _ (ne_of_gt c0), intro e₁, rw [← nc, ← nat.dvd_iff_mod_eq_zero, ← e₁], apply nat.min_fac_dvd end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 n % bit1 k = 0) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by { rw ← nat.dvd_iff_mod_eq_zero at hd, exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 } lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end /-- Given `e` a natural numeral and `d : nat` a factor of it, return `⊢ ¬ prime e`. -/ meta def prove_non_prime (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt_nat c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (c, e', p) ← prove_mul_nat c e₁ e₂, guard (e' =ₐ e), (c, p₂) ← prove_lt_nat c `(1) e₂, return $ `(@nat.not_prime_mul').mk_app [e₁, e₂, e, p, p₁, p₂] /-- Given `a`,`a1 := bit1 a`, `n1` the value of `a1`, `b` and `p : min_fac_helper a b`, returns `(c, ⊢ min_fac a1 = c)`. -/ meta def prove_min_fac_aux (a a1 : expr) (n1 : ℕ) : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic b p := do k ← b.to_nat, let k1 := bit1 k, let b1 := `(bit1:ℕ→ℕ).mk_app [b], if n1 < k1*k1 then do (ic, e', p₁) ← prove_mul_nat ic b1 b1, (ic, p₂) ← prove_lt_nat ic a1 e', return (ic, a1, `(min_fac_helper_5).mk_app [a, b, e', p₁, p₂, p]) else let d := k1.min_fac in if to_bool (d < k1) then do let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', p₂ ← prove_non_prime b1 k1 d, prove_min_fac_aux ic e' $ `(min_fac_helper_2).mk_app [a, b, e', p₁, p₂, p] else do let nc := n1 % k1, (ic, c, pc) ← prove_div_mod ic a1 b1 tt, if nc = 0 then return (ic, b1, `(min_fac_helper_4).mk_app [a, b, pc, p]) else do (ic, p₀) ← prove_pos ic c, let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', prove_min_fac_aux ic e' $ `(min_fac_helper_3).mk_app [a, b, e', c, p₁, pc, p₀, p] /-- Given `a` a natural numeral, returns `(b, ⊢ min_fac a = b)`. -/ meta def prove_min_fac (ic : instance_cache) (e : expr) : tactic (instance_cache × expr × expr) := match match_numeral e with | match_numeral_result.zero := return (ic, `(2:ℕ), `(nat.min_fac_zero)) | match_numeral_result.one := return (ic, `(1:ℕ), `(nat.min_fac_one)) | match_numeral_result.bit0 e := return (ic, `(2), `(min_fac_bit0).mk_app [e]) | match_numeral_result.bit1 e := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, let a1 := `(bit1:ℕ→ℕ).mk_app [e], prove_min_fac_aux e a1 (bit1 n) c `(1) (`(min_fac_helper_0).mk_app [e, p]) | _ := failed end /-- A partial proof of `factors`. Asserts that `l` is a sorted list of primes, lower bounded by a prime `p`, which multiplies to `n`. -/ def factors_helper (n p : ℕ) (l : list ℕ) : Prop := p.prime → list.chain (≤) p l ∧ (∀ a ∈ l, nat.prime a) ∧ list.prod l = n lemma factors_helper_nil (a : ℕ) : factors_helper 1 a [] := λ pa, ⟨list.chain.nil, by rintro _ ⟨⟩, list.prod_nil⟩ lemma factors_helper_cons' (n m a b : ℕ) (l : list ℕ) (h₁ : b * m = n) (h₂ : a ≤ b) (h₃ : nat.min_fac b = b) (H : factors_helper m b l) : factors_helper n a (b :: l) := λ pa, have pb : b.prime, from nat.prime_def_min_fac.2 ⟨le_trans pa.two_le h₂, h₃⟩, let ⟨f₁, f₂, f₃⟩ := H pb in ⟨list.chain.cons h₂ f₁, λ c h, h.elim (λ e, e.symm ▸ pb) (f₂ _), by rw [list.prod_cons, f₃, h₁]⟩ lemma factors_helper_cons (n m a b : ℕ) (l : list ℕ) (h₁ : b * m = n) (h₂ : a < b) (h₃ : nat.min_fac b = b) (H : factors_helper m b l) : factors_helper n a (b :: l) := factors_helper_cons' _ _ _ _ _ h₁ h₂.le h₃ H lemma factors_helper_sn (n a : ℕ) (h₁ : a < n) (h₂ : nat.min_fac n = n) : factors_helper n a [n] := factors_helper_cons _ _ _ _ _ (mul_one _) h₁ h₂ (factors_helper_nil _) lemma factors_helper_same (n m a : ℕ) (l : list ℕ) (h : a * m = n) (H : factors_helper m a l) : factors_helper n a (a :: l) := λ pa, factors_helper_cons' _ _ _ _ _ h le_rfl (nat.prime_def_min_fac.1 pa).2 H pa lemma factors_helper_same_sn (a : ℕ) : factors_helper a a [a] := factors_helper_same _ _ _ _ (mul_one _) (factors_helper_nil _) lemma factors_helper_end (n : ℕ) (l : list ℕ) (H : factors_helper n 2 l) : nat.factors n = l := let ⟨h₁, h₂, h₃⟩ := H nat.prime_two in have _, from (list.chain'_iff_pairwise (@le_trans _ _)).1 (@list.chain'.tail _ _ (_::_) h₁), (list.eq_of_perm_of_sorted (nat.factors_unique h₃ h₂) this (nat.factors_sorted _)).symm /-- Given `n` and `a` natural numerals, returns `(l, ⊢ factors_helper n a l)`. -/ meta def prove_factors_aux : instance_cache → expr → expr → ℕ → ℕ → tactic (instance_cache × expr × expr) | c en ea n a := let b := n.min_fac in if b < n then do let m := n / b, (c, em) ← c.of_nat m, if b = a then do (c, _, p₁) ← prove_mul_nat c ea em, (c, l, p₂) ← prove_factors_aux c em ea m a, pure (c, `(%%ea::%%l:list ℕ), `(factors_helper_same).mk_app [en, em, ea, l, p₁, p₂]) else do (c, eb) ← c.of_nat b, (c, _, p₁) ← prove_mul_nat c eb em, (c, p₂) ← prove_lt_nat c ea eb, (c, _, p₃) ← prove_min_fac c eb, (c, l, p₄) ← prove_factors_aux c em eb m b, pure (c, `(%%eb::%%l : list ℕ), `(factors_helper_cons).mk_app [en, em, ea, eb, l, p₁, p₂, p₃, p₄]) else if b = a then pure (c, `([%%ea] : list ℕ), `(factors_helper_same_sn).mk_app [ea]) else do (c, p₁) ← prove_lt_nat c ea en, (c, _, p₂) ← prove_min_fac c en, pure (c, `([%%en] : list ℕ), `(factors_helper_sn).mk_app [en, ea, p₁, p₂]) /-- Evaluates the `prime` and `min_fac` functions. -/ @[norm_num] meta def eval_prime : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(ℕ), (c, p₁) ← prove_lt_nat c `(1) e₁, (c, e₁, p) ← prove_min_fac c e, true_intro $ `(is_prime_helper).mk_app [e, p₁, p] end | `(nat.min_fac %%e) := do ic ← mk_instance_cache `(ℕ), prod.snd <$> prove_min_fac ic e | `(nat.factors %%e) := do n ← e.to_nat, match n with | 0 := pure (`(@list.nil ℕ), `(nat.factors_zero)) | 1 := pure (`(@list.nil ℕ), `(nat.factors_one)) | _ := do c ← mk_instance_cache `(ℕ), (c, l, p) ← prove_factors_aux c e `(2) n 2, pure (l, `(factors_helper_end).mk_app [e, l, p]) end | _ := failed end norm_num end tactic namespace nat theorem prime_three : prime 3 := by norm_num instance fact_prime_two : fact (prime 2) := ⟨prime_two⟩ instance fact_prime_three : fact (prime 3) := ⟨prime_three⟩ end nat namespace nat lemma mem_factors_mul {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) {p : ℕ} : p ∈ (a * b).factors ↔ p ∈ a.factors ∨ p ∈ b.factors := begin rw [mem_factors (mul_ne_zero ha hb), mem_factors ha, mem_factors hb, ←and_or_distrib_left], simpa only [and.congr_right_iff] using prime.dvd_mul end /-- If `a`, `b` are positive, the prime divisors of `a * b` are the union of those of `a` and `b` -/ lemma factors_mul_to_finset {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) : (a * b).factors.to_finset = a.factors.to_finset ∪ b.factors.to_finset := (list.to_finset.ext $ λ x, (mem_factors_mul ha hb).trans list.mem_union.symm).trans $ list.to_finset_union _ _ lemma pow_succ_factors_to_finset (n k : ℕ) : (n^(k+1)).factors.to_finset = n.factors.to_finset := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, induction k with k ih, { simp }, rw [pow_succ, factors_mul_to_finset hn (pow_ne_zero _ hn), ih, finset.union_idempotent] end lemma pow_factors_to_finset (n : ℕ) {k : ℕ} (hk : k ≠ 0) : (n^k).factors.to_finset = n.factors.to_finset := begin cases k, { simpa using hk }, rw pow_succ_factors_to_finset end /-- The only prime divisor of positive prime power `p^k` is `p` itself -/ lemma prime_pow_prime_divisor {p k : ℕ} (hk : k ≠ 0) (hp : prime p) : (p^k).factors.to_finset = {p} := by simp [pow_factors_to_finset p hk, factors_prime hp] /-- The sets of factors of coprime `a` and `b` are disjoint -/ lemma coprime_factors_disjoint {a b : ℕ} (hab : a.coprime b) : list.disjoint a.factors b.factors := begin intros q hqa hqb, apply not_prime_one, rw ←(eq_one_of_dvd_coprimes hab (dvd_of_mem_factors hqa) (dvd_of_mem_factors hqb)), exact prime_of_mem_factors hqa end lemma mem_factors_mul_of_coprime {a b : ℕ} (hab : coprime a b) (p : ℕ) : p ∈ (a * b).factors ↔ p ∈ a.factors ∪ b.factors := begin rcases a.eq_zero_or_pos with rfl | ha, { simp [(coprime_zero_left _).mp hab] }, rcases b.eq_zero_or_pos with rfl | hb, { simp [(coprime_zero_right _).mp hab] }, rw [mem_factors_mul ha.ne' hb.ne', list.mem_union] end lemma factors_mul_to_finset_of_coprime {a b : ℕ} (hab : coprime a b) : (a * b).factors.to_finset = a.factors.to_finset ∪ b.factors.to_finset := (list.to_finset.ext $ mem_factors_mul_of_coprime hab).trans $ list.to_finset_union _ _ open list /-- For `0 < b`, the power of `p` in `a * b` is at least that in `a` -/ lemma le_factors_count_mul_left {p a b : ℕ} (hb : 0 < b) : list.count p a.factors ≤ list.count p (a * b).factors := begin rcases a.eq_zero_or_pos with rfl | ha, { simp }, { rw [perm.count_eq (perm_factors_mul_of_pos ha hb) p, count_append p], simp }, end /-- For `a > 0`, the power of `p` in `a * b` is at least that in `b` -/ lemma le_factors_count_mul_right {p a b : ℕ} (ha : 0 < a) : list.count p b.factors ≤ list.count p (a * b).factors := by { rw mul_comm, apply le_factors_count_mul_left ha } /-- If `p` is a prime factor of `a` then `p` is also a prime factor of `a * b` for any `b > 0` -/ lemma mem_factors_mul_left {p a b : ℕ} (hpa : p ∈ a.factors) (hb : 0 < b) : p ∈ (a*b).factors := by { rw ←list.count_pos, exact gt_of_ge_of_gt (le_factors_count_mul_left hb) (count_pos.mpr hpa) } /-- If `p` is a prime factor of `b` then `p` is also a prime factor of `a * b` for any `a > 0` -/ lemma mem_factors_mul_right {p a b : ℕ} (hpb : p ∈ b.factors) (ha : 0 < a) : p ∈ (a*b).factors := by { rw mul_comm, exact mem_factors_mul_left hpb ha } /-- If `p` is a prime factor of `a` then the power of `p` in `a` is the same that in `a * b`, for any `b` coprime to `a`. -/ lemma factors_count_eq_of_coprime_left {p a b : ℕ} (hab : coprime a b) (hpa : p ∈ a.factors) : list.count p (a * b).factors = list.count p a.factors := begin rw count_factors_mul_of_coprime hab, simpa only [count_eq_zero_of_not_mem (coprime_factors_disjoint hab hpa)], end /-- If `p` is a prime factor of `b` then the power of `p` in `b` is the same that in `a * b`, for any `a` coprime to `b`. -/ lemma factors_count_eq_of_coprime_right {p a b : ℕ} (hab : coprime a b) (hpb : p ∈ b.factors) : list.count p (a * b).factors = list.count p b.factors := by { rw mul_comm, exact factors_count_eq_of_coprime_left (coprime_comm.mp hab) hpb } end nat
6a6765c505eaa4dbc64ddb3d585d98f961447be2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/ElimDeadBranches.lean
160a574c7775cf0e0bdc0fd7f603743cebdfe590
[ "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
20,077
lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving -/ import Lean.Compiler.LCNF.CompilerM import Lean.Compiler.LCNF.PassManager import Lean.Compiler.LCNF.PhaseExt import Lean.Compiler.LCNF.InferType namespace Lean.Compiler.LCNF namespace UnreachableBranches /-- The abstract domain of the interpreter. Representing sets of values of a certain type. -/ inductive Value where /-- Undefined, could be anything we have no information. -/ | bot /-- All values are possible. -/ | top /-- A certian consructor with a certain sets of parameters is possible. -/ | ctor (i : Name) (vs : Array Value) /-- A set of values are possible. -/ | choice (vs : List Value) deriving Inhabited, Repr namespace Value -- TODO: parameterize def maxValueDepth := 8 protected partial def beq : Value → Value → Bool | bot, bot => true | top, top => true | ctor i1 vs1 , ctor i2 vs2 => i1 == i2 && Array.isEqv vs1 vs2 Value.beq | choice vs1 , choice vs2 => let isSubset as bs := as.all (fun a => bs.any fun b => Value.beq a b) isSubset vs1 vs2 && isSubset vs2 vs1 | _, _ => false instance : BEq Value := ⟨Value.beq⟩ mutual /-- Fuse `v` into `vs`. That is do not only append but if we see that `v` is a constructor that is already contained within `vs` try to detect the difference between these values and merge them accordingly into a choice node further down the tree. -/ partial def addChoice (vs : List Value) (v : Value) : List Value := match vs, v with | [], v => [v] | v1@(ctor i1 _ ) :: cs, ctor i2 _ => if i1 == i2 then (merge v1 v) :: cs else v1 :: addChoice cs v | _, _ => panic! "invalid addChoice" /-- Merge two values into one. `bot` is the neutral element, `top` the annihilator. -/ partial def merge (v1 v2 : Value) : Value := match v1, v2 with | bot, v | v, bot => v | top, _ | _, top => top | ctor i1 vs1, ctor i2 vs2 => if i1 == i2 then ctor i1 (vs1.zipWith vs2 merge) else choice [v1, v2] | choice vs1, choice vs2 => choice (vs1.foldl addChoice vs2) | choice vs, v | v, choice vs => choice (addChoice vs v) end /-- Make sure constructors of recursive inductive datatypes can only occur once in each path. Values at depth > `maxValueDepth` are also approximated at `top`. We use this function to implement a simple widening operation for our abstract interpreter. Recall the widening functions is used to ensure termination in abstract interpreters. -/ partial def truncate (env : Environment) (v : Value) : Value := go v {} maxValueDepth where go (v : Value) (forbiddenTypes : NameSet) (remainingDepth : Nat) := match remainingDepth with | 0 => top | remainingDepth + 1 => match v with | ctor i vs => let typeName := i.getPrefix if forbiddenTypes.contains typeName then top else let cont forbiddenTypes' := ctor i (vs.map (go · forbiddenTypes' remainingDepth)) match env.find? typeName with | some (.inductInfo type) => if type.isRec then cont <| forbiddenTypes.insert typeName else cont forbiddenTypes | _ => cont forbiddenTypes | choice vs => let vs := vs.map (go · forbiddenTypes remainingDepth) if vs.elem top then top else choice vs | v => v /-- Widening operator that guarantees termination in our abstract interpreter. -/ def widening (env : Environment) (v1 v2 : Value) : Value := truncate env (merge v1 v2) /-- Check whether a certain constructor is part of a `Value` by name. Note that both `top` and `bot` will always true here. For bot this is because we have no information about the `Value` so just to be sure we don't claim the absence of a certain constructor. -/ partial def containsCtor : Value → Name → Bool | .top .., _ => true | .bot .., _ => true -- we don't know so better be safe than sorry | .ctor i .., j => i == j | .choice vs .., j => vs.any fun v => containsCtor v j /-- Obtain the arguments of a certain constructor within the `Value`. -/ partial def getCtorArgs : Value → Name → Option (Array Value) | .ctor i args .., j => if i == j then some args else none | .choice vs .., j => do for variant in vs do if let .ctor i args .. := variant then if i == j then return args none | _, _ => none partial def ofNat (n : Nat) : Value := if n > maxValueDepth then goBig n n else goSmall n where goBig (orig : Nat) (curr : Nat) : Value := if orig - curr == maxValueDepth then .top else .ctor ``Nat.succ #[goBig orig (curr - 1)] goSmall : Nat → Value | 0 => .ctor ``Nat.zero #[] | n + 1 => .ctor ``Nat.succ #[goSmall n] def ofLCNFLit : LCNF.LitValue → Value | .natVal n => ofNat n -- TODO: We could make this much more precise but the payoff is questionable | .strVal .. => .top partial def proj : Value → Nat → Value | .ctor _ vs , i => vs.getD i bot | .choice vs, i => vs.foldl (fun r v => merge r (proj v i)) bot | v, _ => v /-- We say that a `Value` is a literal iff it is only a tree of `Value.ctor` nodes. -/ partial def isLiteral : Value → Bool | .ctor _ vs => vs.all isLiteral | _ => false /- TODO: Add support for "Higher Order Literals", that is literals with type parameters. -/ /-- Attempt to turn a `Value` that is representing a literal into a set of auxiliary declarations + the final `FVarId` of the declaration that contains the actual literal. If it is not a literal return none. -/ partial def getLiteral (v : Value) : CompilerM (Option ((Array CodeDecl) × FVarId)) := do if isLiteral v then let literal ← go v return some literal else return none where go : Value → CompilerM ((Array CodeDecl) × FVarId) | .ctor `Nat.zero #[] .. => do let decl ← mkAuxLetDecl <| .value <| .natVal <| 0 return (#[.let decl], decl.fvarId) | .ctor `Nat.succ #[val] .. => do let val := getNatConstant val + 1 let decl ← mkAuxLetDecl <| .value <| .natVal <| val return (#[.let decl], decl.fvarId) | .ctor i vs => do let args ← vs.mapM go let flatten acc := fun (decls, var) => (acc.fst ++ decls, acc.snd.push <| .fvar var) let (decls, params) := args.foldl (init := (#[], Array.mkEmpty args.size)) flatten let letVal : LetValue := .const i [] params let letDecl ← mkAuxLetDecl letVal return (decls.push <| .let letDecl, letDecl.fvarId) | _ => unreachable! getNatConstant : Value → Nat | .ctor `Nat.zero #[] .. => 0 | .ctor `Nat.succ #[val] .. => getNatConstant val + 1 | _ => panic! "Not a well formed Nat constant Value" end Value /-- A map from function names to the `Value` that the abstract interpreter produced for them. -/ abbrev FunctionSummaries := PHashMap Name Value private abbrev decLt (a b : Name × Value) : Bool := Name.quickLt a.fst b.fst private abbrev findAtSorted? (entries : Array (Name × Value)) (fid : Name) : Option Value := entries.binSearch (fid, default) decLt |>.map Prod.snd /-- Storing `FunctionSummaries` for all functions in a `.olean`. -/ builtin_initialize functionSummariesExt : SimplePersistentEnvExtension (Name × Value) FunctionSummaries ← registerSimplePersistentEnvExtension { addImportedFn := fun _ => {} addEntryFn := fun s ⟨e, n⟩ => s.insert e n toArrayFn := fun s => s.toArray.qsort decLt } /-- Add a `Value` for a function name. -/ def addFunctionSummary (env : Environment) (fid : Name) (v : Value) : Environment := functionSummariesExt.addEntry (env.addExtraName fid) (fid, v) /-- Obtain the `Value` for a function name if possible. -/ def getFunctionSummary? (env : Environment) (fid : Name) : Option Value := match env.getModuleIdxFor? fid with | some modIdx => findAtSorted? (functionSummariesExt.getModuleEntries env modIdx) fid | none => functionSummariesExt.getState env |>.find? fid /-- A map from variable identifiers to the `Value` produced by the abstract interpreter for them. -/ abbrev Assignment := HashMap FVarId Value /-- The context of `InterpM`. -/ structure InterpContext where /-- The list of `Decl`s we are operating on in `InterpM`. This can be a single declaration or a mutual block of declarations where their analysis might influence each other as we approach the fixpoint. -/ decls : Array Decl /-- The index of the function we are currently operating on in `decls.` -/ currFnIdx : Nat := 0 structure InterpState where /-- `Assignment`s of functions in the `InterpContext`. -/ assignments : Array Assignment /-- `Value`s of functions in the `InterpContext` use during computation of the fixpoint. Afterwards they are stored into the `Environment`. -/ funVals : PArray Value /-- The monad which powers the abstract interpreter. -/ abbrev InterpM := ReaderT InterpContext StateRefT InterpState CompilerM /-- Get the variable `Assignment` of the current function. -/ def getAssignment : InterpM Assignment := do return (← get).assignments[(← read).currFnIdx]! /-- Get the `Value` of a certain function in the current block by index. -/ def getFunVal (funIdx : Nat) : InterpM Value := do return (← get).funVals[funIdx]! def findFunVal? (declName : Name) : InterpM (Option Value) := do match (← read).decls.findIdx? (·.name == declName) with | some idx => return some (← getFunVal idx) | none => return none /-- Run `f` on the variable `Assignment` of the current function. -/ def modifyAssignment (f : Assignment → Assignment) : InterpM Unit := do let ctx ← read let currFnIdx := ctx.currFnIdx modify fun s => { s with assignments := s.assignments.modify currFnIdx f } /-- Obtain the `Value` associated with `var` from the context of `InterpM`. If none is available return `Value.bot`. -/ def findVarValue (var : FVarId) : InterpM Value := do let assignment ← getAssignment return assignment.findD var .bot /-- Find the value of `arg` using the logic of `findVarValue`. -/ def findArgValue (arg : Arg) : InterpM Value := do match arg with | .fvar fvarId => findVarValue fvarId | _ => return .top /-- Update the assignment of `var` by merging the current value with `newVal`. -/ def updateVarAssignment (var : FVarId) (newVal : Value) : InterpM Unit := do let val ← findVarValue var let updatedVal := .merge val newVal modifyAssignment (·.insert var updatedVal) /-- Set the value of `var` to `bot`. -/ def resetVarAssignment (var : FVarId) : InterpM Unit := do modifyAssignment (·.insert var .bot) /-- Widen the value of the current function by `v`. -/ def updateCurrFnSummary (v : Value) : InterpM Unit := do let ctx ← read let env ← getEnv let currFnIdx := ctx.currFnIdx modify fun s => { s with funVals := s.funVals.modify currFnIdx (fun v' => .widening env v v') } /-- Return true if the assignment of at least one parameter has been updated. Furthermore if we see that `params.size != args.size` we know that this is a partial application and set the values of the remaining parameters to `top` since it is impossible to track what will happen with them from here on. -/ def updateFunDeclParamsAssignment (params : Array Param) (args : Array Arg) : InterpM Bool := do let mut ret := false for param in params, arg in args do let paramVal ← findVarValue param.fvarId let argVal ← findArgValue arg let newVal := .merge paramVal argVal if newVal != paramVal then modifyAssignment (·.insert param.fvarId newVal) ret := true /- This is a partial application, we can not know for sure what remaining arguments the local function is getting passed without a much more sophisticated analysis. Hence we will set all of the non applied ones to top. -/ if params.size != args.size then for param in params[args.size:] do ret := (← findVarValue param.fvarId) == .bot updateVarAssignment param.fvarId .top return ret private partial def resetNestedFunDeclParams : Code → InterpM Unit | .let _ k => resetNestedFunDeclParams k | .jp decl k | .fun decl k => do decl.params.forM (resetVarAssignment ·.fvarId) /- We don't need to reset the parameters of decls nested in this one since they will be reset if this decl is used. -/ resetNestedFunDeclParams k | .cases cs => cs.alts.forM (resetNestedFunDeclParams ·.getCode) | .return .. | .unreach .. | .jmp .. => return () /-- The actual abstract interpreter on a block of `Code`. -/ partial def interpCode : Code → InterpM Unit | .let decl k => do let val ← interpLetValue decl.value updateVarAssignment decl.fvarId val if let .fvar fvarId args := decl.value then if let some funDecl ← findFunDecl? fvarId then -- TODO: unclear how much we should reset in the case of partial applications interpFunCall funDecl args interpCode k | .jp decl k | .fun decl k => do interpCode decl.value interpCode k | .jmp fn args => do let jp ← getFunDecl fn args.forM handleFunArg interpFunCall jp args | .cases cs => do let discrVal ← findVarValue cs.discr for alt in cs.alts do match alt with | .alt ctor params body => if let some argValues := discrVal.getCtorArgs ctor then params.zip argValues |>.forM (fun (param, val) => updateVarAssignment param.fvarId val) else params.forM (updateVarAssignment ·.fvarId .top) interpCode body | .default body => interpCode body | .return var => do handleFunVar var let val ← findVarValue var updateCurrFnSummary val | .unreach .. => return () where /-- The abstract interpreter on a `LetValue`. -/ interpLetValue (letVal : LetValue) : InterpM Value := do match letVal with | .value val => return .ofLCNFLit val | .proj _ idx struct => return (← findVarValue struct).proj idx | .const declName _ args => let env ← getEnv args.forM handleFunArg match (← getDecl? declName) with | some decl => if decl.getArity == args.size then match getFunctionSummary? env declName with | some v => return v | none => return (← findFunVal? declName).getD .top else return .top | none => let some (.ctorInfo info) := env.find? declName | return .top let args := args[info.numParams:].toArray if info.numFields == args.size then return .ctor declName (← args.mapM findArgValue) else return .top | .fvar _ args => args.forM handleFunArg /- Since free variables in `LetValue`s cannot be of the form `let x := y` after a simplifier pass we know they are in fact a partially applied function, we cannot know anything about the result of a partially applied function. -/ return .top | .erased => return .top handleFunArg (arg : Arg) : InterpM Unit := do if let .fvar fvarId := arg then handleFunVar fvarId /-- If we see a function being passed as an argument to a higher order function we cannot know what arguments it will be passed further down the line. Hence we set all of its arguments to `top` since anything is possible. -/ handleFunVar (var : FVarId) : InterpM Unit := do if let some funDecl ← findFunDecl? var then funDecl.params.forM (updateVarAssignment ·.fvarId .top) interpFunCall funDecl #[] interpFunCall (funDecl : FunDecl) (args : Array Arg) : InterpM Unit := do let updated ← updateFunDeclParamsAssignment funDecl.params args if updated then /- We must reset the value of nested function declaration parameters since they depend on `args` values. -/ resetNestedFunDeclParams funDecl.value interpCode funDecl.value /-- Rerun the abstract interpreter on all declarations except of the unsafe ones. Return whether any `Value` got updated in the process. -/ def inferStep : InterpM Bool := do let ctx ← read for idx in [0:ctx.decls.size] do let decl := ctx.decls[idx]! if !decl.safe then continue let currentVal ← getFunVal idx withReader (fun ctx => { ctx with currFnIdx := idx }) do decl.params.forM fun p => updateVarAssignment p.fvarId .top interpCode decl.value let newVal ← getFunVal idx if currentVal != newVal then return true return false /-- Run `inferStep` until it reaches a fix point. -/ partial def inferMain : InterpM Unit := do let ctx ← read modify fun s => { s with assignments := ctx.decls.map fun _ => {} } let modified ← inferStep if modified then inferMain else return () /-- Use the information produced by the abstract interpeter to: - Eliminate branches that we know cannot be hit - Eliminate values that we know have to be constants. -/ partial def elimDead (assignment : Assignment) (decl : Decl) : CompilerM Decl := do trace[Compiler.elimDeadBranches] s!"Eliminating {decl.name} with {repr (← assignment.toArray |>.mapM (fun (name, val) => do return (toString (← getBinderName name), val)))}" return { decl with value := (← go decl.value) } where go (code : Code) : CompilerM Code := do match code with | .let decl k => return code.updateLet! decl (← go k) | .jp decl k | .fun decl k => return code.updateFun! (← decl.updateValue (← go decl.value)) (← go k) | .cases cs => let discrVal := assignment.findD cs.discr .bot let processAlt typ alt := do match alt with | .alt ctor args body => if discrVal.containsCtor ctor then let filter param := do if let some val := assignment.find? param.fvarId then if let some literal ← val.getLiteral then return some (param, literal) return none let constantInfos ← args.filterMapM filter if constantInfos.size != 0 then let folder := fun (body, subst) (param, decls, var) => do return (attachCodeDecls decls body, subst.insert param.fvarId (.fvar var)) let (body, subst) ← constantInfos.foldlM (init := (← go body, {})) folder let body ← replaceFVars body subst false return alt.updateCode body else return alt.updateCode (← go body) else trace[Compiler.elimDeadBranches] s!"Threw away cases {← getBinderName cs.discr} branch {ctor}" eraseCode alt.getCode return alt.updateCode <| .unreach typ | .default body => return alt.updateCode (← go body) return code.updateCases! cs.resultType cs.discr (← cs.alts.mapM <| processAlt cs.resultType) | .jmp .. | .return .. | .unreach .. => return code end UnreachableBranches open UnreachableBranches in def Decl.elimDeadBranches (decls : Array Decl) : CompilerM (Array Decl) := do let mut assignments := decls.map fun _ => {} let initialVal i := /- Non terminating functions are marked as unsafe, we don't want to run any analysis on them since we cannot be sure they will ever return the constructor that we inferred for them. For more information refer to the docstring of `Decl.safe`. -/ if decls[i]!.safe then .bot else .top let mut funVals := decls.size.fold (init := .empty) fun i p => p.push (initialVal i) let ctx := { decls } let mut state := { assignments, funVals } (_, state) ← inferMain |>.run ctx |>.run state funVals := state.funVals assignments := state.assignments modifyEnv fun e => decls.size.fold (init := e) fun i env => addFunctionSummary env decls[i]!.name funVals[i]! decls.mapIdxM fun i decl => if decl.safe then elimDead assignments[i]! decl else return decl def elimDeadBranches : Pass := { name := `elimDeadBranches, run := Decl.elimDeadBranches, phase := .mono } builtin_initialize registerTraceClass `Compiler.elimDeadBranches (inherited := true) end Lean.Compiler.LCNF
2692a09ba892285d75cfa947be13c8f5e07b8f81
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/data/bitvec.lean
17d04aad8a3db5c17fa4ad4181e6c76c02ad3791
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,136
lean
/- Copyright (c) 2015 Joe Hendrix. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joe Hendrix, Sebastian Ullrich Basic operations on bitvectors. This is a work-in-progress, and contains additions to other theories. -/ import data.vector @[reducible] def bitvec (n : ℕ) := vector bool n namespace bitvec open nat open vector local infix `++ₜ`:65 := vector.append -- Create a zero bitvector @[reducible] protected def zero (n : ℕ) : bitvec n := repeat ff n -- Create a bitvector with the constant one. @[reducible] protected def one : Π (n : ℕ), bitvec n | 0 := [] | (succ n) := repeat ff n ++ₜ [tt] protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b | ⟨x, p⟩ := ⟨x, h ▸ p⟩ -- bitvec specific version of vector.append def append {m n} : bitvec m → bitvec n → bitvec (m + n) := vector.append section shift variable {n : ℕ} def shl (x : bitvec n) (i : ℕ) : bitvec n := bitvec.cong (by simp) $ dropn i x ++ₜ repeat ff (min n i) local attribute [ematch] nat.add_sub_assoc sub_le le_of_not_ge sub_eq_zero_of_le def fill_shr (x : bitvec n) (i : ℕ) (fill : bool) : bitvec n := bitvec.cong (by async { begin [smt] by_cases (i ≤ n), eblast end }) $ repeat fill (min n i) ++ₜ taken (n-i) x -- unsigned shift right def ushr (x : bitvec n) (i : ℕ) : bitvec n := fill_shr x i ff -- signed shift right def sshr : Π {m : ℕ}, bitvec m → ℕ → bitvec m | 0 _ _ := [] | (succ m) x i := head x :: fill_shr (tail x) i (head x) end shift section bitwise variable {n : ℕ} def not : bitvec n → bitvec n := map bnot def and : bitvec n → bitvec n → bitvec n := map₂ band def or : bitvec n → bitvec n → bitvec n := map₂ bor def xor : bitvec n → bitvec n → bitvec n := map₂ bxor end bitwise section arith variable {n : ℕ} protected def xor3 (x y c : bool) := bxor (bxor x y) c protected def carry (x y c : bool) := x && y || x && c || y && c protected def neg (x : bitvec n) : bitvec n := let f := λ y c, (y || c, bxor y c) in prod.snd (map_accumr f x ff) -- Add with carry (no overflow) def adc (x y : bitvec n) (c : bool) : bitvec (n+1) := let f := λ x y c, (bitvec.carry x y c, bitvec.xor3 x y c) in let ⟨c, z⟩ := vector.map_accumr₂ f x y c in c :: z protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff) protected def borrow (x y b : bool) := bnot x && y || bnot x && b || y && b -- Subtract with borrow def sbb (x y : bitvec n) (b : bool) : bool × bitvec n := let f := λ x y c, (bitvec.borrow x y c, bitvec.xor3 x y c) in vector.map_accumr₂ f x y b protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff) instance : has_zero (bitvec n) := ⟨bitvec.zero n⟩ instance : has_one (bitvec n) := ⟨bitvec.one n⟩ instance : has_add (bitvec n) := ⟨bitvec.add⟩ instance : has_sub (bitvec n) := ⟨bitvec.sub⟩ instance : has_neg (bitvec n) := ⟨bitvec.neg⟩ protected def mul (x y : bitvec n) : bitvec n := let f := λ r b, cond b (r + r + y) (r + r) in list.foldl f 0 (to_list x) instance : has_mul (bitvec n) := ⟨bitvec.mul⟩ end arith section comparison variable {n : ℕ} def uborrow (x y : bitvec n) : bool := prod.fst (sbb x y ff) def ult (x y : bitvec n) : Prop := uborrow x y def ugt (x y : bitvec n) : Prop := ult y x def ule (x y : bitvec n) : Prop := ¬ (ult y x) def uge (x y : bitvec n) : Prop := ule y x def sborrow : Π {n : ℕ}, bitvec n → bitvec n → bool | 0 _ _ := ff | (succ n) x y := match (head x, head y) with | (tt, ff) := tt | (ff, tt) := ff | _ := uborrow (tail x) (tail y) end def slt (x y : bitvec n) : Prop := sborrow x y def sgt (x y : bitvec n) : Prop := slt y x def sle (x y : bitvec n) : Prop := ¬ (slt y x) def sge (x y : bitvec n) : Prop := sle y x end comparison section conversion variable {α : Type} protected def of_nat : Π (n : ℕ), nat → bitvec n | 0 x := nil | (succ n) x := of_nat n (x / 2) ++ₜ [to_bool (x % 2 = 1)] protected def of_int : Π (n : ℕ), int → bitvec (succ n) | n (int.of_nat m) := ff :: bitvec.of_nat n m | n (int.neg_succ_of_nat m) := tt :: not (bitvec.of_nat n m) def bits_to_nat (v : list bool) : nat := list.foldl (λ r b, r + r + cond b 1 0) 0 v protected def to_nat {n : nat} (v : bitvec n) : nat := bits_to_nat (to_list v) protected def to_int : Π {n : nat}, bitvec n → int | 0 _ := 0 | (succ n) v := cond (head v) (int.neg_succ_of_nat $ bitvec.to_nat $ not $ tail v) (int.of_nat $ bitvec.to_nat $ tail v) end conversion private def to_string {n : nat} : bitvec n → string | ⟨bs, p⟩ := "0b" ++ (bs^.reverse^.for (λ b, if b then #"1" else #"0")) instance (n : nat) : has_to_string (bitvec n) := ⟨to_string⟩ end bitvec instance {n} {x y : bitvec n} : decidable (bitvec.ult x y) := bool.decidable_eq _ _ instance {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := bool.decidable_eq _ _
688da35c587f976409d058409d0f0045533bb675
b04370a335fa89c708a3d43678d79c1f61aa24c7
/library/init/meta/tactic.lean
072e197c337b75b8b6faa05ed17ce26e2ee20b6a
[ "Apache-2.0" ]
permissive
jalex-stark/lean
9b97cd8b0eb970ab0d4cdbc7b4dd57645f33a92c
85ba44431d77c8222342c7616f0bfa98fba88368
refs/heads/master
1,664,328,815,754
1,590,514,885,000
1,590,514,885,000
267,196,280
0
0
null
1,590,544,752,000
1,590,544,752,000
null
UTF-8
Lean
false
false
70,942
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad open native meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic open interaction_monad.result variables {α : Type u} /-- Does nothing. -/ meta def skip : tactic unit := success () /-- `try_core t` acts like `t`, but succeeds even if `t` fails. It returns the result of `t` if `t` succeeded and `none` otherwise. -/ meta def try_core (t : tactic α) : tactic (option α) := λ s, match t s with | (exception _ _ _) := success none s | (success a s') := success (some a) s' end /-- `try t` acts like `t`, but succeeds even if `t` fails. -/ meta def try (t : tactic α) : tactic unit := λ s, match t s with | (exception _ _ _) := success () s | (success _ s') := success () s' end meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | success _ s' := try (try_lst tacs) s' | exception e p s' := match try_lst tacs s' with | exception _ _ _ := exception e p s' | r := r end end /-- `fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, match (t s) with | (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end /-- `success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t` succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t` succeeds. -/ meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s | (exception _ _ _) := success () s end open nat /-- `iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the result of each successful iteration. -/ meta def iterate_at_most : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do (some a) ← try_core t | pure [], as ← iterate_at_most n t, pure $ a :: as /-- `iterate_at_most' n t` repeats `t` `n` times or until `t` fails. -/ meta def iterate_at_most' : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do (some _) ← try_core t | skip, iterate_at_most' n t /-- `iterate_exactly n t` iterates `t` `n` times, returning the result of each iteration. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly : nat → tactic α → tactic (list α) | 0 t := pure [] | (n + 1) t := do a ← t, as ← iterate_exactly n t, pure $ a ::as /-- `iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole tactic fails. -/ meta def iterate_exactly' : nat → tactic unit → tactic unit | 0 t := skip | (n + 1) t := t *> iterate_exactly' n t /-- `iterate t` repeats `t` 100.000 times or until `t` fails, returning the result of each iteration. -/ meta def iterate : tactic α → tactic (list α) := iterate_at_most 100000 /-- `iterate' t` repeats `t` 100.000 times or until `t` fails. -/ meta def iterate' : tactic unit → tactic unit := iterate_at_most' 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority and whether or not the attribute is persistent. -/ meta constant has_attribute : name → name → tactic (bool × nat) /-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`; if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/ meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit := try $ do (p', prio) ← has_attribute attr_name src, let p := p.get_or_else p', set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /-- Freeze the current set of local instances. -/ meta constant freeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- `intron' n` introduces `n` hypotheses and returns the resulting local constants. Fails if there are not at least `n` arguments to introduce. If you do not need the return value, use `intron`. -/ meta def intron' : ℕ → tactic (list expr) | 0 := pure [] | (n + 1) := do h ← intro1, hs ← intron' n, pure $ h :: hs /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 {α} (tac : tactic α) : tactic α := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], a ← tac, gs' ← get_goals, match gs' with | [] := set_goals rs >> pure a | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve {α} (ts : list (tactic α)) : tactic α := first $ map solve1 ts private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α) | [] [] rs := set_goals rs *> pure [] | (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics", a ← t, rs' ← get_goals, as ← focus_aux ts gs (rs ++ rs'), pure $ a :: as /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. Returns the results of t_i (one per goal). -/ meta def focus {α} (ts : list (tactic α)) : tactic (list α) := do gs ← get_goals, focus_aux ts gs [] private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus'_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus'_aux ts gs (rs ++ rs') /-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus' (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus'_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core {α} (tac : tactic α) : list expr → list expr → tactic (list α) | [] ac := set_goals ac *> pure [] | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], a ← tac, new_gs ← get_goals, as ← all_goals_core gs (ac ++ new_gs), pure $ a :: as /-- Apply the given tactic to all goals. Return one result per goal. -/ meta def all_goals {α} (tac : tactic α) : tactic (list α) := do gs ← get_goals, all_goals_core tac gs [] private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals'_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals'_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals'_core tac gs [] private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α)) | [] ac progress := guard progress *> set_goals ac *> pure [] | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], res ← try_core tac, new_gs ← get_goals, ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress), pure $ res :: ress /-- Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac` succeeds for at least one goal. The returned list contains the result of `tac` for each goal: `some a` if tac succeeded, or `none` if it did not. -/ meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) := do gs ← get_goals, any_goals_core tac gs [] ff private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals'_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals' (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals'_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies `tac2` to each goal produced by `tac1`. -/ meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← all_goals $ tac2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals' tac2, gs' ← get_goals, set_goals (gs' ++ gs) /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus'`). -/ meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) := do g::gs ← get_goals, set_goals [g], a ← tac1, bs ← focus $ tacs2 a, gs' ← get_goals, set_goals (gs' ++ gs), pure bs /-- Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to one of the produced subgoals (like `focus`). -/ meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq'⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus'⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute [instance] classical.prop_decidable' is used, all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal and the newly introduced hypotheses. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ ⟨n, hs, _⟩, ⟨n, hs⟩) else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 $ do r ← cases_core h ids md, hs' ← all_goals (intron' n), return $ r.map₂ (λ ⟨n, hs, _⟩ hs', ⟨n, hs ++ hs'⟩) hs' /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq' (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- add declaration `d` as a protected declaration -/ meta def add_protected_decl (d : declaration) : tactic unit := updateex_env $ λ e, e.add_protected d /-- check if `n` is the name of a protected declaration -/ meta def is_protected_decl (n : name) : tactic bool := do env ← get_env, return $ env.is_protected n /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. If `use_unique_names` is true, the keys of `name_map` should be the unique names of hypotheses to be renamed. Otherwise, the keys should be display names. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. If `use_unique_names` is false and there are multiple hypotheses with the same display name in the context, they are all renamed. -/ meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff) : tactic unit := do let hyp_name : expr → name := if use_unique_names then expr.local_uniq_name else expr.local_pp_name, ctx ← revertible_local_context, -- The part of the context after (but including) the first hypthesis that -- must be renamed. let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none), when strict $ do { let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.join $ (invalid_renames.map to_fmt).intersperse ", " , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ] }, -- The new names for all hypotheses in ctx_suffix. let new_names := ctx_suffix.map $ λ h, (renames.find $ hyp_name h).get_or_else h.local_pp_name, revert_lst ctx_suffix, intro_lst new_names, pure () /-- Rename a local hypothesis. This is a special case of `rename_many`; see there for caveats. -/ meta def rename (curr : name) (new : name) : tactic unit := rename_many (rb_map.of_list [⟨curr, new⟩]) /-- Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does not preserve the order of hypotheses. Its implementation is simpler (and therefore probably faster) than that of `rename`. -/ meta def rename_unstable (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
e0cb3c262f18b1fe7b18553e412a384fe7e6f0b1
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_347.lean
fa54eec3ed1c8de499e9181df21fed84e90ad73d
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
251
lean
import tactic open set variable {α : Type*} variables (s t u : set α) -- BEGIN example : s ∩ t = t ∩ s := begin apply subset.antisymm, { rintros x ⟨xs, xt⟩, exact ⟨xt, xs⟩ }, rintros x ⟨xt, xs⟩, exact ⟨xs, xt⟩ end -- END
16afbec1a85f98a0e62f0f42697574b7b9153a38
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/algebra/multilinear.lean
b045a4cbcd6484d5b125cc2ccfbc576dc702d9cb
[ "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
16,178
lean
/- Copyright (c) 2020 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.algebra.module import linear_algebra.multilinear /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set open_locale big_operators universes u v w w₁ w₁' w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section semiring variables [semiring R] [Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, semimodule R (M i)] [Π i, semimodule R (M₁ i)] [Π i, semimodule R (M₁' i)] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] [Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) := ⟨_, λ f, f.to_multilinear_map.to_fun⟩ @[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont @[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl theorem to_multilinear_map_inj : function.injective (continuous_multilinear_map.to_multilinear_map : continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂) | ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := to_multilinear_map_inj $ multilinear_map.ext H @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl section has_continuous_add variable [has_continuous_add M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl @[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) : (f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map := rfl instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl) /-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/ def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ := ⟨λ f, f m, rfl, λ _ _, rfl⟩ @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m := (apply_add_hom m).map_sum f s end has_continuous_add /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp (continuous_const.update i continuous_id), .. f.to_multilinear_map.to_linear_map m i } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a continuous multilinear map taking values in the space of functions `Π i, M' i`. -/ def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_group (M' i)] [Π i, topological_space (M' i)] [Π i, semimodule R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : continuous_multilinear_map R M₁ (Π i, M' i) := { cont := continuous_pi $ λ i, (f i).coe_continuous, to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) } @[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_group (M' i)] [Π i, topological_space (M' i)] [Π i, semimodule R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : ⇑(pi f) = λ m j, f j m := rfl lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_group (M' i)] [Π i, topological_space (M' i)] [Π i, semimodule R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') : pi f m j = f j m := rfl /-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) : continuous_multilinear_map R M₁ M₄ := { cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) } @[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) : g.comp_continuous_linear_map f m = g (λ i, f i $ m i) := rfl /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum _ end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), semimodule A (M₁ i)] [semimodule A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved semimodules agree with the action of `R` on `A`. -/ def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : continuous_multilinear_map R M₁ M₂ := { to_multilinear_map := f.to_multilinear_map.restrict_scalars R, cont := f.cont } @[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar end semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f f' : continuous_multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ section topological_add_group variable [topological_add_group M₂] instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (continuous_multilinear_map R M₁ M₂) := ⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) end topological_add_group end ring section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = (∏ i, c i) • f m := f.to_multilinear_map.map_smul_univ _ _ variables {R' A : Type*} [comm_semiring R'] [semiring A] [algebra R' A] [Π i, semimodule A (M₁ i)] [semimodule R' M₂] [semimodule A M₂] [is_scalar_tower R' A M₂] [topological_space R'] [has_continuous_smul R' M₂] instance : has_scalar R' (continuous_multilinear_map A M₁ M₂) := ⟨λ c f, { cont := continuous_const.smul f.cont, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl @[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) : (c • f).to_multilinear_map = c • f.to_multilinear_map := rfl instance {R''} [comm_semiring R''] [has_scalar R' R''] [algebra R'' A] [semimodule R'' M₂] [is_scalar_tower R'' A M₂] [is_scalar_tower R' R'' M₂] [topological_space R''] [has_continuous_smul R'' M₂]: is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩ variable [has_continuous_add M₂] /-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : semimodule R' (continuous_multilinear_map A M₁ M₂) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _, add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ @[simps] def to_multilinear_map_linear : (continuous_multilinear_map A M₁ M₂) →ₗ[R'] (multilinear_map A M₁ M₂) := { to_fun := λ f, f.to_multilinear_map, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end comm_semiring end continuous_multilinear_map namespace continuous_linear_map variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃] /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } end continuous_linear_map
a039ea54a1a80d7f0a3b44cbc39abd935609401d
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/dense_embedding.lean
acd08bbc565d4e196b471937acb2900aa12b7ba1
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,328
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.separation import topology.bases /-! # Dense embeddings This file defines three properties of functions: * `dense_range f` means `f` has dense image; * `dense_inducing i` means `i` is also `inducing`; * `dense_embedding e` means `e` is also an `embedding`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a regular (T₃) space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `dense_inducing` (not necessarily injective). -/ noncomputable theory open set filter open_locale classical topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ @[protect_proj] structure dense_inducing [topological_space α] [topological_space β] (i : α → β) extends inducing i : Prop := (dense : dense_range i) namespace dense_inducing variables [topological_space α] [topological_space β] variables {i : α → β} (di : dense_inducing i) lemma nhds_eq_comap (di : dense_inducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 $ i a) := di.to_inducing.nhds_eq_comap protected lemma continuous (di : dense_inducing i) : continuous i := di.to_inducing.continuous lemma closure_range : closure (range i) = univ := di.dense.closure_range protected lemma preconnected_space [preconnected_space α] (di : dense_inducing i) : preconnected_space β := di.dense.preconnected_space di.continuous lemma closure_image_mem_nhds {s : set α} {a : α} (di : dense_inducing i) (hs : s ∈ 𝓝 a) : closure (i '' s) ∈ 𝓝 (i a) := begin rw [di.nhds_eq_comap a, ((nhds_basis_opens _).comap _).mem_iff] at hs, rcases hs with ⟨U, ⟨haU, hUo⟩, sub : i ⁻¹' U ⊆ s⟩, refine mem_of_superset (hUo.mem_nhds haU) _, calc U ⊆ closure (i '' (i ⁻¹' U)) : di.dense.subset_closure_image_preimage_of_is_open hUo ... ⊆ closure (i '' s) : closure_mono (image_subset i sub) end lemma dense_image (di : dense_inducing i) {s : set α} : dense (i '' s) ↔ dense s := begin refine ⟨λ H x, _, di.dense.dense_image di.continuous⟩, rw [di.to_inducing.closure_eq_preimage_closure_image, H.closure_eq, preimage_univ], trivial end /-- If `i : α → β` is a dense embedding with dense complement of the range, then any compact set in `α` has empty interior. -/ lemma interior_compact_eq_empty [t2_space β] (di : dense_inducing i) (hd : dense (range i)ᶜ) {s : set α} (hs : is_compact s) : interior s = ∅ := begin refine eq_empty_iff_forall_not_mem.2 (λ x hx, _), rw [mem_interior_iff_mem_nhds] at hx, have := di.closure_image_mem_nhds hx, rw (hs.image di.continuous).is_closed.closure_eq at this, rcases hd.inter_nhds_nonempty this with ⟨y, hyi, hys⟩, exact hyi (image_subset_range _ _ hys) end /-- The product of two dense inducings is a dense inducing -/ protected lemma prod [topological_space γ] [topological_space δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := de₁.dense.prod_map de₂.dense } open topological_space /-- If the domain of a `dense_inducing` map is a separable space, then so is the codomain. -/ protected lemma separable_space [separable_space α] : separable_space β := di.dense.separable_space di.continuous variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- ``` γ -f→ α g↓ ↓e δ -h→ β ``` -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) := begin have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le, replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H, rw ← di.nhds_eq_comap at lim2, exact le_trans lim1 lim2, end protected lemma nhds_within_ne_bot (di : dense_inducing i) (b : β) : ne_bot (𝓝[range i] b) := di.dense.nhds_within_ne_bot b lemma comap_nhds_ne_bot (di : dense_inducing i) (b : β) : ne_bot (comap i (𝓝 b)) := comap_ne_bot $ λ s hs, let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩ variables [topological_space γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ := @@lim _ ⟨f (di.dense.some b)⟩ (comap i (𝓝 b)) f lemma extend_eq_of_tendsto [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : tendsto f (comap i (𝓝 b)) (𝓝 c)) : di.extend f b = c := by haveI := di.comap_nhds_ne_bot; exact hf.lim_eq lemma extend_eq_at [t2_space γ] {f : α → γ} {a : α} (hf : continuous_at f a) : di.extend f (i a) = f a := extend_eq_of_tendsto _ $ di.nhds_eq_comap a ▸ hf lemma extend_eq_at' [t2_space γ] {f : α → γ} {a : α} (c : γ) (hf : tendsto f (𝓝 a) (𝓝 c)) : di.extend f (i a) = f a := di.extend_eq_at (continuous_at_of_tendsto_nhds hf) lemma extend_eq [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) : di.extend f (i a) = f a := di.extend_eq_at hf.continuous_at /-- Variation of `extend_eq` where we ask that `f` has a limit along `comap i (𝓝 b)` for each `b : β`. This is a strictly stronger assumption than continuity of `f`, but in a lot of cases you'd have to prove it anyway to use `continuous_extend`, so this avoids doing the work twice. -/ lemma extend_eq' [t2_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀ b, ∃ c, tendsto f (comap i (𝓝 b)) (𝓝 c)) (a : α) : di.extend f (i a) = f a := begin rcases hf (i a) with ⟨b, hb⟩, refine di.extend_eq_at' b _, rwa ← di.to_inducing.nhds_eq_comap at hb, end lemma extend_unique_at [t2_space γ] {b : β} {f : α → γ} {g : β → γ} (di : dense_inducing i) (hf : ∀ᶠ x in comap i (𝓝 b), g (i x) = f x) (hg : continuous_at g b) : di.extend f b = g b := begin refine di.extend_eq_of_tendsto (λ s hs, mem_map.2 _), suffices : ∀ᶠ (x : α) in comap i (𝓝 b), g (i x) ∈ s, from hf.mp (this.mono $ λ x hgx hfx, hfx ▸ hgx), clear hf f, refine eventually_comap.2 ((hg.eventually hs).mono _), rintros _ hxs x rfl, exact hxs end lemma extend_unique [t2_space γ] {f : α → γ} {g : β → γ} (di : dense_inducing i) (hf : ∀ x, g (i x) = f x) (hg : continuous g) : di.extend f = g := funext $ λ b, extend_unique_at di (eventually_of_forall hf) hg.continuous_at lemma continuous_at_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i) (hf : ∀ᶠ x in 𝓝 b, ∃c, tendsto f (comap i $ 𝓝 x) (𝓝 c)) : continuous_at (di.extend f) b := begin set φ := di.extend f, haveI := di.comap_nhds_ne_bot, suffices : ∀ V' ∈ 𝓝 (φ b), is_closed V' → φ ⁻¹' V' ∈ 𝓝 b, by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff], intros V' V'_in V'_closed, set V₁ := {x | tendsto f (comap i $ 𝓝 x) (𝓝 $ φ x)}, have V₁_in : V₁ ∈ 𝓝 b, { filter_upwards [hf], rintros x ⟨c, hc⟩, dsimp [V₁, φ], rwa di.extend_eq_of_tendsto hc }, obtain ⟨V₂, V₂_in, V₂_op, hV₂⟩ : ∃ V₂ ∈ 𝓝 b, is_open V₂ ∧ ∀ x ∈ i ⁻¹' V₂, f x ∈ V', { simpa [and_assoc] using ((nhds_basis_opens' b).comap i).tendsto_left_iff.mp (mem_of_mem_nhds V₁_in : b ∈ V₁) V' V'_in }, suffices : ∀ x ∈ V₁ ∩ V₂, φ x ∈ V', { filter_upwards [inter_mem V₁_in V₂_in] using this, }, rintros x ⟨x_in₁, x_in₂⟩, have hV₂x : V₂ ∈ 𝓝 x := is_open.mem_nhds V₂_op x_in₂, apply V'_closed.mem_of_tendsto x_in₁, use V₂, tauto, end lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) := continuous_iff_continuous_at.mpr $ assume b, di.continuous_at_extend $ univ_mem' hf lemma mk' (i : α → β) (c : continuous i) (dense : ∀x, x ∈ closure (range i)) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : dense_inducing i := { induced := (induced_iff_nhds_eq i).2 $ λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [filter.le_def] using H a), dense := dense } end dense_inducing /-- A dense embedding is an embedding with dense image. -/ structure dense_embedding [topological_space α] [topological_space β] (e : α → β) extends dense_inducing e : Prop := (inj : function.injective e) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : dense_range e) (inj : function.injective e) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := { inj := inj, ..dense_inducing.mk' e c dense H} namespace dense_embedding open topological_space variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {e : α → β} (de : dense_embedding e) lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma to_embedding : embedding e := { induced := de.induced, inj := de.inj } /-- If the domain of a `dense_embedding` is a separable space, then so is its codomain. -/ protected lemma separable_space [separable_space α] : separable_space β := de.to_dense_inducing.separable_space /-- The product of two dense embeddings is a dense embedding. -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } /-- The dense embedding of a subtype inside its closure. -/ @[simps] def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x, subset_closure $ mem_image_of_mem e x.prop⟩ protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) := { dense := dense_iff_closure_eq.2 $ begin ext ⟨x, hx⟩, rw image_eq_range at hx, simpa [closure_subtype, ← range_comp, (∘)], end, inj := (de.inj.comp subtype.coe_injective).cod_restrict _, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap, (∘)]) } lemma dense_image {s : set α} : dense (e '' s) ↔ dense s := de.to_dense_inducing.dense_image end dense_embedding lemma dense.dense_embedding_coe [topological_space α] {s : set α} (hs : dense s) : dense_embedding (coe : s → α) := { dense := hs.dense_range_coe, .. embedding_subtype_coe } lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.closure_range.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : hp.closure_eq, assume b, this trivial lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod_map he) hp $ λ _, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod_map $ he.prod_map he) hp $ λ _, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ @[elab_as_eliminator] lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop} (b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ := is_closed_property he hp ih b₀ @[elab_as_eliminator] lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _ @[elab_as_eliminator] lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _ section variables [topological_space β] [topological_space γ] [t2_space γ] variables {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ lemma dense_range.equalizer (hfd : dense_range f) {g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end -- Bourbaki GT III §3 no.4 Proposition 7 (generalised to any dense-inducing map to a regular space) lemma filter.has_basis.has_basis_of_dense_inducing [topological_space α] [topological_space β] [regular_space β] {ι : Type*} {s : ι → set α} {p : ι → Prop} {x : α} (h : (𝓝 x).has_basis p s) {f : α → β} (hf : dense_inducing f) : (𝓝 (f x)).has_basis p $ λ i, closure $ f '' (s i) := begin rw filter.has_basis_iff at h ⊢, intros T, refine ⟨λ hT, _, λ hT, _⟩, { obtain ⟨T', hT₁, hT₂, hT₃⟩ := nhds_is_closed hT, have hT₄ : f⁻¹' T' ∈ 𝓝 x, { rw hf.to_inducing.nhds_eq_comap x, exact ⟨T', hT₁, subset.rfl⟩, }, obtain ⟨i, hi, hi'⟩ := (h _).mp hT₄, exact ⟨i, hi, (closure_mono (image_subset f hi')).trans (subset.trans (closure_minimal (image_subset_iff.mpr subset.rfl) hT₃) hT₂)⟩, }, { obtain ⟨i, hi, hi'⟩ := hT, suffices : closure (f '' s i) ∈ 𝓝 (f x), { filter_upwards [this] using hi', }, replace h := (h (s i)).mpr ⟨i, hi, subset.rfl⟩, exact hf.closure_image_mem_nhds h, }, end
d14e99a9bdb82e6178b454f73195f6a811c910df
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/at_at_bug.lean
4ef55d5bc6754c90c6b35a29eb69bcd48b59b5b0
[ "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
391
lean
example (a b : nat) (p : nat → nat → Prop) (h₁ : p a b) (h₂ : a = b) : p b b := @@eq.subst (λ x, p x b) h₂ h₁ set_option pp.all true variable my_has_add : has_add nat #check @@has_add.add my_has_add 0 1 local notation h1 `▸[` m `]` h2 := @@eq.subst m h1 h2 example (a b : nat) (p : nat → nat → Prop) (h₁ : p a b) (h₂ : a = b) : p b b := h₂ ▸[λ x, p x b] h₁
cc800b86e572320df850ed7ee28d1af122ce87df
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/enorm.lean
d65e3e326273b50a056d007b782b7a380be5189f
[ "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,828
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed_space.basic /-! # Extended norm In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for an `enorm` because the same space can have more than one extended norm. For example, the space of measurable functions `f : α → ℝ` has a family of `L_p` extended norms. We prove some basic inequalities, then define * `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`; * the subspace of vectors with finite norm, called `e.finite_subspace`; * a `normed_space` structure on this space. The last definition is an instance because the type involves `e`. ## Implementation notes We do not define extended normed groups. They can be added to the chain once someone will need them. ## Tags normed space, extended norm -/ noncomputable theory local attribute [instance, priority 1001] classical.prop_decidable open_locale ennreal /-- Extended norm on a vector space. As in the case of normed spaces, we require only `∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/ structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] := (to_fun : V → ℝ≥0∞) (eq_zero' : ∀ x, to_fun x = 0 → x = 0) (map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y) (map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ nnnorm c * to_fun x) namespace enorm variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] (e : enorm 𝕜 V) instance : has_coe_to_fun (enorm 𝕜 V) (λ _, V → ℝ≥0∞) := ⟨enorm.to_fun⟩ lemma coe_fn_injective : function.injective (coe_fn : enorm 𝕜 V → (V → ℝ≥0∞)) := λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h @[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ := coe_fn_injective $ funext h lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : (e₁ : V → ℝ≥0∞) = e₂ ↔ e₁ = e₂ := coe_fn_injective.eq_iff @[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = nnnorm c * e x := le_antisymm (e.map_smul_le' c x) $ begin by_cases hc : c = 0, { simp [hc] }, calc (nnnorm c : ℝ≥0∞) * e x = nnnorm c * e (c⁻¹ • c • x) : by rw [inv_smul_smul₀ hc] ... ≤ nnnorm c * (nnnorm (c⁻¹) * e (c • x)) : _ ... = e (c • x) : _, { exact ennreal.mul_le_mul (le_refl _) (e.map_smul_le' _ _) }, { rw [← mul_assoc, normed_field.nnnorm_inv, ennreal.coe_inv, ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] } end @[simp] lemma map_zero : e 0 = 0 := by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num } @[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 := ⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩ @[simp] lemma map_neg (x : V) : e (-x) = e x := calc e (-x) = nnnorm (-1:𝕜) * e x : by rw [← map_smul, neg_one_smul] ... = e x : by simp lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) := by rw [← neg_sub, e.map_neg] lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y := calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg ... ≤ e x + e (-y) : e.map_add_le x (-y) ... = e x + e y : by rw [e.map_neg] instance : partial_order (enorm 𝕜 V) := { le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x, le_refl := λ e x, le_refl _, le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) } /-- The `enorm` sending each non-zero vector to infinity. -/ noncomputable instance : has_top (enorm 𝕜 V) := ⟨{ to_fun := λ x, if x = 0 then 0 else ⊤, eq_zero' := λ x, by { split_ifs; simp [*] }, map_add_le' := λ x y, begin split_ifs with hxy hx hy hy hx hy hy; try { simp [*] }, simpa [hx, hy] using hxy end, map_smul_le' := λ c x, begin split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx, { simp only [mul_zero, le_refl] }, { have : c = 0, by tauto, simp [this] }, { tauto }, { simp [hcx.1] } end }⟩ noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩ lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx noncomputable instance : order_top (enorm 𝕜 V) := { top := ⊤, le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h] } noncomputable instance : semilattice_sup_top (enorm 𝕜 V) := { le := (≤), lt := (<), sup := λ e₁ e₂, { to_fun := λ x, max (e₁ x) (e₂ x), eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1, map_add_le' := λ x y, max_le (le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _)) (le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)), map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] }, le_sup_left := λ e₁ e₂ x, le_max_left _ _, le_sup_right := λ e₁ e₂ x, le_max_right _ _, sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), .. enorm.order_top, .. enorm.partial_order } @[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl @[norm_cast] lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl /-- Structure of an `emetric_space` defined by an extended norm. -/ def emetric_space : emetric_space V := { edist := λ x y, e (x - y), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero], edist_comm := e.map_sub_rev, edist_triangle := λ x y z, calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel] ... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) } /-- The subspace of vectors with finite enorm. -/ def finite_subspace : subspace 𝕜 V := { carrier := {x | e x < ⊤}, zero_mem' := by simp, add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩), smul_mem' := λ c x (hx : _ < _), calc e (c • x) = nnnorm c * e x : e.map_smul c x ... < ⊤ : ennreal.mul_lt_top ennreal.coe_ne_top hx.ne } /-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist` to ensure that this definition agrees with `e.emetric_space`. -/ instance : metric_space e.finite_subspace := begin letI := e.emetric_space, refine emetric_space.to_metric_space_of_dist _ (λ x y, _) (λ x y, rfl), change e (x - y) ≠ ⊤, exact ne_top_of_le_ne_top (ennreal.add_lt_top.2 ⟨x.2, y.2⟩).ne (e.map_sub_le x y) end lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl /-- Normed group instance on `e.finite_subspace`. -/ instance : normed_group e.finite_subspace := { norm := λ x, (e x).to_real, dist_eq := λ x y, rfl } lemma finite_norm_eq (x : e.finite_subspace) : ∥x∥ = (e x).to_real := rfl /-- Normed space instance on `e.finite_subspace`. -/ instance : normed_space 𝕜 e.finite_subspace := { norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] } end enorm
bdd0665f7151336ca9080b11d3bebb8393d94017
b9a81ebb9de684db509231c4469a7d2c88915808
/src/super/prover_state.lean
411119a5e534b96e5ff3612ae3356dc6b55870f1
[]
no_license
leanprover/super
3dd81ce8d9ac3cba20bce55e84833fadb2f5716e
47b107b4cec8f3b41d72daba9cbda2f9d54025de
refs/heads/master
1,678,482,996,979
1,676,526,367,000
1,676,526,367,000
92,215,900
12
6
null
1,513,327,539,000
1,495,570,640,000
Lean
UTF-8
Lean
false
false
15,090
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .lpo .cdcl_solver open tactic functor monad expr native namespace super structure score := (priority : ℕ) (in_sos : bool) (cost : ℕ) (age : ℕ) namespace score def prio.immediate : ℕ := 0 def prio.default : ℕ := 1 def prio.never : ℕ := 2 def sched_default (sc : score) : score := { sc with priority := prio.default } def sched_now (sc : score) : score := { sc with priority := prio.immediate } def inc_cost (sc : score) (n : ℕ) : score := { sc with cost := sc.cost + n } def min (a b : score) : score := { priority := min a.priority b.priority, in_sos := a.in_sos && b.in_sos, cost := min a.cost b.cost, age := min a.age b.age } def combine (a b : score) : score := { priority := max a.priority b.priority, in_sos := a.in_sos && b.in_sos, cost := a.cost + b.cost, age := max a.age b.age } end score namespace score meta instance : has_to_string score := ⟨λe, "[" ++ to_string e.priority ++ "," ++ to_string e.cost ++ "," ++ to_string e.age ++ ",sos=" ++ to_string e.in_sos ++ "]"⟩ end score def clause_id := ℕ namespace clause_id def to_nat (id : clause_id) : ℕ := id instance : decidable_eq clause_id := nat.decidable_eq instance : has_lt clause_id := nat.has_lt instance : decidable_rel ((<) : clause_id → clause_id → Prop) := nat.decidable_lt end clause_id meta structure derived_clause := (id : clause_id) (c : clause) (selected : list ℕ) (assertions : list expr) (sc : score) namespace derived_clause meta instance : has_to_tactic_format derived_clause := ⟨λc, do prf_fmt ← pp c.c.proof, c_fmt ← pp c.c, ass_fmt ← pp (c.assertions.map (λa, a.local_type)), return $ to_string c.sc ++ " " ++ prf_fmt ++ " " ++ c_fmt ++ " <- " ++ ass_fmt ++ " (selected: " ++ to_fmt c.selected ++ ")" ⟩ meta def clause_with_assertions (ac : derived_clause) : clause := ac.c.close_constn ac.assertions meta def update_proof (dc : derived_clause) (p : expr) : derived_clause := { dc with c := { dc.c with proof := p } } end derived_clause meta structure locked_clause := (dc : derived_clause) (reasons : list (list expr)) namespace locked_clause meta instance : has_to_tactic_format locked_clause := ⟨λc, do c_fmt ← pp c.dc, reasons_fmt ← pp (c.reasons.map (λr, r.map (λa, a.local_type))), return $ c_fmt ++ " (locked in case of: " ++ reasons_fmt ++ ")" ⟩ end locked_clause meta structure prover_state := (active : rb_map clause_id derived_clause) (passive : rb_map clause_id derived_clause) (newly_derived : list derived_clause) (prec : list expr) (locked : list locked_clause) (local_false : expr) (sat_solver : cdcl.state) (current_model : rb_map expr bool) (sat_hyps : rb_map expr (expr × expr)) (needs_sat_run : bool) (clause_counter : nat) open prover_state private meta def join_with_nl : list format → format := list.foldl (λx y, x ++ format.line ++ y) format.nil private meta def prover_state_tactic_fmt (s : prover_state) : tactic format := do active_fmts ← mapm pp $ rb_map.values s.active, passive_fmts ← mapm pp $ rb_map.values s.passive, new_fmts ← mapm pp s.newly_derived, locked_fmts ← mapm pp s.locked, sat_fmts ← mapm pp s.sat_solver.clauses, sat_model_fmts ← s.current_model.to_list.mmap (λx, if x.2 = tt then pp x.1 else pp `(not %%x.1)), prec_fmts ← mapm pp s.prec, return (join_with_nl ([to_fmt "active:"] ++ ((append (to_fmt " ")) <$> active_fmts) ++ [to_fmt "passive:"] ++ ((append (to_fmt " ")) <$> passive_fmts) ++ [to_fmt "new:"] ++ ((append (to_fmt " ")) <$> new_fmts) ++ [to_fmt "locked:"] ++ ((append (to_fmt " ")) <$> locked_fmts) ++ [to_fmt "sat formulas:"] ++ ((append (to_fmt " ")) <$> sat_fmts) ++ [to_fmt "sat model:"] ++ ((append (to_fmt " ")) <$> sat_model_fmts) ++ [to_fmt "precedence order: " ++ to_fmt prec_fmts])) meta instance : has_to_tactic_format prover_state := ⟨prover_state_tactic_fmt⟩ meta def prover := state_t prover_state tactic namespace prover local attribute [reducible] prover cdcl.solver meta instance : monad prover := infer_instance meta instance : alternative prover := infer_instance meta instance : monad_state _ prover := infer_instance meta instance : monad_state_adapter _ _ cdcl.solver prover := infer_instance meta instance : has_monad_lift tactic prover := infer_instance meta instance (α : Type) : has_coe (tactic α) (prover α) := ⟨monad_lift⟩ end prover meta def selection_strategy := derived_clause → prover derived_clause meta def get_active : prover (rb_map clause_id derived_clause) := do state ← get, return state.active meta def add_active (a : derived_clause) : prover punit := do state ← get, put { state with active := state.active.insert a.id a } meta def get_passive : prover (rb_map clause_id derived_clause) := passive <$> get meta def get_precedence : prover (list expr) := do state ← get, return state.prec meta def get_term_order : prover (expr → expr → bool) := do state ← get, return $ mk_lpo (name_of_funsym <$> state.prec) private meta def set_precedence (new_prec : list expr) : prover punit := do state ← get, put { state with prec := new_prec } meta def register_consts_in_precedence (consts : list expr) := do p ← get_precedence, p_set ← return (rb_map.set_of_list (name_of_funsym <$> p)), new_syms ← return $ list.filter (λc, ¬p_set.contains (name_of_funsym c)) consts, set_precedence (new_syms ++ p) meta def in_sat_solver {A} : cdcl.solver A → prover A := adapt_state (λ st, (st.sat_solver, st)) (λ sat st, { sat_solver := sat, ..st }) meta def collect_ass_hyps (c : clause) : prover (list expr) := let lcs := contained_lconsts c.proof in do st ← get, return (do hs ← st.sat_hyps.values, h ← [hs.1, hs.2], guard $ lcs.contains h.local_uniq_name, [h]) meta def get_clause_count : prover ℕ := do s ← get, return s.clause_counter meta def get_new_cls_id : prover clause_id := do state ← get, put { state with clause_counter := state.clause_counter + 1 }, return state.clause_counter meta def mk_derived (c : clause) (sc : score) : prover derived_clause := do ass ← collect_ass_hyps c, id ← get_new_cls_id, return { id := id, c := c, selected := [], assertions := ass, sc := sc } meta def add_inferred (c : derived_clause) : prover unit := do c' ← c.c.normalize, c' ← return { c with c := c' }, register_consts_in_precedence (contained_funsyms c'.c.type).values, state ← get, put { state with newly_derived := c' :: state.newly_derived }, skip -- FIXME: what if we've seen the variable before, but with a weaker score? meta def mk_sat_var (v : expr) (suggested_ph : bool) (suggested_ev : score) : prover unit := do st ← get, if st.sat_hyps.contains v then return () else do hpv ← mk_local_def `h v, hnv ← mk_local_def `hn $ imp v st.local_false, modify $ λst, { st with sat_hyps := st.sat_hyps.insert v (hpv, hnv) }, in_sat_solver $ cdcl.mk_var_core v suggested_ph, match v with | (pi _ _ _ _) := do c ← clause.of_proof st.local_false hpv, mk_derived c suggested_ev >>= add_inferred | _ := do cp ← clause.of_proof st.local_false hpv, mk_derived cp suggested_ev >>= add_inferred, cn ← clause.of_proof st.local_false hnv, mk_derived cn suggested_ev >>= add_inferred end meta def get_sat_hyp_core (v : expr) (ph : bool) : prover (option expr) := flip (<$>) get $ λst, match st.sat_hyps.find v with | some (hp, hn) := some $ if ph then hp else hn | none := none end meta def get_sat_hyp (v : expr) (ph : bool) : prover expr := do hyp_opt ← get_sat_hyp_core v ph, match hyp_opt with | some hyp := return hyp | none := fail $ "unknown sat variable: " ++ v.to_string end meta def add_sat_clause (c : clause) (suggested_ev : score) : prover unit := do c ← c.distinct, already_added ← flip (<$>) get $ λst, decidable.to_bool $ c.type ∈ st.sat_solver.clauses.map (λd, d.type), if already_added then return () else do c.get_lits.mmap' $ λl, mk_sat_var l.formula l.is_neg suggested_ev, in_sat_solver $ cdcl.mk_clause c, modify $ λst, { st with needs_sat_run := tt }, skip meta def sat_eval_lit (v : expr) (pol : bool) : prover bool := do v_st ← flip (<$>) get $ λst, st.current_model.find v, match v_st with | some ph := return $ if pol then ph else bnot ph | none := return tt end meta def sat_eval_assertion (assertion : expr) : prover bool := do lf ← flip (<$>) get $ λst, st.local_false, match is_local_not lf assertion.local_type with | some v := sat_eval_lit v ff | none := sat_eval_lit assertion.local_type tt end meta def sat_eval_assertions : list expr → prover bool | (a::ass) := do v_a ← sat_eval_assertion a, if v_a then sat_eval_assertions ass else return ff | [] := return tt private meta def intern_clause (c : derived_clause) : prover derived_clause := do hyp_name ← get_unused_name (mk_simple_name $ "clause_" ++ to_string c.id.to_nat) none, c' ← return $ c.c.close_constn c.assertions, assertv hyp_name c'.type c'.proof, proof' ← get_local hyp_name, type ← infer_type proof', -- FIXME: otherwise "" return $ c.update_proof $ app_of_list proof' c.assertions meta def register_as_passive (c : derived_clause) : prover unit := do c ← intern_clause c, ass_v ← sat_eval_assertions c.assertions, if c.c.num_quants = 0 ∧ c.c.num_lits = 0 then add_sat_clause c.clause_with_assertions c.sc else if ¬ass_v then do modify $ λst, { st with locked := ⟨c, []⟩ :: st.locked }, skip else do modify $ λst, { st with passive := st.passive.insert c.id c }, skip meta def remove_passive (id : clause_id) : prover unit := do state ← get, put { state with passive := state.passive.erase id }, skip meta def move_locked_to_passive : prover unit := do locked ← flip (<$>) get (λst, st.locked), new_locked ← flip filter locked (λlc, do reason_vals ← mapm sat_eval_assertions lc.reasons, c_val ← sat_eval_assertions lc.dc.assertions, if reason_vals.for_all (λr, r = ff) ∧ c_val then do modify $ λst, { st with passive := st.passive.insert lc.dc.id lc.dc }, return ff else return tt ), modify $ λst, { st with locked := new_locked }, skip meta def move_active_to_locked : prover unit := do active ← get_active, active.values.mmap' $ λac, do c_val ← sat_eval_assertions ac.assertions, if ¬c_val then do modify $ λst, { st with active := st.active.erase ac.id, locked := ⟨ac, []⟩ :: st.locked }, skip else return () meta def move_passive_to_locked : prover unit := do passive ← flip (<$>) get $ λst, st.passive, passive.to_list.mmap' $ λpc, do c_val ← sat_eval_assertions pc.2.assertions, if ¬c_val then do modify $ λst, { st with passive := st.passive.erase pc.1, locked := ⟨pc.2, []⟩ :: st.locked }, skip else return () def super_cc_config : cc_config := { em := ff } meta def do_sat_run : prover (option expr) := do sat_result ← in_sat_solver $ cdcl.run (cdcl.theory_solver_of_tactic failure), modify $ λst, { st with needs_sat_run := ff }, old_model ← prover_state.current_model <$> get, match sat_result with | (cdcl.result.unsat proof) := return (some proof) | (cdcl.result.sat new_model) := do modify $ λst, { st with current_model := new_model }, move_locked_to_passive, move_active_to_locked, move_passive_to_locked, return none end meta def take_newly_derived : prover (list derived_clause) := do state ← get, put { state with newly_derived := [] }, return state.newly_derived meta def remove_redundant (id : clause_id) (parents : list derived_clause) : prover unit := do when (not $ parents.for_all $ λp, p.id ≠ id) (fail "clause is redundant because of itself"), red ← flip (<$>) get (λst, st.active.find id), match red with | none := return () | some red := do let reasons := parents.map (λp, p.assertions), let assertion := red.assertions, if reasons.for_all $ λr, r.subset_of assertion then do modify $ λst, { st with active := st.active.erase id }, skip else do modify $ λst, { st with active := st.active.erase id, locked := ⟨red, reasons⟩ :: st.locked }, skip end meta def inference := derived_clause → prover unit meta structure inf_decl := (prio : ℕ) (inf : inference) @[user_attribute] meta def inf_attr : user_attribute := {name := `super.inf, descr := "inference for the super prover"} meta def seq_inferences : list inference → inference | [] := λgiven, return () | (inf::infs) := λgiven, do inf given, now_active ← get_active, if rb_map.contains now_active given.id then seq_inferences infs given else return () meta def simp_inference (simpl : derived_clause → prover (option clause)) : inference := λgiven, do maybe_simpld ← simpl given, match maybe_simpld with | some simpld := do derived_simpld ← mk_derived simpld given.sc.sched_now, add_inferred derived_simpld, remove_redundant given.id [] | none := return () end meta def preprocessing_rule (f : list derived_clause → prover (list derived_clause)) : prover unit := do state ← get, newly_derived' ← f state.newly_derived, state' ← get, put { state' with newly_derived := newly_derived' }, skip meta def clause_selection_strategy := ℕ → prover clause_id namespace prover_state meta def empty (local_false : expr) : prover_state := { active := rb_map.mk _ _, passive := rb_map.mk _ _, newly_derived := [], prec := [], clause_counter := 0, local_false := local_false, locked := [], sat_solver := cdcl.state.initial local_false, current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff } meta def initial (local_false : expr) (clauses : list clause) : tactic prover_state := do after_setup ← (clauses.mmap' (λc : clause, let in_sos := ((contained_lconsts c.proof).erase local_false.local_uniq_name).size = 0 in do mk_derived c { priority := score.prio.immediate, in_sos := in_sos, age := 0, cost := 0 } >>= add_inferred )).run (empty local_false), return after_setup.2 end prover_state meta def inf_score (add_cost : ℕ) (scores : list score) : prover score := do age ← get_clause_count, return $ list.foldl score.combine { priority := score.prio.default, in_sos := tt, age := age, cost := add_cost } scores meta def inf_if_successful (add_cost : ℕ) (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, inferred.mmap' $ λc, inf_score add_cost [parent.sc] >>= mk_derived c >>= add_inferred) <|> return () meta def simp_if_successful (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, inferred.mmap' $ λc, mk_derived c parent.sc.sched_now >>= add_inferred, remove_redundant parent.id []) <|> return () end super
598dde5d47cd9f63bb7a611afe751b76f90d23ba
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/opt_param_cc.lean
22fdd097679f74ad0a79a2272c20fca9e54306f4
[ "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
717
lean
def f (a : nat) (b : nat := a) (c : nat := a) := a + b + c lemma ex1 (a a' b c d : nat) (h : b = c) (h2 : a = a') : f a b d = f a' c d := by cc lemma ex2 (a a' b c d : nat) (h : b = c) (h2 : a = a') : f a b d = f a' c d := by rw [h, h2] set_option pp.beta true set_option pp.all true lemma ex3 (a a' b c d : nat) (h : b = c) (h2 : a = a') : f a b d = f a' c d := begin simp [h, h2], end open tactic run_cmd do c ← mk_const `f, get_fun_info c >>= trace run_cmd do c ← mk_const `eq, get_fun_info c >>= trace run_cmd do c ← mk_const `id, get_fun_info c >>= trace set_option trace.congr_lemma true set_option trace.app_builder true run_cmd do h ← mk_const `f, l ← mk_congr_lemma_simp h, trace l^.type
a6fcbacf7a1ceb22b6b003cdfa2210d3852b7917
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/punit_instances.lean
830975dd6fbc9d1af497e3febc1a60d3716beff1
[]
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,058
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Instances on punit. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.basic import Mathlib.PostPort universes u_1 u namespace Mathlib namespace punit protected instance comm_group : comm_group PUnit := comm_group.mk (fun (_x _x : PUnit) => PUnit.unit) sorry PUnit.unit sorry sorry (fun (_x : PUnit) => PUnit.unit) (fun (_x _x : PUnit) => PUnit.unit) sorry sorry protected instance comm_ring : comm_ring PUnit := comm_ring.mk add_comm_group.add add_comm_group.add_assoc add_comm_group.zero add_comm_group.zero_add add_comm_group.add_zero add_comm_group.neg add_comm_group.sub add_comm_group.add_left_neg add_comm_group.add_comm comm_group.mul comm_group.mul_assoc comm_group.one comm_group.one_mul comm_group.mul_one sorry sorry comm_group.mul_comm protected instance complete_boolean_algebra : complete_boolean_algebra PUnit := complete_boolean_algebra.mk (fun (_x _x : PUnit) => PUnit.unit) (fun (_x _x : PUnit) => True) (fun (_x _x : PUnit) => False) sorry sorry sorry sorry sorry sorry (fun (_x _x : PUnit) => PUnit.unit) sorry sorry sorry sorry PUnit.unit sorry PUnit.unit sorry (fun (_x : PUnit) => PUnit.unit) (fun (_x _x : PUnit) => PUnit.unit) sorry sorry sorry (fun (_x : set PUnit) => PUnit.unit) (fun (_x : set PUnit) => PUnit.unit) sorry sorry sorry sorry sorry sorry protected instance canonically_ordered_add_monoid : canonically_ordered_add_monoid PUnit := canonically_ordered_add_monoid.mk comm_ring.add comm_ring.add_assoc comm_ring.zero comm_ring.zero_add comm_ring.add_zero comm_ring.add_comm complete_boolean_algebra.le complete_boolean_algebra.lt complete_boolean_algebra.le_refl complete_boolean_algebra.le_trans complete_boolean_algebra.le_antisymm sorry sorry complete_boolean_algebra.bot complete_boolean_algebra.bot_le sorry protected instance linear_ordered_cancel_add_comm_monoid : linear_ordered_cancel_add_comm_monoid PUnit := linear_ordered_cancel_add_comm_monoid.mk canonically_ordered_add_monoid.add canonically_ordered_add_monoid.add_assoc sorry canonically_ordered_add_monoid.zero canonically_ordered_add_monoid.zero_add canonically_ordered_add_monoid.add_zero canonically_ordered_add_monoid.add_comm sorry canonically_ordered_add_monoid.le canonically_ordered_add_monoid.lt canonically_ordered_add_monoid.le_refl canonically_ordered_add_monoid.le_trans canonically_ordered_add_monoid.le_antisymm canonically_ordered_add_monoid.add_le_add_left sorry sorry (fun (_x _x : PUnit) => decidable.true) punit.decidable_eq fun (_x _x : PUnit) => decidable.false protected instance semimodule (R : Type u) [semiring R] : semimodule R PUnit := semimodule.of_core (semimodule.core.mk (has_scalar.mk fun (_x : R) (_x : PUnit) => PUnit.unit) sorry sorry sorry sorry) @[simp] theorem zero_eq : 0 = PUnit.unit := rfl @[simp] theorem one_eq : 1 = PUnit.unit := rfl @[simp] theorem add_eq (x : PUnit) (y : PUnit) : x + y = PUnit.unit := rfl @[simp] theorem mul_eq (x : PUnit) (y : PUnit) : x * y = PUnit.unit := rfl @[simp] theorem sub_eq (x : PUnit) (y : PUnit) : x - y = PUnit.unit := rfl @[simp] theorem neg_eq (x : PUnit) : -x = PUnit.unit := rfl @[simp] theorem inv_eq (x : PUnit) : x⁻¹ = PUnit.unit := rfl theorem smul_eq (x : PUnit) (y : PUnit) : x • y = PUnit.unit := rfl @[simp] theorem top_eq : ⊤ = PUnit.unit := rfl @[simp] theorem bot_eq : ⊥ = PUnit.unit := rfl @[simp] theorem sup_eq (x : PUnit) (y : PUnit) : x ⊔ y = PUnit.unit := rfl @[simp] theorem inf_eq (x : PUnit) (y : PUnit) : x ⊓ y = PUnit.unit := rfl @[simp] theorem Sup_eq (s : set PUnit) : Sup s = PUnit.unit := rfl @[simp] theorem Inf_eq (s : set PUnit) : Inf s = PUnit.unit := rfl @[simp] protected theorem le (x : PUnit) (y : PUnit) : x ≤ y := trivial @[simp] theorem not_lt (x : PUnit) (y : PUnit) : ¬x < y := not_false
4b322837149e3c5974198ef6c19db8be40026482
abd85493667895c57a7507870867b28124b3998f
/src/algebra/field_power.lean
dbdc9a09c9b6eda4b9805dc4589072bd6b1c6907
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
5,161
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Integer power operation on fields. -/ import algebra.group_with_zero_power import tactic.linarith universe u @[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) (a : K) : ∀ (n : ℤ), f (a ^ n) = f a ^ n | (n : ℕ) := f.map_pow a n | -[1+n] := by simp only [fpow_neg_succ_of_nat, f.map_pow, f.map_inv, f.map_one] namespace is_ring_hom lemma map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K → L) [is_ring_hom f] (a : K) : ∀ (n : ℤ), f (a ^ n) = f a ^ n := (ring_hom.of f).map_fpow a end is_ring_hom section ordered_field_power open int variables {K : Type u} [discrete_linear_ordered_field K] lemma fpow_nonneg_of_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (of_nat n) := pow_nonneg ha _ | -[1+n] := inv_nonneg.2 $ pow_nonneg ha _ lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (of_nat n) := pow_pos ha _ | -[1+n] := inv_pos.2 $ pow_pos ha _ lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [fpow_of_nat, of_nat_eq_coe], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [fpow_neg_succ_of_nat, one_div_eq_inv], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [fpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply fpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp end ordered_field_power lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n | 1 h := by simp; assumption | (k+2) h := begin rw ←one_mul (1 : K), apply mul_lt_mul, { assumption }, { apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)}, { apply zero_lt_one }, { apply le_of_lt (lt_trans zero_lt_one hp) } end lemma one_lt_fpow {K} [discrete_linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (int.of_nat n) h := one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h)) section ordered variables {K : Type*} [discrete_linear_ordered_field K] lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply fpow_pos_of_pos, exact_mod_cast h } lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.fpow_pos_of_pos h n) lemma fpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := by linarith, have h₀ : x ≠ 0 := by linarith, have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have hxm₀ : x^m ≠ 0 := ne_of_gt hxm, suffices : 1 < x^(n-m), { replace := mul_lt_mul_of_pos_right this hxm, simp [sub_eq_add_neg] at this, simpa [*, fpow_add, mul_assoc, fpow_neg, inv_mul_cancel], }, apply one_lt_fpow hx, linarith, end @[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (fpow_strict_mono hx).lt_iff_lt @[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (fpow_strict_mono hx).le_iff_le lemma injective_fpow {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases lt_trichotomy x 1 with H|rfl|H, { apply (fpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← fpow_neg_one, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], }, { contradiction }, { exact (fpow_strict_mono H).injective h, }, end @[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (injective_fpow h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, norm_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_fpow q n end
3687a35ecb35b480a3aba4c63c3420401e35abe0
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Elab/Tactic/Induction.lean
18b5ae63cb4c99d0836417c54a120dfcd8702a78
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,775
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, Sebastian Ullrich -/ import Lean.Meta.RecursorInfo import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Generalize namespace Lean namespace Elab namespace Tactic open Meta -- Recall that -- majorPremise := parser! optional (try (ident >> " : ")) >> termParser private def getAuxHypothesisName (stx : Syntax) : Option Name := if ((stx.getArg 1).getArg 0).isNone then none else some (((stx.getArg 1).getArg 0).getIdAt 0) private def getMajor (stx : Syntax) : Syntax := (stx.getArg 1).getArg 1 private def elabMajor (h? : Option Name) (major : Syntax) : TacticM Expr := do match h? with | none => withMainMVarContext $ elabTerm major none | some h => withMainMVarContext do lctx ← getLCtx; let x := lctx.getUnusedName `x; major ← elabTerm major none; evalGeneralizeAux h? major x; withMainMVarContext do lctx ← getLCtx; match lctx.findFromUserName? x with | some decl => pure decl.toExpr | none => throwError "failed to generalize" private def generalizeMajor (major : Expr) : TacticM Expr := do match major with | Expr.fvar _ _ => pure major | _ => do liftMetaTacticAux fun mvarId => do mvarId ← Meta.generalize mvarId major `x; (fvarId, mvarId) ← Meta.intro1 mvarId; pure (mkFVar fvarId, [mvarId]) /- Recall that ``` generalizingVars := optional (" generalizing " >> many1 ident) «induction» := parser! nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> withAlts ``` `stx` is syntax for `induction`. -/ private def getGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) := withRef stx $ let generalizingStx := stx.getArg 3; if generalizingStx.isNone then pure #[] else withMainMVarContext do trace `Elab.induction fun _ => generalizingStx; let vars := (generalizingStx.getArg 1).getArgs; getFVarIds vars -- process `generalizingVars` subterm of induction Syntax `stx`. private def generalizeVars (stx : Syntax) (major : Expr) : TacticM Nat := do fvarIds ← getGeneralizingFVarIds stx; liftMetaTacticAux fun mvarId => do (fvarIds, mvarId') ← Meta.revert mvarId fvarIds; when (fvarIds.contains major.fvarId!) $ Meta.throwTacticEx `induction mvarId "major premise depends on variable being generalized"; pure (fvarIds.size, [mvarId']) private def getAlts (withAlts : Syntax) : Array Syntax := (withAlts.getArg 2).getArgs.getSepElems /- Given an `inductionAlt` of the form ``` nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser ``` -/ private def getAltName (alt : Syntax) : Name := (alt.getArg 0).getId.eraseMacroScopes private def getAltVarNames (alt : Syntax) : Array Name := (alt.getArg 1).getArgs.map Syntax.getId private def getAltRHS (alt : Syntax) : Syntax := alt.getArg 3 /- Given alts of the form ``` nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser ``` esnure the first `ident'` is `_` or a constructor name. -/ private def checkAltCtorNames (alts : Array Syntax) (ctorNames : List Name) : TacticM Unit := alts.forM $ fun alt => do let n := getAltName alt; withRef alt $ trace `Elab.checkAlt $ fun _ => n ++ ", " ++ alt; unless (n == `_ || ctorNames.any (fun ctorName => n.isSuffixOf ctorName)) $ throwErrorAt (alt.getArg 0) ("invalid constructor name '" ++ toString n ++ "'") structure RecInfo := (recName : Name) (altVars : Array (List Name) := #[]) -- new variable names for each minor premise (altRHSs : Array Syntax := #[]) -- RHS for each minor premise def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal := liftMetaMAtMain $ fun mvarId => do majorType ← inferType major; majorType ← whnf majorType; matchConstInduct majorType.getAppFn (fun _ => Meta.throwTacticEx `induction mvarId ("major premise type is not an inductive type " ++ indentExpr majorType)) (fun val _ => pure val) private partial def getRecFromUsingLoop (baseRecName : Name) : Expr → TacticM (Option Meta.RecursorInfo) | majorType => do let continue (majorType : Expr) : TacticM (Option Meta.RecursorInfo) := do { majorType? ← unfoldDefinition? majorType; match majorType? with | some majorType => withIncRecDepth $ getRecFromUsingLoop majorType | none => pure none }; majorType ← whnfCore majorType; match majorType.getAppFn with | Expr.const name _ _ => do let candidate := name ++ baseRecName; env ← getEnv; match env.find? candidate with | some _ => catch (liftMetaMAtMain fun _ => do info ← Meta.mkRecursorInfo candidate; pure (some info)) (fun _ => continue majorType) | none => continue majorType | _ => continue majorType def getRecFromUsing (major : Expr) (baseRecName : Name) : TacticM Meta.RecursorInfo := do majorType ← inferType major; recInfo? ← getRecFromUsingLoop baseRecName majorType; match recInfo? with | some recInfo => pure recInfo | none => do result ← resolveGlobalName baseRecName; match result with | _::_::_ => throwError ("ambiguous recursor name '" ++ baseRecName ++ "', " ++ toString (result.map Prod.fst)) | [(recName, [])] => do catch (liftMetaMAtMain fun _ => Meta.mkRecursorInfo recName) (fun _ => throwError ("invalid recursor name '" ++ baseRecName ++ "'")) | _ => throwError ("invalid recursor name '" ++ baseRecName ++ "'") /- Create `RecInfo` assuming builtin recursor -/ private def getRecInfoDefault (major : Expr) (withAlts : Syntax) (allowMissingAlts : Bool) : TacticM (RecInfo × Array Name) := do indVal ← getInductiveValFromMajor major; let recName := mkRecFor indVal.name; if withAlts.isNone then pure ({ recName := recName }, #[]) else do let ctorNames := indVal.ctors; let alts := getAlts withAlts; checkAltCtorNames alts ctorNames; (altVars, altRHSs, remainingAlts, _) ← ctorNames.foldlM (fun (result : Array (List Name) × Array Syntax × Array Syntax × Option Syntax) (ctorName : Name) => do let (altVars, altRHSs, remainingAlts, prevAnonymousAlt?) := result; match remainingAlts.findIdx? (fun alt => (getAltName alt).isSuffixOf ctorName) with | some idx => let newAlt := remainingAlts.get! idx; pure (altVars.push (getAltVarNames newAlt).toList, altRHSs.push (getAltRHS newAlt), remainingAlts.eraseIdx idx, prevAnonymousAlt?) | none => match remainingAlts.findIdx? (fun alt => getAltName alt == `_) with | some idx => let newAlt := remainingAlts.get! idx; pure (altVars.push (getAltVarNames newAlt).toList, altRHSs.push (getAltRHS newAlt), remainingAlts.eraseIdx idx, some newAlt) | none => match prevAnonymousAlt? with | some alt => pure (altVars.push (getAltVarNames alt).toList, altRHSs.push (getAltRHS alt), remainingAlts, prevAnonymousAlt?) | none => if allowMissingAlts then pure (altVars.push [], altRHSs.push Syntax.missing, remainingAlts, prevAnonymousAlt?) else throwError ("alternative for constructor '" ++ toString ctorName ++ "' is missing")) (#[], #[], alts, none); unless remainingAlts.isEmpty $ throwErrorAt (remainingAlts.get! 0) "unused alternative"; pure ({ recName := recName, altVars := altVars, altRHSs := altRHSs }, ctorNames.toArray) /- Recall that ``` inductionAlt : Parser := nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> (hole <|> syntheticHole <|> tacticParser) inductionAlts : Parser := withPosition $ fun pos => "|" >> sepBy1 inductionAlt (checkColGe pos.column "alternatives must be indented" >> "|") withAlts : Parser := optional (" with " >> inductionAlts) usingRec : Parser := optional (" using " >> ident) ``` -/ private def getRecInfo (stx : Syntax) (major : Expr) : TacticM RecInfo := withRef stx $ let usingRecStx := stx.getArg 2; let withAlts := stx.getArg 4; if usingRecStx.isNone then do (rinfo, _) ← getRecInfoDefault major withAlts false; pure rinfo else do let baseRecName := (usingRecStx.getIdAt 1).eraseMacroScopes; recInfo ← getRecFromUsing major baseRecName; let recName := recInfo.recursorName; if withAlts.isNone then pure { recName := recName } else do let alts := getAlts withAlts; paramNames ← liftMetaMAtMain $ fun _ => getParamNames recInfo.recursorName; (altVars, altRHSs, remainingAlts, _) ← paramNames.size.foldM (fun (i : Nat) (result : Array (List Name) × Array Syntax × Array Syntax × Option Syntax) => if recInfo.isMinor i then let paramName := paramNames.get! i; let (altVars, altRHSs, remainingAlts, prevAnonymousAlt?) := result; match remainingAlts.findIdx? (fun alt => getAltName alt == paramName) with | some idx => let newAlt := remainingAlts.get! idx; pure (altVars.push (getAltVarNames newAlt).toList, altRHSs.push (getAltRHS newAlt), remainingAlts.eraseIdx idx, prevAnonymousAlt?) | none => match remainingAlts.findIdx? (fun alt => getAltName alt == `_) with | some idx => let newAlt := remainingAlts.get! idx; pure (altVars.push (getAltVarNames newAlt).toList, altRHSs.push (getAltRHS newAlt), remainingAlts.eraseIdx idx, some newAlt) | none => match prevAnonymousAlt? with | some alt => pure (altVars.push (getAltVarNames alt).toList, altRHSs.push (getAltRHS alt), remainingAlts, prevAnonymousAlt?) | none => throwError ("alternative for minor premise '" ++ toString paramName ++ "' is missing") else pure result) (#[], #[], alts, none); unless remainingAlts.isEmpty $ throwErrorAt (remainingAlts.get! 0) "unused alternative"; pure { recName := recName, altVars := altVars, altRHSs := altRHSs } -- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic def isHoleRHS (rhs : Syntax) : Bool := rhs.isOfKind `Lean.Parser.Term.syntheticHole || rhs.isOfKind `Lean.Parser.Term.hole private def processResult (altRHSs : Array Syntax) (result : Array Meta.InductionSubgoal) : TacticM Unit := do if altRHSs.isEmpty then setGoals $ result.toList.map $ fun s => s.mvarId else do unless (altRHSs.size == result.size) $ throwError ("mistmatch on the number of subgoals produced (" ++ toString result.size ++ ") and " ++ "alternatives provided (" ++ toString altRHSs.size ++ ")"); gs ← result.size.foldM (fun i gs => do let subgoal := result.get! i; let rhs := altRHSs.get! i; let ref := rhs; let mvarId := subgoal.mvarId; if isHoleRHS rhs then withMVarContext mvarId $ withRef rhs do mvarDecl ← getMVarDecl mvarId; val ← elabTermEnsuringType rhs mvarDecl.type; assignExprMVar mvarId val; gs' ← getMVarsNoDelayed val; let gs' := gs'.toList; tagUntaggedGoals mvarDecl.userName `induction gs'; pure (gs ++ gs') else do setGoals [mvarId]; evalTactic rhs; done; pure gs) []; setGoals gs @[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focusAux $ do let h? := getAuxHypothesisName stx; major ← elabMajor h? (getMajor stx); major ← generalizeMajor major; n ← generalizeVars stx major; recInfo ← getRecInfo stx major; (mvarId, _) ← getMainGoal; result ← liftMetaM $ Meta.induction mvarId major.fvarId! recInfo.recName recInfo.altVars; processResult recInfo.altRHSs result private partial def checkCasesResultAux (casesResult : Array Meta.CasesSubgoal) (ctorNames : Array Name) (altRHSs : Array Syntax) : Nat → Nat → TacticM Unit | i, j => if h : j < altRHSs.size then do let altRHS := altRHSs.get ⟨j, h⟩; if altRHS.isMissing then checkCasesResultAux i (j+1) else let ctorName := ctorNames.get! j; if h : i < casesResult.size then let subgoal := casesResult.get ⟨i, h⟩; if ctorName == subgoal.ctorName then checkCasesResultAux (i+1) (j+1) else throwError ("alternative for '" ++ subgoal.ctorName ++ "' has not been provided") else throwError ("alternative for '" ++ ctorName ++ "' is not needed") else if h : i < casesResult.size then let subgoal := casesResult.get ⟨i, h⟩; throwError ("alternative for '" ++ subgoal.ctorName ++ "' has not been provided") else pure () private def checkCasesResult (casesResult : Array Meta.CasesSubgoal) (ctorNames : Array Name) (altRHSs : Array Syntax) : TacticM Unit := unless altRHSs.isEmpty $ checkCasesResultAux casesResult ctorNames altRHSs 0 0 @[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focusAux $ do -- parser! nonReservedSymbol "cases " >> majorPremise >> withAlts let h? := getAuxHypothesisName stx; major ← elabMajor h? (getMajor stx); major ← generalizeMajor major; (mvarId, _) ← getMainGoal; let withAlts := stx.getArg 2; (recInfo, ctorNames) ← getRecInfoDefault major withAlts true; result ← liftMetaM $ Meta.cases mvarId major.fvarId! recInfo.altVars; checkCasesResult result ctorNames recInfo.altRHSs; let result := result.map (fun s => s.toInductionSubgoal); let altRHSs := recInfo.altRHSs.filter $ fun stx => !stx.isMissing; processResult altRHSs result end Tactic end Elab end Lean
cb83c99b4ecff7e55402aa7e8e7e116f4af6e5e4
367134ba5a65885e863bdc4507601606690974c1
/src/control/traversable/basic.lean
809090741d10e97871ded5b0ee897a9429228b1a
[ "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
9,532
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import control.functor /-! # Traversable type class Type classes for traversing collections. The concepts and laws are taken from <http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html> Traversable collections are a generalization of functors. Whereas functors (such as `list`) allow us to apply a function to every element, it does not allow functions which external effects encoded in a monad. Consider for instance a functor `invite : email → io response` that takes an email address, sends an email and waits for a response. If we have a list `guests : list email`, using calling `invite` using `map` gives us the following: `map invite guests : list (io response)`. It is not what we need. We need something of type `io (list response)`. Instead of using `map`, we can use `traverse` to send all the invites: `traverse invite guests : io (list response)`. `traverse` applies `invite` to every element of `guests` and combines all the resulting effects. In the example, the effect is encoded in the monad `io` but any applicative functor is accepted by `traverse`. For more on how to use traversable, consider the Haskell tutorial: <https://en.wikibooks.org/wiki/Haskell/Traversable> ## Main definitions * `traversable` type class - exposes the `traverse` function * `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection * `is_lawful_traversable` - laws for a traversable functor * `applicative_transformation` - the notion of a natural transformation for applicative functors ## Tags traversable iterator functor applicative ## References * "Applicative Programming with Effects", by Conor McBride and Ross Paterson, Journal of Functional Programming 18:1 (2008) 1-13, online at <http://www.soi.city.ac.uk/~ross/papers/Applicative.html> * "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in Mathematically-Structured Functional Programming, 2006, online at <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator> * "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in Mathematically-Structured Functional Programming, 2012, online at <http://arxiv.org/pdf/1202.2919> -/ open function (hiding comp) universes u v w section applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] /-- A transformation between applicative functors. It a natural transformation such that `app` preserves the `has_pure.pure` and `functor.map` (`<*>`) operations. See `applicative_transformation.preserves_map` for naturality. -/ structure applicative_transformation : Type (max (u+1) v w) := (app : Π α : Type u, F α → G α) (preserves_pure' : ∀ {α : Type u} (x : α), app _ (pure x) = pure x) (preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app _ (x <*> y) = app _ x <*> app _ y) end applicative_transformation namespace applicative_transformation variables (F : Type u → Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u → Type w) [applicative G] [is_lawful_applicative G] instance : has_coe_to_fun (applicative_transformation F G) := { F := λ _, Π {α}, F α → G α, coe := λ a, a.app } variables {F G} @[simp] lemma app_eq_coe (η : applicative_transformation F G) : η.app = η := rfl @[simp] lemma coe_mk (f : Π (α : Type u), F α → G α) (pp ps) : ⇑(applicative_transformation.mk f pp ps) = f := rfl protected lemma congr_fun (η η' : applicative_transformation F G) (h : η = η') {α : Type u} (x : F α) : η x = η' x := congr_arg (λ η'' : applicative_transformation F G, η'' x) h protected lemma congr_arg (η : applicative_transformation F G) {α : Type u} {x y : F α} (h : x = y) : η x = η y := congr_arg (λ z : F α, η z) h lemma coe_inj ⦃η η' : applicative_transformation F G⦄ (h : (η : Π α, F α → G α) = η') : η = η' := by { cases η, cases η', congr, exact h } @[ext] lemma ext ⦃η η' : applicative_transformation F G⦄ (h : ∀ (α : Type u) (x : F α), η x = η' x) : η = η' := by { apply coe_inj, ext1 α, exact funext (h α) } lemma ext_iff {η η' : applicative_transformation F G} : η = η' ↔ ∀ (α : Type u) (x : F α), η x = η' x := ⟨λ h α x, h ▸ rfl, λ h, ext h⟩ section preserves variables (η : applicative_transformation F G) @[functor_norm] lemma preserves_pure : ∀ {α} (x : α), η (pure x) = pure x := η.preserves_pure' @[functor_norm] lemma preserves_seq : ∀ {α β : Type u} (x : F (α → β)) (y : F α), η (x <*> y) = η x <*> η y := η.preserves_seq' @[functor_norm] lemma preserves_map {α β} (x : α → β) (y : F α) : η (x <$> y) = x <$> η y := by rw [← pure_seq_eq_map, η.preserves_seq]; simp with functor_norm lemma preserves_map' {α β} (x : α → β) : @η _ ∘ functor.map x = functor.map x ∘ @η _ := by { ext y, exact preserves_map η x y } end preserves /-- The identity applicative transformation from an applicative functor to itself. -/ def id_transformation : applicative_transformation F F := { app := λ α, id, preserves_pure' := by simp, preserves_seq' := λ α β x y, by simp } instance : inhabited (applicative_transformation F F) := ⟨id_transformation⟩ universes s t variables {H : Type u → Type s} [applicative H] [is_lawful_applicative H] /-- The composition of applicative transformations. -/ def comp (η' : applicative_transformation G H) (η : applicative_transformation F G) : applicative_transformation F H := { app := λ α x, η' (η x), preserves_pure' := λ α x, by simp with functor_norm, preserves_seq' := λ α β x y, by simp with functor_norm } @[simp] lemma comp_apply (η' : applicative_transformation G H) (η : applicative_transformation F G) {α : Type u} (x : F α) : η'.comp η x = η' (η x) := rfl lemma comp_assoc {I : Type u → Type t} [applicative I] [is_lawful_applicative I] (η'' : applicative_transformation H I) (η' : applicative_transformation G H) (η : applicative_transformation F G) : (η''.comp η').comp η = η''.comp (η'.comp η) := rfl @[simp] lemma comp_id (η : applicative_transformation F G) : η.comp id_transformation = η := ext $ λ α x, rfl @[simp] lemma id_comp (η : applicative_transformation F G) : id_transformation.comp η = η := ext $ λ α x, rfl end applicative_transformation open applicative_transformation /-- A traversable functor is a functor along with a way to commute with all applicative functors (see `sequence`). For example, if `t` is the traversable functor `list` and `m` is the applicative functor `io`, then given a function `f : α → io β`, the function `functor.map f` is `list α → list (io β)`, but `traverse f` is `list α → io (list β)`. -/ class traversable (t : Type u → Type u) extends functor t := (traverse : Π {m : Type u → Type u} [applicative m] {α β}, (α → m β) → t α → m (t β)) open functor export traversable (traverse) section functions variables {t : Type u → Type u} variables {m : Type u → Type v} [applicative m] variables {α β : Type u} variables {f : Type u → Type u} [applicative f] /-- A traversable functor commutes with all applicative functors. -/ def sequence [traversable t] : t (f α) → f (t α) := traverse id end functions /-- A traversable functor is lawful if its `traverse` satisfies a number of additional properties. It must send `id.mk` to `id.mk`, send the composition of applicative functors to the composition of the `traverse` of each, send each function `f` to `λ x, f <$> x`, and satisfy a naturality condition with respect to applicative transformations. -/ class is_lawful_traversable (t : Type u → Type u) [traversable t] extends is_lawful_functor t : Type (u+1) := (id_traverse : ∀ {α} (x : t α), traverse id.mk x = x ) (comp_traverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α β γ} (f : β → F γ) (g : α → G β) (x : t α), traverse (comp.mk ∘ map f ∘ g) x = comp.mk (map (traverse f) (traverse g x))) (traverse_eq_map_id : ∀ {α β} (f : α → β) (x : t α), traverse (id.mk ∘ f) x = id.mk (f <$> x)) (naturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α β} (f : α → F β) (x : t α), η (traverse f x) = traverse (@η _ ∘ f) x) instance : traversable id := ⟨λ _ _ _ _, id⟩ instance : is_lawful_traversable id := by refine {..}; intros; refl section variables {F : Type u → Type v} [applicative F] instance : traversable option := ⟨@option.traverse⟩ instance : traversable list := ⟨@list.traverse⟩ end namespace sum variables {σ : Type u} variables {F : Type u → Type u} variables [applicative F] /-- Defines a `traverse` function on the second component of a sum type. This is used to give a `traversable` instance for the functor `σ ⊕ -`. -/ protected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) | (sum.inl x) := pure (sum.inl x) | (sum.inr x) := sum.inr <$> f x end sum instance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩
c2f9c4bc871b23d79d400c43bede51c2353ca57d
3ed5a65c1ab3ce5d1a094edce8fa3287980f197b
/src/herstein/ex2_3/Q_04_Alt.lean
1c961b0c77b6dcfd65c93affdbb69aa123e12257
[]
no_license
group-study-group/herstein
35d32e77158efa2cc303c84e1ee5e3bc80831137
f5a1a72eb56fa19c19ece0cb3ab6cf7ffd161f66
refs/heads/master
1,586,202,191,519
1,548,969,759,000
1,548,969,759,000
157,746,953
0
0
null
1,542,412,901,000
1,542,302,366,000
Lean
UTF-8
Lean
false
false
3,713
lean
import algebra.group algebra.group_power variables {G: Type*} (a b : G) @[symm] theorem gpow_add' {G : Type*} [group G] (a : G) (i : ℤ): a^(i + 1) = a * a^i := by rw [add_comm, gpow_add]; simp @[symm] theorem gpow_add'' {G : Type*} [group G] (a : G) (i : ℤ): a^(i + 1) = a^i * a := by rw [gpow_add]; simp def Q04H {G : Type*} [group G] (a b : G) (i : ℤ): Prop := (a * b)^i = a^i * b^i theorem Q04Alt [group G] (H : ∀ a b : G, ∃ i : ℤ, (Q04H a b i) ∧ (Q04H a b (i + 1)) ∧ (Q04H a b (i + 1 + 1)) ) : ∀ a b : G, a * b = b * a := λ a b : G, exists.elim (H a b) (λ i Hi, have H1 : b * a^i = a^i * b, from have H10 : (a * b)^(i + 1) = a^(i + 1) * b^(i + 1), from Hi.2.1, have H11 : (a*b) * (a*b)^i = (a * a^i) * (b * b^i), by {rw [(gpow_add' (a*b) i).symm, (gpow_add' a i).symm, (gpow_add' b i).symm], exact H10}, have H12 : a * ( b * (a*b)^i) = a * (a^i * (b * b^i)), by {rw [mul_assoc, mul_assoc] at H11, exact H11}, have H13 : b * (a*b)^i = a^i * (b * b^i), from mul_left_cancel H12, have H14 : b * (a^i * b^i) = a^i * (b * b^i), from Hi.1 ▸ H13, have H15 : b * a^i * b^i = a^i * b * b^i, from by {rw [mul_assoc, mul_assoc], exact H14}, (mul_right_inj (b^i)).mp H15, show a * b = b * a, from have H20 : a * b * (a * b)^(i+1) = a * a^(i+1) * (b * b^(i+1)), by {rw [(gpow_add' (a*b) (i+1)).symm, (gpow_add' a (i+1)).symm, (gpow_add' b (i+1)).symm], exact Hi.2.2}, have H21 : a * b * (a^(i+1)*b^(i+1)) = a * a^(i+1) * (b * b^(i+1)), from Hi.2.1 ▸ H20, have H22 : a * b * a^(i+1) * b^(i+1) = a * a^(i+1) * b * b^(i+1), by {conv {to_lhs, rw [mul_assoc]}, conv {to_rhs, rw [mul_assoc]}, exact H21}, have H23 : a * b * a^(i+1) = a * a^(i+1) * b, from mul_right_cancel H22, have H24 : a * (b * a^(i+1)) = a * (a^(i+1) * b), by {rw [mul_assoc, mul_assoc] at H23; exact H23}, have H25 : b * a^(i+1) = a^(i+1) * b, from mul_left_cancel H24, have H26 : b * (a^i * a) = (a^i * a) * b, from (gpow_add'' a i) ▸ H25, have H27 : b * a^i * a = a^i * a * b, by {rw [mul_assoc], exact H26}, have H28 : a^i * b * a = a^i * a * b, from H1 ▸ H27, have H29 : a^i * (b * a) = a^i * (a * b), by {rw [mul_assoc, mul_assoc] at H28, exact H28}, have H30 : b * a = a * b, from mul_left_cancel H29, H30.symm ) /- theorem Q04AltAlt [group G] : (∀ a b : G, (∃ i : ℤ, (Q04H a b i) ∧ (Q04H a b (i + 1)) ∧ (Q04H a b (i + 2)))) → ∀ a b : G, a * b = b * a := begin intro H0, intros a b, apply exists.elim (H0 a b), intros i Hi, unfold Q04H at Hi, have H1 : a^i * b = b * a^i, apply (mul_right_inj (b^i)).1, apply eq.symm, rw mul_assoc, rw ←(Hi.1), apply (mul_left_inj (a)).1, rw [←mul_assoc, ←mul_assoc, ←mul_assoc], rw [←gpow_add', ←gpow_add', mul_assoc, ←gpow_add'], from Hi.2.1, let H3 : _ ^ ( i + ( 1 + 1)) = _ := Hi.2.2, rw ←add_assoc at H3, rw gpow_add' at H3, rw (show i + 2 = (i + 1) + 1, by rw [add_assoc];refl) at H3, conv at H3 begin to_rhs, rw gpow_add', end, rw gpow_add' at H3, rw [mul_assoc, mul_assoc a (a^(i + 1))] at H3, rw mul_left_inj at H3, rw Hi.1 at H3, rw (gpow_add' b ) at H3, rw (gpow_add' b ) at H3, repeat {rw [←mul_assoc] at H3}, rw mul_right_inj at H3, rw (gpow_add' a) at H3, rw mul_assoc (a) at H3, rw (H1) at H3, rw [mul_assoc a] at H3, rw mul_assoc b (a^i) b at H3, rw H1 at H3, repeat {rw [←mul_assoc] at H3}, rw mul_right_inj at H3, rw mul_right_inj at H3, rw H3, end -/
7e1bfe22d558aeefab85fa9e6e86d01ccf36dc22
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/ideal/norm.lean
b0e0cdd6fcd752141147d757f562b1ece8a0a7d7
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
28,887
lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Alex J. Best -/ import algebra.char_p.quotient import data.finsupp.fintype import data.int.absolute_value import data.int.associated import linear_algebra.free_module.determinant import linear_algebra.free_module.ideal_quotient import ring_theory.dedekind_domain.pid import ring_theory.local_properties import ring_theory.localization.norm /-! # Ideal norms This file defines the absolute ideal norm `ideal.abs_norm (I : ideal R) : ℕ` as the cardinality of the quotient `R ⧸ I` (setting it to 0 if the cardinality is infinite), and the relative ideal norm `ideal.span_norm R (I : ideal S) : ideal S` as the ideal spanned by the norms of elements in `I`. ## Main definitions * `submodule.card_quot (S : submodule R M)`: the cardinality of the quotient `M ⧸ S`, in `ℕ`. This maps `⊥` to `0` and `⊤` to `1`. * `ideal.abs_norm (I : ideal R)`: the absolute ideal norm, defined as the cardinality of the quotient `R ⧸ I`, as a bundled monoid-with-zero homomorphism. * `ideal.span_norm R (I : ideal S)`: the ideal spanned by the norms of elements in `I`. This is used to define `ideal.rel_norm`. * `ideal.rel_norm R (I : ideal S)`: the relative ideal norm as a bundled monoid-with-zero morphism, defined as the ideal spanned by the norms of elements in `I`. ## Main results * `map_mul ideal.abs_norm`: multiplicativity of the ideal norm is bundled in the definition of `ideal.abs_norm` * `ideal.nat_abs_det_basis_change`: the ideal norm is given by the determinant of the basis change matrix * `ideal.abs_norm_span_singleton`: the ideal norm of a principal ideal is the norm of its generator * `map_mul ideal.rel_norm`: multiplicativity of the relative ideal norm -/ open_locale big_operators open_locale non_zero_divisors section abs_norm namespace submodule variables {R M : Type*} [ring R] [add_comm_group M] [module R M] section /-- The cardinality of `(M ⧸ S)`, if `(M ⧸ S)` is finite, and `0` otherwise. This is used to define the absolute ideal norm `ideal.abs_norm`. -/ noncomputable def card_quot (S : submodule R M) : ℕ := add_subgroup.index S.to_add_subgroup @[simp] lemma card_quot_apply (S : submodule R M) [fintype (M ⧸ S)] : card_quot S = fintype.card (M ⧸ S) := add_subgroup.index_eq_card _ variables (R M) @[simp] lemma card_quot_bot [infinite M] : card_quot (⊥ : submodule R M) = 0 := add_subgroup.index_bot.trans nat.card_eq_zero_of_infinite @[simp] lemma card_quot_top : card_quot (⊤ : submodule R M) = 1 := add_subgroup.index_top variables {R M} @[simp] lemma card_quot_eq_one_iff {P : submodule R M} : card_quot P = 1 ↔ P = ⊤ := add_subgroup.index_eq_one.trans (by simp [set_like.ext_iff]) end end submodule section ring_of_integers variables {S : Type*} [comm_ring S] [is_domain S] open submodule /-- Multiplicity of the ideal norm, for coprime ideals. This is essentially just a repackaging of the Chinese Remainder Theorem. -/ lemma card_quot_mul_of_coprime [is_dedekind_domain S] [module.free ℤ S] [module.finite ℤ S] {I J : ideal S} (coprime : I ⊔ J = ⊤) : card_quot (I * J) = card_quot I * card_quot J := begin let b := module.free.choose_basis ℤ S, casesI is_empty_or_nonempty (module.free.choose_basis_index ℤ S), { haveI : subsingleton S := function.surjective.subsingleton b.repr.to_equiv.symm.surjective, nontriviality S, exfalso, exact not_nontrivial_iff_subsingleton.mpr ‹subsingleton S› ‹nontrivial S› }, haveI : infinite S := infinite.of_surjective _ b.repr.to_equiv.surjective, by_cases hI : I = ⊥, { rw [hI, submodule.bot_mul, card_quot_bot, zero_mul] }, by_cases hJ : J = ⊥, { rw [hJ, submodule.mul_bot, card_quot_bot, mul_zero] }, have hIJ : I * J ≠ ⊥ := mt ideal.mul_eq_bot.mp (not_or hI hJ), letI := classical.dec_eq (module.free.choose_basis_index ℤ S), letI := I.fintype_quotient_of_free_of_ne_bot hI, letI := J.fintype_quotient_of_free_of_ne_bot hJ, letI := (I * J).fintype_quotient_of_free_of_ne_bot hIJ, rw [card_quot_apply, card_quot_apply, card_quot_apply, fintype.card_eq.mpr ⟨(ideal.quotient_mul_equiv_quotient_prod I J coprime).to_equiv⟩, fintype.card_prod] end /-- If the `d` from `ideal.exists_mul_add_mem_pow_succ` is unique, up to `P`, then so are the `c`s, up to `P ^ (i + 1)`. Inspired by [Neukirch], proposition 6.1 -/ lemma ideal.mul_add_mem_pow_succ_inj (P : ideal S) {i : ℕ} (a d d' e e' : S) (a_mem : a ∈ P ^ i) (e_mem : e ∈ P ^ (i + 1)) (e'_mem : e' ∈ P ^ (i + 1)) (h : d - d' ∈ P) : (a * d + e) - (a * d' + e') ∈ P ^ (i + 1) := begin have : a * d - a * d' ∈ P ^ (i + 1), { convert ideal.mul_mem_mul a_mem h; simp [mul_sub, pow_succ, mul_comm] }, convert ideal.add_mem _ this (ideal.sub_mem _ e_mem e'_mem), ring, end section P_prime variables {P : ideal S} [P_prime : P.is_prime] (hP : P ≠ ⊥) include P_prime hP /-- If `a ∈ P^i \ P^(i+1)` and `c ∈ P^i`, then `a * d + e = c` for `e ∈ P^(i+1)`. `ideal.mul_add_mem_pow_succ_unique` shows the choice of `d` is unique, up to `P`. Inspired by [Neukirch], proposition 6.1 -/ lemma ideal.exists_mul_add_mem_pow_succ [is_dedekind_domain S] {i : ℕ} (a c : S) (a_mem : a ∈ P ^ i) (a_not_mem : a ∉ P ^ (i + 1)) (c_mem : c ∈ P ^ i) : ∃ (d : S) (e ∈ P ^ (i + 1)), a * d + e = c := begin suffices eq_b : P ^ i = ideal.span {a} ⊔ P ^ (i + 1), { rw eq_b at c_mem, simp only [mul_comm a], exact ideal.mem_span_singleton_sup.mp c_mem }, refine (ideal.eq_prime_pow_of_succ_lt_of_le hP (lt_of_le_of_ne le_sup_right _) (sup_le (ideal.span_le.mpr (set.singleton_subset_iff.mpr a_mem)) (ideal.pow_succ_lt_pow hP i).le)).symm, contrapose! a_not_mem with this, rw this, exact mem_sup.mpr ⟨a, mem_span_singleton_self a, 0, by simp, by simp⟩ end lemma ideal.mem_prime_of_mul_mem_pow [is_dedekind_domain S] {P : ideal S} [P_prime : P.is_prime] (hP : P ≠ ⊥) {i : ℕ} {a b : S} (a_not_mem : a ∉ P ^ (i + 1)) (ab_mem : a * b ∈ P ^ (i + 1)) : b ∈ P := begin simp only [← ideal.span_singleton_le_iff_mem, ← ideal.dvd_iff_le, pow_succ, ← ideal.span_singleton_mul_span_singleton] at a_not_mem ab_mem ⊢, exact (prime_pow_succ_dvd_mul (ideal.prime_of_is_prime hP P_prime) ab_mem).resolve_left a_not_mem end /-- The choice of `d` in `ideal.exists_mul_add_mem_pow_succ` is unique, up to `P`. Inspired by [Neukirch], proposition 6.1 -/ lemma ideal.mul_add_mem_pow_succ_unique [is_dedekind_domain S] {i : ℕ} (a d d' e e' : S) (a_not_mem : a ∉ P ^ (i + 1)) (e_mem : e ∈ P ^ (i + 1)) (e'_mem : e' ∈ P ^ (i + 1)) (h : (a * d + e) - (a * d' + e') ∈ P ^ (i + 1)) : d - d' ∈ P := begin have : e' - e ∈ P ^ (i + 1) := ideal.sub_mem _ e'_mem e_mem, have h' : a * (d - d') ∈ P ^ (i + 1), { convert ideal.add_mem _ h (ideal.sub_mem _ e'_mem e_mem), ring }, exact ideal.mem_prime_of_mul_mem_pow hP a_not_mem h' end /-- Multiplicity of the ideal norm, for powers of prime ideals. -/ lemma card_quot_pow_of_prime [is_dedekind_domain S] [module.finite ℤ S] [module.free ℤ S] {i : ℕ} : card_quot (P ^ i) = card_quot P ^ i := begin let b := module.free.choose_basis ℤ S, classical, induction i with i ih, { simp }, letI := ideal.fintype_quotient_of_free_of_ne_bot (P ^ i.succ) (pow_ne_zero _ hP), letI := ideal.fintype_quotient_of_free_of_ne_bot (P ^ i) (pow_ne_zero _ hP), letI := ideal.fintype_quotient_of_free_of_ne_bot P hP, have : P ^ (i + 1) < P ^ i := ideal.pow_succ_lt_pow hP i, suffices hquot : map (P ^ i.succ).mkq (P ^ i) ≃ S ⧸ P, { rw [pow_succ (card_quot P), ← ih, card_quot_apply (P ^ i.succ), ← card_quotient_mul_card_quotient (P ^ i) (P ^ i.succ) this.le, card_quot_apply (P ^ i), card_quot_apply P], congr' 1, rw fintype.card_eq, exact ⟨hquot⟩ }, choose a a_mem a_not_mem using set_like.exists_of_lt this, choose f g hg hf using λ c (hc : c ∈ P ^ i), ideal.exists_mul_add_mem_pow_succ hP a c a_mem a_not_mem hc, choose k hk_mem hk_eq using λ c' (hc' : c' ∈ (map (mkq (P ^ i.succ)) (P ^ i))), submodule.mem_map.mp hc', refine equiv.of_bijective (λ c', quotient.mk' (f (k c' c'.prop) (hk_mem c' c'.prop))) ⟨_, _⟩, { rintros ⟨c₁', hc₁'⟩ ⟨c₂', hc₂'⟩ h, rw [subtype.mk_eq_mk, ← hk_eq _ hc₁', ← hk_eq _ hc₂', mkq_apply, mkq_apply, submodule.quotient.eq, ← hf _ (hk_mem _ hc₁'), ← hf _ (hk_mem _ hc₂')], refine ideal.mul_add_mem_pow_succ_inj _ _ _ _ _ _ a_mem (hg _ _) (hg _ _) _, simpa only [submodule.quotient.mk'_eq_mk, submodule.quotient.mk'_eq_mk, submodule.quotient.eq] using h, }, { intros d', refine quotient.induction_on' d' (λ d, _), have hd' := mem_map.mpr ⟨a * d, ideal.mul_mem_right d _ a_mem, rfl⟩, refine ⟨⟨_, hd'⟩, _⟩, simp only [submodule.quotient.mk'_eq_mk, ideal.quotient.mk_eq_mk, ideal.quotient.eq, subtype.coe_mk], refine ideal.mul_add_mem_pow_succ_unique hP a _ _ _ _ a_not_mem (hg _ (hk_mem _ hd')) (zero_mem _) _, rw [hf, add_zero], exact (submodule.quotient.eq _).mp (hk_eq _ hd') } end end P_prime /-- Multiplicativity of the ideal norm in number rings. -/ theorem card_quot_mul [is_dedekind_domain S] [module.free ℤ S] [module.finite ℤ S] (I J : ideal S) : card_quot (I * J) = card_quot I * card_quot J := begin let b := module.free.choose_basis ℤ S, casesI is_empty_or_nonempty (module.free.choose_basis_index ℤ S), { haveI : subsingleton S := function.surjective.subsingleton b.repr.to_equiv.symm.surjective, nontriviality S, exfalso, exact not_nontrivial_iff_subsingleton.mpr ‹subsingleton S› ‹nontrivial S›, }, haveI : infinite S := infinite.of_surjective _ b.repr.to_equiv.surjective, exact unique_factorization_monoid.multiplicative_of_coprime card_quot I J (card_quot_bot _ _) (λ I J hI, by simp [ideal.is_unit_iff.mp hI, ideal.mul_top]) (λ I i hI, have ideal.is_prime I := ideal.is_prime_of_prime hI, by exactI card_quot_pow_of_prime hI.ne_zero) (λ I J hIJ, card_quot_mul_of_coprime (ideal.is_unit_iff.mp (hIJ _ (ideal.dvd_iff_le.mpr le_sup_left) (ideal.dvd_iff_le.mpr le_sup_right)))) end /-- The absolute norm of the ideal `I : ideal R` is the cardinality of the quotient `R ⧸ I`. -/ noncomputable def ideal.abs_norm [infinite S] [is_dedekind_domain S] [module.free ℤ S] [module.finite ℤ S] : ideal S →*₀ ℕ := { to_fun := submodule.card_quot, map_mul' := λ I J, by rw card_quot_mul, map_one' := by rw [ideal.one_eq_top, card_quot_top], map_zero' := by rw [ideal.zero_eq_bot, card_quot_bot] } namespace ideal variables [infinite S] [is_dedekind_domain S] [module.free ℤ S] [module.finite ℤ S] lemma abs_norm_apply (I : ideal S) : abs_norm I = card_quot I := rfl @[simp] lemma abs_norm_bot : abs_norm (⊥ : ideal S) = 0 := by rw [← ideal.zero_eq_bot, _root_.map_zero] @[simp] lemma abs_norm_top : abs_norm (⊤ : ideal S) = 1 := by rw [← ideal.one_eq_top, _root_.map_one] @[simp] lemma abs_norm_eq_one_iff {I : ideal S} : abs_norm I = 1 ↔ I = ⊤ := by rw [abs_norm_apply, card_quot_eq_one_iff] lemma abs_norm_ne_zero_iff (I : ideal S) : ideal.abs_norm I ≠ 0 ↔ finite (S ⧸ I) := ⟨λ h,nat.finite_of_card_ne_zero h, λ h, (@add_subgroup.finite_index_of_finite_quotient _ _ _ h).finite_index⟩ /-- Let `e : S ≃ I` be an additive isomorphism (therefore a `ℤ`-linear equiv). Then an alternative way to compute the norm of `I` is given by taking the determinant of `e`. See `nat_abs_det_basis_change` for a more familiar formulation of this result. -/ theorem nat_abs_det_equiv (I : ideal S) {E : Type*} [add_equiv_class E S I] (e : E) : int.nat_abs (linear_map.det ((submodule.subtype I).restrict_scalars ℤ ∘ₗ add_monoid_hom.to_int_linear_map (e : S →+ I))) = ideal.abs_norm I := begin -- `S ⧸ I` might be infinite if `I = ⊥`, but then `e` can't be an equiv. by_cases hI : I = ⊥, { unfreezingI { subst hI }, have : (1 : S) ≠ 0 := one_ne_zero, have : (1 : S) = 0 := equiv_like.injective e (subsingleton.elim _ _), contradiction }, let ι := module.free.choose_basis_index ℤ S, let b := module.free.choose_basis ℤ S, casesI is_empty_or_nonempty ι, { nontriviality S, exact (not_nontrivial_iff_subsingleton.mpr (function.surjective.subsingleton b.repr.to_equiv.symm.surjective) (by apply_instance)).elim }, -- Thus `(S ⧸ I)` is isomorphic to a product of `zmod`s, so it is a fintype. letI := ideal.fintype_quotient_of_free_of_ne_bot I hI, -- Use the Smith normal form to choose a nice basis for `I`. letI := classical.dec_eq ι, let a := I.smith_coeffs b hI, let b' := I.ring_basis b hI, let ab := I.self_basis b hI, have ab_eq := I.self_basis_def b hI, let e' : S ≃ₗ[ℤ] I := b'.equiv ab (equiv.refl _), let f : S →ₗ[ℤ] S := (I.subtype.restrict_scalars ℤ).comp (e' : S →ₗ[ℤ] I), let f_apply : ∀ x, f x = b'.equiv ab (equiv.refl _) x := λ x, rfl, suffices : (linear_map.det f).nat_abs = ideal.abs_norm I, { calc (linear_map.det ((submodule.subtype I).restrict_scalars ℤ ∘ₗ _)).nat_abs = (linear_map.det ((submodule.subtype I).restrict_scalars ℤ ∘ₗ (↑(add_equiv.to_int_linear_equiv ↑e) : S →ₗ[ℤ] I))).nat_abs : rfl ... = (linear_map.det ((submodule.subtype I).restrict_scalars ℤ ∘ₗ _)).nat_abs : int.nat_abs_eq_iff_associated.mpr (linear_map.associated_det_comp_equiv _ _ _) ... = abs_norm I : this }, have ha : ∀ i, f (b' i) = a i • b' i, { intro i, rw [f_apply, b'.equiv_apply, equiv.refl_apply, ab_eq] }, have mem_I_iff : ∀ x, x ∈ I ↔ ∀ i, a i ∣ b'.repr x i, { intro x, simp_rw [ab.mem_ideal_iff', ab_eq], have : ∀ (c : ι → ℤ) i, b'.repr (∑ (j : ι), c j • a j • b' j) i = a i * c i, { intros c i, simp only [← mul_action.mul_smul, b'.repr_sum_self, mul_comm] }, split, { rintro ⟨c, rfl⟩ i, exact ⟨c i, this c i⟩ }, { rintros ha, choose c hc using ha, exact ⟨c, b'.ext_elem (λ i, trans (hc i) (this c i).symm)⟩ } }, -- `det f` is equal to `∏ i, a i`, letI := classical.dec_eq ι, calc int.nat_abs (linear_map.det f) = int.nat_abs (linear_map.to_matrix b' b' f).det : by rw linear_map.det_to_matrix ... = int.nat_abs (matrix.diagonal a).det : _ ... = int.nat_abs (∏ i, a i) : by rw matrix.det_diagonal ... = ∏ i, int.nat_abs (a i) : map_prod int.nat_abs_hom a finset.univ ... = fintype.card (S ⧸ I) : _ ... = abs_norm I : (submodule.card_quot_apply _).symm, -- since `linear_map.to_matrix b' b' f` is the diagonal matrix with `a` along the diagonal. { congr, ext i j, rw [linear_map.to_matrix_apply, ha, linear_equiv.map_smul, basis.repr_self, finsupp.smul_single, smul_eq_mul, mul_one], by_cases h : i = j, { rw [h, matrix.diagonal_apply_eq, finsupp.single_eq_same] }, { rw [matrix.diagonal_apply_ne _ h, finsupp.single_eq_of_ne (ne.symm h)] } }, -- Now we map everything through the linear equiv `S ≃ₗ (ι → ℤ)`, -- which maps `(S ⧸ I)` to `Π i, zmod (a i).nat_abs`. haveI : ∀ i, ne_zero ((a i).nat_abs) := λ i, ⟨int.nat_abs_ne_zero_of_ne_zero (ideal.smith_coeffs_ne_zero b I hI i)⟩, simp_rw [fintype.card_eq.mpr ⟨(ideal.quotient_equiv_pi_zmod I b hI).to_equiv⟩, fintype.card_pi, zmod.card] , end /-- Let `b` be a basis for `S` over `ℤ` and `bI` a basis for `I` over `ℤ` of the same dimension. Then an alternative way to compute the norm of `I` is given by taking the determinant of `bI` over `b`. -/ theorem nat_abs_det_basis_change {ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι ℤ S) (I : ideal S) (bI : basis ι ℤ I) : (b.det (coe ∘ bI)).nat_abs = ideal.abs_norm I := begin let e := b.equiv bI (equiv.refl _), calc (b.det ((submodule.subtype I).restrict_scalars ℤ ∘ bI)).nat_abs = (linear_map.det ((submodule.subtype I).restrict_scalars ℤ ∘ₗ (e : S →ₗ[ℤ] I))).nat_abs : by rw basis.det_comp_basis ... = _ : nat_abs_det_equiv I e end @[simp] lemma abs_norm_span_singleton (r : S) : abs_norm (span ({r} : set S)) = (algebra.norm ℤ r).nat_abs := begin rw algebra.norm_apply, by_cases hr : r = 0, { simp only [hr, ideal.span_zero, algebra.coe_lmul_eq_mul, eq_self_iff_true, ideal.abs_norm_bot, linear_map.det_zero'', set.singleton_zero, _root_.map_zero, int.nat_abs_zero] }, letI := ideal.fintype_quotient_of_free_of_ne_bot (span {r}) (mt span_singleton_eq_bot.mp hr), let b := module.free.choose_basis ℤ S, rw [← nat_abs_det_equiv _ (b.equiv (basis_span_singleton b hr) (equiv.refl _))], swap, apply_instance, congr, refine b.ext (λ i, _), simp end lemma abs_norm_dvd_abs_norm_of_le {I J : ideal S} (h : J ≤ I) : I.abs_norm ∣ J.abs_norm := map_dvd abs_norm (dvd_iff_le.mpr h) lemma abs_norm_dvd_norm_of_mem {I : ideal S} {x : S} (h : x ∈ I) : ↑I.abs_norm ∣ algebra.norm ℤ x := begin rw [← int.dvd_nat_abs, ← abs_norm_span_singleton x, int.coe_nat_dvd], exact abs_norm_dvd_abs_norm_of_le ((span_singleton_le_iff_mem _).mpr h) end @[simp] lemma abs_norm_span_insert (r : S) (s : set S) : abs_norm (span (insert r s)) ∣ gcd (abs_norm (span s)) (algebra.norm ℤ r).nat_abs := (dvd_gcd_iff _ _ _).mpr ⟨abs_norm_dvd_abs_norm_of_le (span_mono (set.subset_insert _ _)), trans (abs_norm_dvd_abs_norm_of_le (span_mono (set.singleton_subset_iff.mpr (set.mem_insert _ _)))) (by rw abs_norm_span_singleton)⟩ lemma irreducible_of_irreducible_abs_norm {I : ideal S} (hI : irreducible I.abs_norm) : irreducible I := irreducible_iff.mpr ⟨λ h, hI.not_unit (by simpa only [ideal.is_unit_iff, nat.is_unit_iff, abs_norm_eq_one_iff] using h), by rintro a b rfl; simpa only [ideal.is_unit_iff, nat.is_unit_iff, abs_norm_eq_one_iff] using hI.is_unit_or_is_unit (_root_.map_mul abs_norm a b)⟩ lemma is_prime_of_irreducible_abs_norm {I : ideal S} (hI : irreducible I.abs_norm) : I.is_prime := is_prime_of_prime (unique_factorization_monoid.irreducible_iff_prime.mp (irreducible_of_irreducible_abs_norm hI)) lemma prime_of_irreducible_abs_norm_span {a : S} (ha : a ≠ 0) (hI : irreducible (ideal.span ({a} : set S)).abs_norm) : prime a := (ideal.span_singleton_prime ha).mp (is_prime_of_irreducible_abs_norm hI) lemma abs_norm_mem (I : ideal S) : ↑I.abs_norm ∈ I := by rw [abs_norm_apply, card_quot, ← ideal.quotient.eq_zero_iff_mem, map_nat_cast, quotient.index_eq_zero] lemma span_singleton_abs_norm_le (I : ideal S) : ideal.span { (ideal.abs_norm I : S) } ≤ I := by simp only [ideal.span_le, set.singleton_subset_iff, set_like.mem_coe, ideal.abs_norm_mem I] lemma finite_set_of_abs_norm_eq [char_zero S] {n : ℕ} (hn : 0 < n) : { I : ideal S | ideal.abs_norm I = n }.finite := begin let f := λ I : ideal S, ideal.map (ideal.quotient.mk (@ideal.span S _ {n})) I, refine @set.finite.of_finite_image _ _ _ f _ _, { suffices : finite (S ⧸ @ideal.span S _ {n}), { let g := (coe : ideal (S ⧸ @ideal.span S _ {n}) → set (S ⧸ @ideal.span S _ {n})), refine @set.finite.of_finite_image _ _ _ g _ (set_like.coe_injective.inj_on _), exact set.finite.subset (@set.finite_univ _ (@set.finite' _ this)) ( set.subset_univ _), }, rw [← abs_norm_ne_zero_iff, abs_norm_span_singleton], simpa only [ne.def, int.nat_abs_eq_zero, algebra.norm_eq_zero_iff, nat.cast_eq_zero] using ne_of_gt hn, }, { intros I hI J hJ h, rw [← comap_map_mk (span_singleton_abs_norm_le I), ← hI.symm, ← comap_map_mk (span_singleton_abs_norm_le J), ← hJ.symm], exact congr_arg (ideal.comap (ideal.quotient.mk (@ideal.span S _ {n}))) h, }, end end ideal end ring_of_integers end abs_norm section span_norm namespace ideal open submodule variables (R : Type*) [comm_ring R] {S : Type*} [comm_ring S] [algebra R S] /-- `ideal.span_norm R (I : ideal S)` is the ideal generated by mapping `algebra.norm R` over `I`. See also `ideal.rel_norm`. -/ def span_norm (I : ideal S) : ideal R := ideal.span (algebra.norm R '' (I : set S)) @[simp] lemma span_norm_bot [nontrivial S] [module.free R S] [module.finite R S] : span_norm R (⊥ : ideal S) = ⊥ := span_eq_bot.mpr (λ x hx, by simpa using hx) variables {R} @[simp] lemma span_norm_eq_bot_iff [is_domain R] [is_domain S] [module.free R S] [module.finite R S] {I : ideal S} : span_norm R I = ⊥ ↔ I = ⊥ := begin simp only [span_norm, ideal.span_eq_bot, set.mem_image, set_like.mem_coe, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, algebra.norm_eq_zero_iff_of_basis (module.free.choose_basis R S), @eq_bot_iff _ _ _ I, set_like.le_def], refl end variables (R) lemma norm_mem_span_norm {I : ideal S} (x : S) (hx : x ∈ I) : algebra.norm R x ∈ I.span_norm R := subset_span (set.mem_image_of_mem _ hx) @[simp] lemma span_norm_singleton {r : S} : span_norm R (span ({r} : set S)) = span {algebra.norm R r} := le_antisymm (span_le.mpr (λ x hx, mem_span_singleton.mpr begin obtain ⟨x, hx', rfl⟩ := (set.mem_image _ _ _).mp hx, exact map_dvd _ (mem_span_singleton.mp hx') end)) ((span_singleton_le_iff_mem _).mpr (norm_mem_span_norm _ _ (mem_span_singleton_self _))) @[simp] lemma span_norm_top : span_norm R (⊤ : ideal S) = ⊤ := by simp [← ideal.span_singleton_one] lemma map_span_norm (I : ideal S) {T : Type*} [comm_ring T] (f : R →+* T) : map f (span_norm R I) = span ((f ∘ algebra.norm R) '' (I : set S)) := by rw [span_norm, map_span, set.image_image] @[mono] lemma span_norm_mono {I J : ideal S} (h : I ≤ J) : span_norm R I ≤ span_norm R J := ideal.span_mono (set.monotone_image h) lemma span_norm_localization (I : ideal S) [module.finite R S] [module.free R S] (M : submonoid R) {Rₘ : Type*} (Sₘ : Type*) [comm_ring Rₘ] [algebra R Rₘ] [comm_ring Sₘ] [algebra S Sₘ] [algebra Rₘ Sₘ] [algebra R Sₘ] [is_scalar_tower R Rₘ Sₘ] [is_scalar_tower R S Sₘ] [is_localization M Rₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] : span_norm Rₘ (I.map (algebra_map S Sₘ)) = (span_norm R I).map (algebra_map R Rₘ) := begin casesI h : subsingleton_or_nontrivial R, { haveI := is_localization.unique R Rₘ M, simp }, let b := module.free.choose_basis R S, rw map_span_norm, refine span_eq_span (set.image_subset_iff.mpr _) (set.image_subset_iff.mpr _), { rintros a' ha', simp only [set.mem_preimage, submodule_span_eq, ← map_span_norm, set_like.mem_coe, is_localization.mem_map_algebra_map_iff (algebra.algebra_map_submonoid S M) Sₘ, is_localization.mem_map_algebra_map_iff M Rₘ, prod.exists] at ⊢ ha', obtain ⟨⟨a, ha⟩, ⟨_, ⟨s, hs, rfl⟩⟩, has⟩ := ha', refine ⟨⟨algebra.norm R a, norm_mem_span_norm _ _ ha⟩, ⟨s ^ fintype.card (module.free.choose_basis_index R S), pow_mem hs _⟩, _⟩, swap, simp only [submodule.coe_mk, subtype.coe_mk, map_pow] at ⊢ has, apply_fun algebra.norm Rₘ at has, rwa [_root_.map_mul, ← is_scalar_tower.algebra_map_apply, is_scalar_tower.algebra_map_apply R Rₘ, algebra.norm_algebra_map_of_basis (b.localization_localization Rₘ M Sₘ), algebra.norm_localization R M a] at has, all_goals { apply_instance } }, { intros a ha, rw [set.mem_preimage, function.comp_app, ← algebra.norm_localization R M a], exact subset_span (set.mem_image_of_mem _ (mem_map_of_mem _ ha)), all_goals { apply_instance } }, end lemma span_norm_mul_span_norm_le (I J : ideal S) : span_norm R I * span_norm R J ≤ span_norm R (I * J) := begin rw [span_norm, span_norm, span_norm, ideal.span_mul_span', ← set.image_mul], refine ideal.span_mono (set.monotone_image _), rintros _ ⟨x, y, hxI, hyJ, rfl⟩, exact ideal.mul_mem_mul hxI hyJ end /-- This condition `eq_bot_or_top` is equivalent to being a field. However, `span_norm_mul_of_field` is harder to apply since we'd need to upgrade a `comm_ring R` instance to a `field R` instance. -/ lemma span_norm_mul_of_bot_or_top [is_domain R] [is_domain S] [module.free R S] [module.finite R S] (eq_bot_or_top : ∀ I : ideal R, I = ⊥ ∨ I = ⊤) (I J : ideal S) : span_norm R (I * J) = span_norm R I * span_norm R J := begin refine le_antisymm _ (span_norm_mul_span_norm_le _ _ _), cases eq_bot_or_top (span_norm R I) with hI hI, { rw [hI, span_norm_eq_bot_iff.mp hI, bot_mul, span_norm_bot], exact bot_le }, rw [hI, ideal.top_mul], cases eq_bot_or_top (span_norm R J) with hJ hJ, { rw [hJ, span_norm_eq_bot_iff.mp hJ, mul_bot, span_norm_bot], exact bot_le }, rw hJ, exact le_top end @[simp] lemma span_norm_mul_of_field {K : Type*} [field K] [algebra K S] [is_domain S] [module.finite K S] (I J : ideal S) : span_norm K (I * J) = span_norm K I * span_norm K J := span_norm_mul_of_bot_or_top K eq_bot_or_top I J variables [is_domain R] [is_domain S] [is_dedekind_domain R] [is_dedekind_domain S] variables [module.finite R S] [module.free R S] /-- Multiplicativity of `ideal.span_norm`. simp-normal form is `map_mul (ideal.rel_norm R)`. -/ lemma span_norm_mul (I J : ideal S) : span_norm R (I * J) = span_norm R I * span_norm R J := begin nontriviality R, casesI subsingleton_or_nontrivial S, { have : ∀ I : ideal S, I = ⊤ := λ I, subsingleton.elim I ⊤, simp [this I, this J, this (I * J)] }, refine eq_of_localization_maximal _, unfreezingI { intros P hP }, by_cases hP0 : P = ⊥, { unfreezingI { subst hP0 }, rw span_norm_mul_of_bot_or_top, intros I, refine or_iff_not_imp_right.mpr (λ hI, _), exact (hP.eq_of_le hI bot_le).symm }, let P' := algebra.algebra_map_submonoid S P.prime_compl, letI : algebra (localization.at_prime P) (localization P') := localization_algebra P.prime_compl S, haveI : is_scalar_tower R (localization.at_prime P) (localization P') := is_scalar_tower.of_algebra_map_eq (λ x, (is_localization.map_eq _ _).symm), have h : P' ≤ S⁰ := map_le_non_zero_divisors_of_injective _ (no_zero_smul_divisors.algebra_map_injective _ _) P.prime_compl_le_non_zero_divisors, haveI : is_domain (localization P') := is_localization.is_domain_localization h, haveI : is_dedekind_domain (localization P') := is_localization.is_dedekind_domain S h _, letI := classical.dec_eq (ideal (localization P')), haveI : is_principal_ideal_ring (localization P') := is_dedekind_domain.is_principal_ideal_ring_localization_over_prime S P hP0, rw [ideal.map_mul, ← span_norm_localization R I P.prime_compl (localization P'), ← span_norm_localization R J P.prime_compl (localization P'), ← span_norm_localization R (I * J) P.prime_compl (localization P'), ideal.map_mul, ← (I.map _).span_singleton_generator, ← (J.map _).span_singleton_generator, span_singleton_mul_span_singleton, span_norm_singleton, span_norm_singleton, span_norm_singleton, span_singleton_mul_span_singleton, _root_.map_mul], repeat { apply_instance }, repeat { assumption }, end /-- The relative norm `ideal.rel_norm R (I : ideal S)`, where `R` and `S` are Dedekind domains, and `S` is an extension of `R` that is finite and free as a module. -/ def rel_norm : ideal S →*₀ ideal R := { to_fun := span_norm R, map_zero' := span_norm_bot R, map_one' := by rw [one_eq_top, span_norm_top R, one_eq_top], map_mul' := span_norm_mul R } lemma rel_norm_apply (I : ideal S) : rel_norm R I = span (algebra.norm R '' (I : set S) : set R) := rfl @[simp] lemma span_norm_eq (I : ideal S) : span_norm R I = rel_norm R I := rfl @[simp] lemma rel_norm_bot : rel_norm R (⊥ : ideal S) = ⊥ := by simpa only [zero_eq_bot] using map_zero (rel_norm R : ideal S →*₀ _) @[simp] lemma rel_norm_top : rel_norm R (⊤ : ideal S) = ⊤ := by simpa only [one_eq_top] using map_one (rel_norm R : ideal S →*₀ _) variables {R} @[simp] lemma rel_norm_eq_bot_iff {I : ideal S} : rel_norm R I = ⊥ ↔ I = ⊥ := span_norm_eq_bot_iff variables (R) lemma norm_mem_rel_norm (I : ideal S) {x : S} (hx : x ∈ I) : algebra.norm R x ∈ rel_norm R I := norm_mem_span_norm R x hx @[simp] lemma rel_norm_singleton (r : S) : rel_norm R (span ({r} : set S)) = span {algebra.norm R r} := span_norm_singleton R lemma map_rel_norm (I : ideal S) {T : Type*} [comm_ring T] (f : R →+* T) : map f (rel_norm R I) = span ((f ∘ algebra.norm R) '' (I : set S)) := map_span_norm R I f @[mono] lemma rel_norm_mono {I J : ideal S} (h : I ≤ J) : rel_norm R I ≤ rel_norm R J := span_norm_mono R h end ideal end span_norm
f1d05a6041430868f34316ffb110c279da99da9d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/openExport.lean
e55c3b542a2b4dc786a403c50ec9ae769afd661d
[ "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
452
lean
def A.x := 10 namespace B export A (x) def y := 20 #check x -- works #check y -- works end B #check A.x -- works #check B.x -- works, but fails in old frontend and Lean3 :) #check B.y -- works #check x -- fails as expected #check y -- fails as expected open B #check x -- works #check y -- works namespace B #check x -- works #check y -- works def z := 30 #check z -- works end B #check z -- works, but fails in old frontend and Lean3 :)
9c7dccf3cf3447cf4aa54f7f223275db2c867225
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/quaternion.lean
96242430025aedecc6409dda5995ca41c37a4c09
[ "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
22,266
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import tactic.ring_exp import algebra.algebra.basic import algebra.opposites import data.equiv.ring /-! # Quaternions In this file we define quaternions `ℍ[R]` over a commutative ring `R`, and define some algebraic structures on `ℍ[R]`. ## Main definitions * `quaternion_algebra R a b`, `ℍ[R, a, b]` : [quaternion algebra](https://en.wikipedia.org/wiki/Quaternion_algebra) with coefficients `a`, `b` * `quaternion R`, `ℍ[R]` : the space of quaternions, a.k.a. `quaternion_algebra R (-1) (-1)`; * `quaternion.norm_sq` : square of the norm of a quaternion; * `quaternion.conj` : conjugate of a quaternion; We also define the following algebraic structures on `ℍ[R]`: * `ring ℍ[R, a, b]` and `algebra R ℍ[R, a, b]` : for any commutative ring `R`; * `ring ℍ[R]` and `algebra R ℍ[R]` : for any commutative ring `R`; * `domain ℍ[R]` : for a linear ordered commutative ring `R`; * `division_algebra ℍ[R]` : for a linear ordered field `R`. ## Notation The following notation is available with `open_locale quaternion`. * `ℍ[R, c₁, c₂]` : `quaternion_algebra R c₁ c₂` * `ℍ[R]` : quaternions over `R`. ## Implementation notes We define quaternions over any ring `R`, not just `ℝ` to be able to deal with, e.g., integer or rational quaternions without using real numbers. In particular, all definitions in this file are computable. ## Tags quaternion -/ /-- Quaternion algebra over a type with fixed coefficients $a=i^2$ and $b=j^2$. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ @[nolint unused_arguments, ext] structure quaternion_algebra (R : Type*) (a b : R) := mk {} :: (re : R) (im_i : R) (im_j : R) (im_k : R) localized "notation `ℍ[` R`,` a`,` b `]` := quaternion_algebra R a b" in quaternion namespace quaternion_algebra @[simp] lemma mk.eta {R : Type*} {c₁ c₂} : ∀ a : ℍ[R, c₁, c₂], mk a.1 a.2 a.3 a.4 = a | ⟨a₁, a₂, a₃, a₄⟩ := rfl variables {R : Type*} [comm_ring R] {c₁ c₂ : R} (r x y z : R) (a b c : ℍ[R, c₁, c₂]) instance : has_coe_t R (ℍ[R, c₁, c₂]) := ⟨λ x, ⟨x, 0, 0, 0⟩⟩ @[simp] lemma coe_re : (x : ℍ[R, c₁, c₂]).re = x := rfl @[simp] lemma coe_im_i : (x : ℍ[R, c₁, c₂]).im_i = 0 := rfl @[simp] lemma coe_im_j : (x : ℍ[R, c₁, c₂]).im_j = 0 := rfl @[simp] lemma coe_im_k : (x : ℍ[R, c₁, c₂]).im_k = 0 := rfl lemma coe_injective : function.injective (coe : R → ℍ[R, c₁, c₂]) := λ x y h, congr_arg re h @[simp] lemma coe_inj {x y : R} : (x : ℍ[R, c₁, c₂]) = y ↔ x = y := coe_injective.eq_iff @[simps] instance : has_zero ℍ[R, c₁, c₂] := ⟨⟨0, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R, c₁, c₂]) = 0 := rfl instance : inhabited ℍ[R, c₁, c₂] := ⟨0⟩ @[simps] instance : has_one ℍ[R, c₁, c₂] := ⟨⟨1, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R, c₁, c₂]) = 1 := rfl @[simps] instance : has_add ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4⟩⟩ @[simp] lemma mk_add_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) + mk b₁ b₂ b₃ b₄ = mk (a₁ + b₁) (a₂ + b₂) (a₃ + b₃) (a₄ + b₄) := rfl @[simps] instance : has_neg ℍ[R, c₁, c₂] := ⟨λ a, ⟨-a.1, -a.2, -a.3, -a.4⟩⟩ @[simp] lemma neg_mk (a₁ a₂ a₃ a₄ : R) : -(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨-a₁, -a₂, -a₃, -a₄⟩ := rfl @[simps] instance : has_sub ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 - b.1, a.2 - b.2, a.3 - b.3, a.4 - b.4⟩⟩ @[simp] lemma mk_sub_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) - mk b₁ b₂ b₃ b₄ = mk (a₁ - b₁) (a₂ - b₂) (a₃ - b₃) (a₄ - b₄) := rfl /-- Multiplication is given by * `1 * x = x * 1 = x`; * `i * i = c₁`; * `j * j = c₂`; * `i * j = k`, `j * i = -k`; * `k * k = -c₁ * c₂`; * `i * k = c₁ * j`, `k * i = `-c₁ * j`; * `j * k = -c₂ * i`, `k * j = c₂ * i`. -/ @[simps] instance : has_mul ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 * b.1 + c₁ * a.2 * b.2 + c₂ * a.3 * b.3 - c₁ * c₂ * a.4 * b.4, a.1 * b.2 + a.2 * b.1 - c₂ * a.3 * b.4 + c₂ * a.4 * b.3, a.1 * b.3 + c₁ * a.2 * b.4 + a.3 * b.1 - c₁ * a.4 * b.2, a.1 * b.4 + a.2 * b.3 - a.3 * b.2 + a.4 * b.1⟩⟩ @[simp] lemma mk_mul_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) * mk b₁ b₂ b₃ b₄ = ⟨a₁ * b₁ + c₁ * a₂ * b₂ + c₂ * a₃ * b₃ - c₁ * c₂ * a₄ * b₄, a₁ * b₂ + a₂ * b₁ - c₂ * a₃ * b₄ + c₂ * a₄ * b₃, a₁ * b₃ + c₁ * a₂ * b₄ + a₃ * b₁ - c₁ * a₄ * b₂, a₁ * b₄ + a₂ * b₃ - a₃ * b₂ + a₄ * b₁⟩ := rfl instance : ring ℍ[R, c₁, c₂] := by refine_struct { add := (+), zero := (0 : ℍ[R, c₁, c₂]), neg := has_neg.neg, sub := has_sub.sub, mul := (*), one := 1, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ }; intros; try { refl }; ext; simp; ring_exp instance : algebra R ℍ[R, c₁, c₂] := { smul := λ r a, ⟨r * a.1, r * a.2, r * a.3, r * a.4⟩, to_fun := coe, map_one' := rfl, map_zero' := rfl, map_mul' := λ x y, by ext; simp, map_add' := λ x y, by ext; simp, smul_def' := λ r x, by ext; simp, commutes' := λ r x, by ext; simp [mul_comm] } @[simp] lemma smul_re : (r • a).re = r • a.re := rfl @[simp] lemma smul_im_i : (r • a).im_i = r • a.im_i := rfl @[simp] lemma smul_im_j : (r • a).im_j = r • a.im_j := rfl @[simp] lemma smul_im_k : (r • a).im_k = r • a.im_k := rfl @[simp] lemma smul_mk (re im_i im_j im_k : R) : r • (⟨re, im_i, im_j, im_k⟩ : ℍ[R, c₁, c₂]) = ⟨r • re, r • im_i, r • im_j, r • im_k⟩ := rfl lemma algebra_map_eq (r : R) : algebra_map R ℍ[R,c₁,c₂] r = ⟨r, 0, 0, 0⟩ := rfl section variables (R c₁ c₂) /-- `quaternion_algebra.re` as a `linear_map`-/ @[simps] def re_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := re, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_i` as a `linear_map`-/ @[simps] def im_i_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_i, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_j` as a `linear_map`-/ @[simps] def im_j_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_j, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_k` as a `linear_map`-/ @[simps] def im_k_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_k, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } end @[norm_cast, simp] lemma coe_add : ((x + y : R) : ℍ[R, c₁, c₂]) = x + y := (algebra_map R ℍ[R, c₁, c₂]).map_add x y @[norm_cast, simp] lemma coe_sub : ((x - y : R) : ℍ[R, c₁, c₂]) = x - y := (algebra_map R ℍ[R, c₁, c₂]).map_sub x y @[norm_cast, simp] lemma coe_neg : ((-x : R) : ℍ[R, c₁, c₂]) = -x := (algebra_map R ℍ[R, c₁, c₂]).map_neg x @[norm_cast, simp] lemma coe_mul : ((x * y : R) : ℍ[R, c₁, c₂]) = x * y := (algebra_map R ℍ[R, c₁, c₂]).map_mul x y lemma coe_commutes : ↑r * a = a * r := algebra.commutes r a lemma coe_commute : commute ↑r a := coe_commutes r a lemma coe_mul_eq_smul : ↑r * a = r • a := (algebra.smul_def r a).symm lemma mul_coe_eq_smul : a * r = r • a := by rw [← coe_commutes, coe_mul_eq_smul] @[norm_cast, simp] lemma coe_algebra_map : ⇑(algebra_map R ℍ[R, c₁, c₂]) = coe := rfl lemma smul_coe : x • (y : ℍ[R, c₁, c₂]) = ↑(x * y) := by rw [coe_mul, coe_mul_eq_smul] /-- Quaternion conjugate. -/ def conj : ℍ[R, c₁, c₂] ≃ₗ[R] ℍ[R, c₁, c₂] := linear_equiv.of_involutive { to_fun := λ a, ⟨a.1, -a.2, -a.3, -a.4⟩, map_add' := λ a b, by ext; simp [neg_add], map_smul' := λ r a, by ext; simp } $ λ a, by simp @[simp] lemma re_conj : (conj a).re = a.re := rfl @[simp] lemma im_i_conj : (conj a).im_i = - a.im_i := rfl @[simp] lemma im_j_conj : (conj a).im_j = - a.im_j := rfl @[simp] lemma im_k_conj : (conj a).im_k = - a.im_k := rfl @[simp] lemma conj_mk (a₁ a₂ a₃ a₄ : R) : conj (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨a₁, -a₂, -a₃, -a₄⟩ := rfl @[simp] lemma conj_conj : a.conj.conj = a := ext _ _ rfl (neg_neg _) (neg_neg _) (neg_neg _) lemma conj_add : (a + b).conj = a.conj + b.conj := conj.map_add a b @[simp] lemma conj_mul : (a * b).conj = b.conj * a.conj := by ext; simp; ring_exp lemma conj_conj_mul : (a.conj * b).conj = b.conj * a := by rw [conj_mul, conj_conj] lemma conj_mul_conj : (a * b.conj).conj = b * a.conj := by rw [conj_mul, conj_conj] lemma self_add_conj' : a + a.conj = ↑(2 * a.re) := by ext; simp [two_mul] lemma self_add_conj : a + a.conj = 2 * a.re := by simp only [self_add_conj', two_mul, coe_add] lemma conj_add_self' : a.conj + a = ↑(2 * a.re) := by rw [add_comm, self_add_conj'] lemma conj_add_self : a.conj + a = 2 * a.re := by rw [add_comm, self_add_conj] lemma conj_eq_two_re_sub : a.conj = ↑(2 * a.re) - a := eq_sub_iff_add_eq.2 a.conj_add_self' lemma commute_conj_self : commute a.conj a := begin rw [a.conj_eq_two_re_sub], exact (coe_commute (2 * a.re) a).sub_left (commute.refl a) end lemma commute_self_conj : commute a a.conj := a.commute_conj_self.symm lemma commute_conj_conj {a b : ℍ[R, c₁, c₂]} (h : commute a b) : commute a.conj b.conj := calc a.conj * b.conj = (b * a).conj : (conj_mul b a).symm ... = (a * b).conj : by rw h.eq ... = b.conj * a.conj : conj_mul a b @[simp] lemma conj_coe : conj (x : ℍ[R, c₁, c₂]) = x := by ext; simp lemma conj_smul : conj (r • a) = r • conj a := conj.map_smul r a @[simp] lemma conj_one : conj (1 : ℍ[R, c₁, c₂]) = 1 := conj_coe 1 lemma eq_re_of_eq_coe {a : ℍ[R, c₁, c₂]} {x : R} (h : a = x) : a = a.re := by rw [h, coe_re] lemma eq_re_iff_mem_range_coe {a : ℍ[R, c₁, c₂]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R, c₁, c₂]) := ⟨λ h, ⟨a.re, h.symm⟩, λ ⟨x, h⟩, eq_re_of_eq_coe h.symm⟩ @[simp] lemma conj_fixed {R : Type*} [comm_ring R] [no_zero_divisors R] [char_zero R] {c₁ c₂ : R} {a : ℍ[R, c₁, c₂]} : conj a = a ↔ a = a.re := by simp [ext_iff, neg_eq_iff_add_eq_zero, add_self_eq_zero] -- Can't use `rw ← conj_fixed` in the proof without additional assumptions lemma conj_mul_eq_coe : conj a * a = (conj a * a).re := by ext; simp; ring_exp lemma mul_conj_eq_coe : a * conj a = (a * conj a).re := by { rw a.commute_self_conj.eq, exact a.conj_mul_eq_coe } lemma conj_zero : conj (0 : ℍ[R, c₁, c₂]) = 0 := conj.map_zero lemma conj_neg : (-a).conj = -a.conj := (conj : ℍ[R, c₁, c₂] ≃ₗ[R] _).map_neg a lemma conj_sub : (a - b).conj = a.conj - b.conj := (conj : ℍ[R, c₁, c₂] ≃ₗ[R] _).map_sub a b instance : star_ring ℍ[R, c₁, c₂] := { star := conj, star_involutive := conj_conj, star_add := conj_add, star_mul := conj_mul } @[simp] lemma star_def (a : ℍ[R, c₁, c₂]) : star a = conj a := rfl open opposite /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def conj_ae : ℍ[R, c₁, c₂] ≃ₐ[R] (ℍ[R, c₁, c₂]ᵒᵖ) := { to_fun := op ∘ conj, inv_fun := conj ∘ unop, map_mul' := λ x y, by simp, commutes' := λ r, by simp, .. conj.to_add_equiv.trans op_add_equiv } @[simp] lemma coe_conj_ae : ⇑(conj_ae : ℍ[R, c₁, c₂] ≃ₐ[R] _) = op ∘ conj := rfl end quaternion_algebra /-- Space of quaternions over a type. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ def quaternion (R : Type*) [has_one R] [has_neg R] := quaternion_algebra R (-1) (-1) localized "notation `ℍ[` R `]` := quaternion R" in quaternion namespace quaternion variables {R : Type*} [comm_ring R] (r x y z : R) (a b c : ℍ[R]) export quaternion_algebra (re im_i im_j im_k) instance : has_coe_t R ℍ[R] := quaternion_algebra.has_coe_t instance : ring ℍ[R] := quaternion_algebra.ring instance : inhabited ℍ[R] := quaternion_algebra.inhabited instance : algebra R ℍ[R] := quaternion_algebra.algebra instance : star_ring ℍ[R] := quaternion_algebra.star_ring @[ext] lemma ext : a.re = b.re → a.im_i = b.im_i → a.im_j = b.im_j → a.im_k = b.im_k → a = b := quaternion_algebra.ext a b lemma ext_iff {a b : ℍ[R]} : a = b ↔ a.re = b.re ∧ a.im_i = b.im_i ∧ a.im_j = b.im_j ∧ a.im_k = b.im_k := quaternion_algebra.ext_iff a b @[simp, norm_cast] lemma coe_re : (x : ℍ[R]).re = x := rfl @[simp, norm_cast] lemma coe_im_i : (x : ℍ[R]).im_i = 0 := rfl @[simp, norm_cast] lemma coe_im_j : (x : ℍ[R]).im_j = 0 := rfl @[simp, norm_cast] lemma coe_im_k : (x : ℍ[R]).im_k = 0 := rfl @[simp] lemma zero_re : (0 : ℍ[R]).re = 0 := rfl @[simp] lemma zero_im_i : (0 : ℍ[R]).im_i = 0 := rfl @[simp] lemma zero_im_j : (0 : ℍ[R]).im_j = 0 := rfl @[simp] lemma zero_im_k : (0 : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R]) = 0 := rfl @[simp] lemma one_re : (1 : ℍ[R]).re = 1 := rfl @[simp] lemma one_im_i : (1 : ℍ[R]).im_i = 0 := rfl @[simp] lemma one_im_j : (1 : ℍ[R]).im_j = 0 := rfl @[simp] lemma one_im_k : (1 : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R]) = 1 := rfl @[simp] lemma add_re : (a + b).re = a.re + b.re := rfl @[simp] lemma add_im_i : (a + b).im_i = a.im_i + b.im_i := rfl @[simp] lemma add_im_j : (a + b).im_j = a.im_j + b.im_j := rfl @[simp] lemma add_im_k : (a + b).im_k = a.im_k + b.im_k := rfl @[simp, norm_cast] lemma coe_add : ((x + y : R) : ℍ[R]) = x + y := quaternion_algebra.coe_add x y @[simp] lemma neg_re : (-a).re = -a.re := rfl @[simp] lemma neg_im_i : (-a).im_i = -a.im_i := rfl @[simp] lemma neg_im_j : (-a).im_j = -a.im_j := rfl @[simp] lemma neg_im_k : (-a).im_k = -a.im_k := rfl @[simp, norm_cast] lemma coe_neg : ((-x : R) : ℍ[R]) = -x := quaternion_algebra.coe_neg x @[simp] lemma sub_re : (a - b).re = a.re - b.re := rfl @[simp] lemma sub_im_i : (a - b).im_i = a.im_i - b.im_i := rfl @[simp] lemma sub_im_j : (a - b).im_j = a.im_j - b.im_j := rfl @[simp] lemma sub_im_k : (a - b).im_k = a.im_k - b.im_k := rfl @[simp, norm_cast] lemma coe_sub : ((x - y : R) : ℍ[R]) = x - y := quaternion_algebra.coe_sub x y @[simp] lemma mul_re : (a * b).re = a.re * b.re - a.im_i * b.im_i - a.im_j * b.im_j - a.im_k * b.im_k := (quaternion_algebra.has_mul_mul_re a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_i : (a * b).im_i = a.re * b.im_i + a.im_i * b.re + a.im_j * b.im_k - a.im_k * b.im_j := (quaternion_algebra.has_mul_mul_im_i a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_j : (a * b).im_j = a.re * b.im_j - a.im_i * b.im_k + a.im_j * b.re + a.im_k * b.im_i := (quaternion_algebra.has_mul_mul_im_j a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_k : (a * b).im_k = a.re * b.im_k + a.im_i * b.im_j - a.im_j * b.im_i + a.im_k * b.re := (quaternion_algebra.has_mul_mul_im_k a b).trans $ by simp only [one_mul, ← neg_mul_eq_neg_mul, sub_eq_add_neg, neg_neg] @[simp, norm_cast] lemma coe_mul : ((x * y : R) : ℍ[R]) = x * y := quaternion_algebra.coe_mul x y lemma coe_injective : function.injective (coe : R → ℍ[R]) := quaternion_algebra.coe_injective @[simp] lemma coe_inj {x y : R} : (x : ℍ[R]) = y ↔ x = y := coe_injective.eq_iff @[simp] lemma smul_re : (r • a).re = r • a.re := rfl @[simp] lemma smul_im_i : (r • a).im_i = r • a.im_i := rfl @[simp] lemma smul_im_j : (r • a).im_j = r • a.im_j := rfl @[simp] lemma smul_im_k : (r • a).im_k = r • a.im_k := rfl lemma coe_commutes : ↑r * a = a * r := quaternion_algebra.coe_commutes r a lemma coe_commute : commute ↑r a := quaternion_algebra.coe_commute r a lemma coe_mul_eq_smul : ↑r * a = r • a := quaternion_algebra.coe_mul_eq_smul r a lemma mul_coe_eq_smul : a * r = r • a := quaternion_algebra.mul_coe_eq_smul r a @[simp] lemma algebra_map_def : ⇑(algebra_map R ℍ[R]) = coe := rfl lemma smul_coe : x • (y : ℍ[R]) = ↑(x * y) := quaternion_algebra.smul_coe x y /-- Quaternion conjugate. -/ def conj : ℍ[R] ≃ₗ[R] ℍ[R] := quaternion_algebra.conj @[simp] lemma conj_re : a.conj.re = a.re := rfl @[simp] lemma conj_im_i : a.conj.im_i = - a.im_i := rfl @[simp] lemma conj_im_j : a.conj.im_j = - a.im_j := rfl @[simp] lemma conj_im_k : a.conj.im_k = - a.im_k := rfl @[simp] lemma conj_conj : a.conj.conj = a := a.conj_conj @[simp] lemma conj_add : (a + b).conj = a.conj + b.conj := a.conj_add b @[simp] lemma conj_mul : (a * b).conj = b.conj * a.conj := a.conj_mul b lemma conj_conj_mul : (a.conj * b).conj = b.conj * a := a.conj_conj_mul b lemma conj_mul_conj : (a * b.conj).conj = b * a.conj := a.conj_mul_conj b lemma self_add_conj' : a + a.conj = ↑(2 * a.re) := a.self_add_conj' lemma self_add_conj : a + a.conj = 2 * a.re := a.self_add_conj lemma conj_add_self' : a.conj + a = ↑(2 * a.re) := a.conj_add_self' lemma conj_add_self : a.conj + a = 2 * a.re := a.conj_add_self lemma conj_eq_two_re_sub : a.conj = ↑(2 * a.re) - a := a.conj_eq_two_re_sub lemma commute_conj_self : commute a.conj a := a.commute_conj_self lemma commute_self_conj : commute a a.conj := a.commute_self_conj lemma commute_conj_conj {a b : ℍ[R]} (h : commute a b) : commute a.conj b.conj := quaternion_algebra.commute_conj_conj h alias commute_conj_conj ← commute.quaternion_conj @[simp] lemma conj_coe : conj (x : ℍ[R]) = x := quaternion_algebra.conj_coe x @[simp] lemma conj_smul : conj (r • a) = r • conj a := a.conj_smul r @[simp] lemma conj_one : conj (1 : ℍ[R]) = 1 := conj_coe 1 lemma eq_re_of_eq_coe {a : ℍ[R]} {x : R} (h : a = x) : a = a.re := quaternion_algebra.eq_re_of_eq_coe h lemma eq_re_iff_mem_range_coe {a : ℍ[R]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R]) := quaternion_algebra.eq_re_iff_mem_range_coe @[simp] lemma conj_fixed {R : Type*} [comm_ring R] [no_zero_divisors R] [char_zero R] {a : ℍ[R]} : conj a = a ↔ a = a.re := quaternion_algebra.conj_fixed lemma conj_mul_eq_coe : conj a * a = (conj a * a).re := a.conj_mul_eq_coe lemma mul_conj_eq_coe : a * conj a = (a * conj a).re := a.mul_conj_eq_coe @[simp] lemma conj_zero : conj (0:ℍ[R]) = 0 := quaternion_algebra.conj_zero @[simp] lemma conj_neg : (-a).conj = -a.conj := a.conj_neg @[simp] lemma conj_sub : (a - b).conj = a.conj - b.conj := a.conj_sub b open opposite /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def conj_ae : ℍ[R] ≃ₐ[R] (ℍ[R]ᵒᵖ) := quaternion_algebra.conj_ae @[simp] lemma coe_conj_ae : ⇑(conj_ae : ℍ[R] ≃ₐ[R] ℍ[R]ᵒᵖ) = op ∘ conj := rfl /-- Square of the norm. -/ def norm_sq : monoid_with_zero_hom ℍ[R] R := { to_fun := λ a, (a * a.conj).re, map_zero' := by rw [conj_zero, zero_mul, zero_re], map_one' := by rw [conj_one, one_mul, one_re], map_mul' := λ x y, coe_injective $ by conv_lhs { rw [← mul_conj_eq_coe, conj_mul, mul_assoc, ← mul_assoc y, y.mul_conj_eq_coe, coe_commutes, ← mul_assoc, x.mul_conj_eq_coe, ← coe_mul] } } lemma norm_sq_def : norm_sq a = (a * a.conj).re := rfl lemma norm_sq_def' : norm_sq a = a.1^2 + a.2^2 + a.3^2 + a.4^2 := by simp only [norm_sq_def, sq, ← neg_mul_eq_mul_neg, sub_neg_eq_add, mul_re, conj_re, conj_im_i, conj_im_j, conj_im_k] lemma norm_sq_coe : norm_sq (x : ℍ[R]) = x^2 := by rw [norm_sq_def, conj_coe, ← coe_mul, coe_re, sq] @[simp] lemma norm_sq_neg : norm_sq (-a) = norm_sq a := by simp only [norm_sq_def, conj_neg, neg_mul_neg] lemma self_mul_conj : a * a.conj = norm_sq a := by rw [mul_conj_eq_coe, norm_sq_def] lemma conj_mul_self : a.conj * a = norm_sq a := by rw [← a.commute_self_conj.eq, self_mul_conj] lemma coe_norm_sq_add : (norm_sq (a + b) : ℍ[R]) = norm_sq a + a * b.conj + b * a.conj + norm_sq b := by simp [← self_mul_conj, mul_add, add_mul, add_assoc] end quaternion namespace quaternion variables {R : Type*} section linear_ordered_comm_ring variables [linear_ordered_comm_ring R] {a : ℍ[R]} @[simp] lemma norm_sq_eq_zero : norm_sq a = 0 ↔ a = 0 := begin refine ⟨λ h, _, λ h, h.symm ▸ norm_sq.map_zero⟩, rw [norm_sq_def', add_eq_zero_iff', add_eq_zero_iff', add_eq_zero_iff'] at h, exact ext a 0 (pow_eq_zero h.1.1.1) (pow_eq_zero h.1.1.2) (pow_eq_zero h.1.2) (pow_eq_zero h.2), all_goals { apply_rules [sq_nonneg, add_nonneg] } end lemma norm_sq_ne_zero : norm_sq a ≠ 0 ↔ a ≠ 0 := not_congr norm_sq_eq_zero @[simp] lemma norm_sq_nonneg : 0 ≤ norm_sq a := by { rw norm_sq_def', apply_rules [sq_nonneg, add_nonneg] } @[simp] lemma norm_sq_le_zero : norm_sq a ≤ 0 ↔ a = 0 := by simpa only [le_antisymm_iff, norm_sq_nonneg, and_true] using @norm_sq_eq_zero _ _ a instance : domain ℍ[R] := { exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := λ a b hab, have norm_sq a * norm_sq b = 0, by rwa [← norm_sq.map_mul, norm_sq_eq_zero], (eq_zero_or_eq_zero_of_mul_eq_zero this).imp norm_sq_eq_zero.1 norm_sq_eq_zero.1, .. quaternion.ring } end linear_ordered_comm_ring section field variables [linear_ordered_field R] (a b : ℍ[R]) @[simps { attrs := [] }]instance : has_inv ℍ[R] := ⟨λ a, (norm_sq a)⁻¹ • a.conj⟩ instance : division_ring ℍ[R] := { inv := has_inv.inv, inv_zero := by rw [has_inv_inv, conj_zero, smul_zero], mul_inv_cancel := λ a ha, by rw [has_inv_inv, algebra.mul_smul_comm, self_mul_conj, smul_coe, inv_mul_cancel (norm_sq_ne_zero.2 ha), coe_one], .. quaternion.domain } @[simp] lemma norm_sq_inv : norm_sq a⁻¹ = (norm_sq a)⁻¹ := monoid_with_zero_hom.map_inv' norm_sq _ @[simp] lemma norm_sq_div : norm_sq (a / b) = norm_sq a / norm_sq b := monoid_with_zero_hom.map_div norm_sq a b end field end quaternion
f06eb0c2febb6455a4fd7024c729d5bdc1a4d0be
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/localization/opposite.lean
f7efcb00d22d4e2434f9cc5e044296149e0affb3
[ "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
1,962
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.localization.predicate /-! # Localization of the opposite category If a functor `L : C ⥤ D` is a localization functor for `W : morphism_property C`, it is shown in this file that `L.op : Cᵒᵖ ⥤ Dᵒᵖ` is also a localization functor. -/ noncomputable theory open category_theory category_theory.category namespace category_theory variables {C D : Type*} [category C] [category D] {L : C ⥤ D} {W : morphism_property C} namespace localization /-- If `L : C ⥤ D` satisfies the universal property of the localisation for `W : morphism_property C`, then `L.op` also does. -/ def strict_universal_property_fixed_target.op {E : Type*} [category E] (h : strict_universal_property_fixed_target L W Eᵒᵖ): strict_universal_property_fixed_target L.op W.op E := { inverts := h.inverts.op, lift := λ F hF, (h.lift F.right_op hF.right_op).left_op, fac := λ F hF, begin convert congr_arg functor.left_op (h.fac F.right_op hF.right_op), exact F.right_op_left_op_eq.symm, end, uniq := λ F₁ F₂ eq, begin suffices : F₁.right_op = F₂.right_op, { rw [← F₁.right_op_left_op_eq, ← F₂.right_op_left_op_eq, this], }, have eq' := congr_arg functor.right_op eq, exact h.uniq _ _ eq', end, } instance is_localization_op : W.Q.op.is_localization W.op := functor.is_localization.mk' W.Q.op W.op (strict_universal_property_fixed_target_Q W _).op (strict_universal_property_fixed_target_Q W _).op end localization namespace functor instance is_localization.op [h : L.is_localization W] : L.op.is_localization W.op := is_localization.of_equivalence_target W.Q.op W.op L.op (localization.equivalence_from_model L W).op (nat_iso.op (localization.Q_comp_equivalence_from_model_functor_iso L W).symm) end functor end category_theory
877c691cc2c934a03a89cc89eee17d56adcdceeb
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/multilinear/finite_dimensional.lean
9aae60e8351c1f525b6daa0717df4fba94bc8fb1
[ "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
2,637
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import linear_algebra.multilinear.basic import linear_algebra.free_module.finite.basic /-! # Multilinear maps over finite dimensional spaces The main results are that multilinear maps over finitely-generated, free modules are finitely-generated and free. * `module.finite.multilinear_map` * `module.free.multilinear_map` We do not put this in `linear_algebra/multilinear_map/basic` to avoid making the imports too large there. -/ namespace multilinear_map variables {ι R M₂ : Type*} {M₁ : ι → Type*} variables [decidable_eq ι] variables [fintype ι] [comm_ring R] [add_comm_group M₂] [module R M₂] variables [Π i, add_comm_group (M₁ i)] [Π i, module R (M₁ i)] variables [module.finite R M₂] [module.free R M₂] variables [∀ i, module.finite R (M₁ i)] [∀ i, module.free R (M₁ i)] -- the induction requires us to show both at once private lemma free_and_finite : module.free R (multilinear_map R M₁ M₂) ∧ module.finite R (multilinear_map R M₁ M₂) := begin -- the `fin n` case is sufficient suffices : ∀ n (N : fin n → Type*) [Π i, add_comm_group (N i)], by exactI ∀ [Π i, module R (N i)], by exactI ∀ [∀ i, module.finite R (N i)] [∀ i, module.free R (N i)], module.free R (multilinear_map R N M₂) ∧ module.finite R (multilinear_map R N M₂), { casesI this _ (M₁ ∘ (fintype.equiv_fin ι).symm), have e := dom_dom_congr_linear_equiv' R M₁ M₂ (fintype.equiv_fin ι), exact ⟨module.free.of_equiv e.symm, module.finite.equiv e.symm⟩, }, introsI n N _ _ _ _, unfreezingI { induction n with n ih }, { exact ⟨module.free.of_equiv (const_linear_equiv_of_is_empty R N M₂), module.finite.equiv (const_linear_equiv_of_is_empty R N M₂)⟩ }, { suffices : module.free R (N 0 →ₗ[R] multilinear_map R (λ (i : fin n), N i.succ) M₂) ∧ module.finite R (N 0 →ₗ[R] multilinear_map R (λ (i : fin n), N i.succ) M₂), { casesI this, exact ⟨module.free.of_equiv (multilinear_curry_left_equiv R N M₂), module.finite.equiv (multilinear_curry_left_equiv R N M₂)⟩ }, casesI ih (λ i, N i.succ), exact ⟨module.free.linear_map _ _ _, module.finite.linear_map _ _⟩ }, end instance _root_.module.finite.multilinear_map : module.finite R (multilinear_map R M₁ M₂) := free_and_finite.2 instance _root_.module.free.multilinear_map : module.free R (multilinear_map R M₁ M₂) := free_and_finite.1 end multilinear_map
5da44e07bed931cfd6c3347f66c3cf358833a0e8
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/opposites.lean
4fa084ceb3d9d562b696f97e2930e96f23ce4441
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
7,515
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.types namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- The type of objects of the opposite of C (which should be a category). In order to avoid confusion between C and its opposite category, we set up the type of objects `opposite C` using the following pattern, which will be repeated later for the morphisms. 1. Define `opposite C := C`. 2. Define the isomorphisms `op : C → opposite C`, `unop : opposite C → C`. 3. Make the definition `opposite` irreducible. This has the following consequences. * `opposite C` and `C` are distinct types in the elaborator, so you must use `op` and `unop` explicitly to convert between them. * Both `unop (op X) = X` and `op (unop X) = X` are definitional equalities. Notably, every object of the opposite category is definitionally of the form `op X`, which greatly simplifies the definition of the structure of the opposite category, for example. (If Lean supported definitional eta equality for records, we could achieve the same goals using a structure with one field.) -/ def opposite (C : Sort u₁) : Sort u₁ := C -- Use a high right binding power (like that of postfix ⁻¹) so that, for example, -- `presheaf Cᵒᵖ` parses as `presheaf (Cᵒᵖ)` and not `(presheaf C)ᵒᵖ`. notation C `ᵒᵖ`:std.prec.max_plus := opposite C variables {C : Sort u₁} def op (X : C) : Cᵒᵖ := X def unop (X : Cᵒᵖ) : C := X attribute [irreducible] opposite @[simp] lemma unop_op (X : C) : unop (op X) = X := rfl @[simp] lemma op_unop (X : Cᵒᵖ) : op (unop X) = X := rfl lemma op_inj : function.injective (@op C) := by { rintros _ _ ⟨ ⟩, refl } lemma unop_inj : function.injective (@unop C) := by { rintros _ _ ⟨ ⟩, refl } section has_hom variables [𝒞 : has_hom.{v₁} C] include 𝒞 /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cᵒᵖ. -/ instance has_hom.opposite : has_hom Cᵒᵖ := { hom := λ X Y, unop Y ⟶ unop X } def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end has_hom variables [𝒞 : category.{v₁} C] include 𝒞 instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } -- TODO this is an equivalence namespace functor section variables {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒟 variables {C D} protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } @[simp] lemma op_obj (F : C ⥤ D) (X : Cᵒᵖ) : (F.op).obj X = op (F.obj (unop X)) := rfl @[simp] lemma op_map (F : C ⥤ D) {X Y : Cᵒᵖ} (f : X ⟶ Y) : (F.op).map f = (F.map f.unop).op := rfl protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } @[simp] lemma unop_obj (F : Cᵒᵖ ⥤ Dᵒᵖ) (X : C) : (F.unop).obj X = unop (F.obj (op X)) := rfl @[simp] lemma unop_map (F : Cᵒᵖ ⥤ Dᵒᵖ) {X Y : C} (f : X ⟶ Y) : (F.unop).map f = (F.map f.op).unop := rfl variables (C D) definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, has_hom.hom.unop_inj $ eq.symm (α.unop.naturality f.unop) } } @[simp] lemma op_hom.obj (F : (C ⥤ D)ᵒᵖ) : (op_hom C D).obj F = (unop F).op := rfl @[simp] lemma op_hom.map_app {F G : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (X : Cᵒᵖ) : ((op_hom C D).map α).app X = (α.unop.app (unop X)).op := rfl definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, has_hom.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, has_hom.hom.op_inj $ eq.symm (α.naturality f.op) } } @[simp] lemma op_inv.obj (F : Cᵒᵖ ⥤ Dᵒᵖ) : (op_inv C D).obj F = op F.unop := rfl @[simp] lemma op_inv.map_app {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) (X : C) : (((op_inv C D).map α).unop).app X = (α.app (op X)).unop := rfl -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { injectivity' := λ X Y f g h, has_hom.hom.unop_inj $ by simpa using injectivity F (has_hom.hom.op_inj h) } end section omit 𝒞 variables (E : Type u₁) [ℰ : category.{v₁+1} E] include ℰ /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : Eᵒᵖ × E ⥤ Type v₁ := { obj := λ p, unop p.1 ⟶ p.2, map := λ X Y f, λ h, f.1.unop ≫ h ≫ f.2 } @[simp] lemma hom_obj (X : Eᵒᵖ × E) : (functor.hom E).obj X = (unop X.1 ⟶ X.2) := rfl @[simp] lemma hom_pairing_map {X Y : Eᵒᵖ × E} (f : X ⟶ Y) : (functor.hom E).map f = λ h, f.1.unop ≫ h ≫ f.2 := rfl end end functor -- TODO the following definitions do not belong here omit 𝒞 variables (E : Type u₁) instance opposite.has_one [has_one E] : has_one (Eᵒᵖ) := { one := op 1 } instance opposite.has_mul [has_mul E] : has_mul (Eᵒᵖ) := { mul := λ x y, op $ unop y * unop x } @[simp] lemma opposite.unop_one [has_one E] : unop (1 : Eᵒᵖ) = (1 : E) := rfl @[simp] lemma opposite.unop_mul [has_mul E] (xs ys : Eᵒᵖ) : unop (xs * ys) = (unop ys * unop xs : E) := rfl @[simp] lemma opposite.op_one [has_one E] : op (1 : E) = 1 := rfl @[simp] lemma opposite.op_mul [has_mul E] (xs ys : E) : op (xs * ys) = (op ys * op xs) := rfl instance opposite.monoid [monoid E] : monoid (Eᵒᵖ) := { one := op 1, mul := λ x y, op $ unop y * unop x, mul_one := by { intros, apply unop_inj, simp }, one_mul := by { intros, simp }, mul_assoc := by { intros, simp [mul_assoc], } } end category_theory
a17e5048a336f29c4dfe1c29322a42c804201358
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/continuous_function/algebra.lean
5418350a9ca2460a95fc521d64999fafb4ae9b4c
[ "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
24,326
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Nicolò Cavalleri -/ import topology.algebra.module import topology.continuous_function.basic import algebra.algebra.subalgebra /-! # Algebraic structures over continuous functions In this file we define instances of algebraic structures over the type `continuous_map α β` (denoted `C(α, β)`) of **bundled** continuous maps from `α` to `β`. For example, `C(α, β)` is a group when `β` is a group, a ring when `β` is a ring, etc. For each type of algebraic structure, we also define an appropriate subobject of `α → β` with carrier `{ f : α → β | continuous f }`. For example, when `β` is a group, a subgroup `continuous_subgroup α β` of `α → β` is constructed with carrier `{ f : α → β | continuous f }`. Note that, rather than using the derived algebraic structures on these subobjects (for example, when `β` is a group, the derived group structure on `continuous_subgroup α β`), one should use `C(α, β)` with the appropriate instance of the structure. -/ local attribute [elab_simple] continuous.comp namespace continuous_functions variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {f g : {f : α → β | continuous f }} instance : has_coe_to_fun {f : α → β | continuous f} := ⟨_, subtype.val⟩ end continuous_functions namespace continuous_map variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] @[to_additive] instance has_mul [has_mul β] [has_continuous_mul β] : has_mul C(α, β) := ⟨λ f g, ⟨f * g, continuous_mul.comp (f.continuous.prod_mk g.continuous : _)⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul [has_mul β] [has_continuous_mul β] (f g : C(α, β)) : ((f * g : C(α, β)) : α → β) = (f : α → β) * (g : α → β) := rfl @[to_additive] instance [has_one β] : has_one C(α, β) := ⟨const (1 : β)⟩ @[simp, norm_cast, to_additive] lemma coe_one [has_one β] : ((1 : C(α, β)) : α → β) = (1 : α → β) := rfl @[simp, to_additive] lemma mul_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [semigroup γ] [has_continuous_mul γ] (f₁ f₂ : C(β, γ)) (g : C(α, β)) : (f₁ * f₂).comp g = f₁.comp g * f₂.comp g := by { ext, simp, } @[simp, to_additive] lemma one_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [has_one γ] (g : C(α, β)) : (1 : C(β, γ)).comp g = 1 := by { ext, simp, } end continuous_map section group_structure /-! ### Group stucture In this section we show that continuous functions valued in a topological group inherit the structure of a group. -/ section subtype /-- The `submonoid` of continuous maps `α → β`. -/ @[to_additive "The `add_submonoid` of continuous maps `α → β`. "] def continuous_submonoid (α : Type*) (β : Type*) [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : submonoid (α → β) := { carrier := { f : α → β | continuous f }, one_mem' := @continuous_const _ _ _ _ 1, mul_mem' := λ f g fc gc, continuous.comp has_continuous_mul.continuous_mul (continuous.prod_mk fc gc : _) } /-- The subgroup of continuous maps `α → β`. -/ @[to_additive "The `add_subgroup` of continuous maps `α → β`. "] def continuous_subgroup (α : Type*) (β : Type*) [topological_space α] [topological_space β] [group β] [topological_group β] : subgroup (α → β) := { inv_mem' := λ f fc, continuous.comp (@topological_group.continuous_inv β _ _ _) fc, ..continuous_submonoid α β, }. end subtype namespace continuous_map @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup β] [has_continuous_mul β] : semigroup C(α, β) := { mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _, ..continuous_map.has_mul} @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid C(α, β) := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, ..continuous_map.semigroup, ..continuous_map.has_one } /-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/ @[to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`.", simps] def coe_fn_monoid_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : C(α, β) →* (α → β) := { to_fun := coe_fn, map_one' := coe_one, map_mul' := coe_mul } /-- Composition on the left by a (continuous) homomorphism of topological monoids, as a `monoid_hom`. Similar to `monoid_hom.comp_left`. -/ @[to_additive "Composition on the left by a (continuous) homomorphism of topological `add_monoid`s, as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_left`.", simps] protected def _root_.monoid_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] [topological_space γ] [monoid γ] [has_continuous_mul γ] (g : β →* γ) (hg : continuous g) : C(α, β) →* C(α, γ) := { to_fun := λ f, (⟨g, hg⟩ : C(β, γ)).comp f, map_one' := ext $ λ x, g.map_one, map_mul' := λ f₁ f₂, ext $ λ x, g.map_mul _ _ } /-- Composition on the right as a `monoid_hom`. Similar to `monoid_hom.comp_hom'`. -/ @[to_additive "Composition on the right as an `add_monoid_hom`. Similar to `add_monoid_hom.comp_hom'`.", simps] def comp_monoid_hom' {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [monoid γ] [has_continuous_mul γ] (g : C(α, β)) : C(β, γ) →* C(α, γ) := { to_fun := λ f, f.comp g, map_one' := one_comp g, map_mul' := λ f₁ f₂, mul_comp f₁ f₂ g } @[simp, norm_cast] lemma coe_pow {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] (f : C(α, β)) (n : ℕ) : ((f^n : C(α, β)) : α → β) = (f : α → β)^n := (coe_fn_monoid_hom : C(α, β) →* _).map_pow f n @[simp] lemma pow_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [monoid γ] [has_continuous_mul γ] (f : C(β, γ)) (n : ℕ) (g : C(α, β)) : (f^n).comp g = (f.comp g)^n := (comp_monoid_hom' g).map_pow f n @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid β] [has_continuous_mul β] : comm_monoid C(α, β) := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, mul_comm := λ a b, by ext; exact mul_comm _ _, ..continuous_map.semigroup, ..continuous_map.has_one } open_locale big_operators @[simp, to_additive] lemma coe_prod {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) : ⇑(∏ i in s, f i) = (∏ i in s, (f i : α → β)) := (coe_fn_monoid_hom : C(α, β) →* _).map_prod f s @[to_additive] lemma prod_apply {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) (a : α) : (∏ i in s, f i) a = (∏ i in s, f i a) := by simp @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group C(α, β) := { inv := λ f, ⟨λ x, (f x)⁻¹, continuous_inv.comp f.continuous⟩, mul_left_inv := λ a, by ext; exact mul_left_inv _, ..continuous_map.monoid } @[simp, norm_cast, to_additive] lemma coe_inv {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] (f : C(α, β)) : ((f⁻¹ : C(α, β)) : α → β) = (f⁻¹ : α → β) := rfl @[simp, norm_cast, to_additive] lemma coe_div {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] (f g : C(α, β)) : ((f / g : C(α, β)) : α → β) = (f : α → β) / (g : α → β) := by { simp only [div_eq_mul_inv], refl, } @[simp, to_additive] lemma inv_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [group γ] [topological_group γ] (f : C(β, γ)) (g : C(α, β)) : (f⁻¹).comp g = (f.comp g)⁻¹ := by { ext, simp, } @[simp, to_additive] lemma div_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [group γ] [topological_group γ] (f g : C(β, γ)) (h : C(α, β)) : (f / g).comp h = (f.comp h) / (g.comp h) := by { ext, simp, } @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group C(α, β) := { ..continuous_map.group, ..continuous_map.comm_monoid } end continuous_map end group_structure section ring_structure /-! ### Ring stucture In this section we show that continuous functions valued in a topological ring `R` inherit the structure of a ring. -/ section subtype /-- The subsemiring of continuous maps `α → β`. -/ def continuous_subsemiring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [semiring R] [topological_semiring R] : subsemiring (α → R) := { ..continuous_add_submonoid α R, ..continuous_submonoid α R }. /-- The subring of continuous maps `α → β`. -/ def continuous_subring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [ring R] [topological_ring R] : subring (α → R) := { ..continuous_subsemiring α R, ..continuous_add_subgroup α R }. end subtype namespace continuous_map instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] : semiring C(α, β) := { left_distrib := λ a b c, by ext; exact left_distrib _ _ _, right_distrib := λ a b c, by ext; exact right_distrib _ _ _, zero_mul := λ a, by ext; exact zero_mul _, mul_zero := λ a, by ext; exact mul_zero _, ..continuous_map.add_comm_monoid, ..continuous_map.monoid } instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : ring C(α, β) := { ..continuous_map.semiring, ..continuous_map.add_comm_group, } instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_ring β] [topological_ring β] : comm_ring C(α, β) := { ..continuous_map.semiring, ..continuous_map.add_comm_group, ..continuous_map.comm_monoid,} /-- Composition on the left by a (continuous) homomorphism of topological rings, as a `ring_hom`. Similar to `ring_hom.comp_left`. -/ @[simps] protected def _root_.ring_hom.comp_left_continuous (α : Type*) {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] [topological_space γ] [semiring γ] [topological_semiring γ] (g : β →+* γ) (hg : continuous g) : C(α, β) →+* C(α, γ) := { .. g.to_monoid_hom.comp_left_continuous α hg, .. g.to_add_monoid_hom.comp_left_continuous α hg } /-- Coercion to a function as a `ring_hom`. -/ @[simps] def coe_fn_ring_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : C(α, β) →+* (α → β) := { to_fun := coe_fn, ..(coe_fn_monoid_hom : C(α, β) →* _), ..(coe_fn_add_monoid_hom : C(α, β) →+ _) } end continuous_map end ring_structure local attribute [ext] subtype.eq section module_structure /-! ### Semiodule stucture In this section we show that continuous functions valued in a topological module `M` over a topological semiring `R` inherit the structure of a module. -/ section subtype variables (α : Type*) [topological_space α] variables (R : Type*) [semiring R] [topological_space R] variables (M : Type*) [topological_space M] [add_comm_group M] variables [module R M] [has_continuous_smul R M] [topological_add_group M] /-- The `R`-submodule of continuous maps `α → M`. -/ def continuous_submodule : submodule R (α → M) := { carrier := { f : α → M | continuous f }, smul_mem' := λ c f hf, continuous_smul.comp (continuous.prod_mk (continuous_const : continuous (λ x, c)) hf), ..continuous_add_subgroup α M } end subtype namespace continuous_map variables {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] instance [module R M] [has_continuous_smul R M] : has_scalar R C(α, M) := ⟨λ r f, ⟨r • f, f.continuous.const_smul r⟩⟩ @[simp, norm_cast] lemma coe_smul [module R M] [has_continuous_smul R M] (c : R) (f : C(α, M)) : ⇑(c • f) = c • f := rfl lemma smul_apply [module R M] [has_continuous_smul R M] (c : R) (f : C(α, M)) (a : α) : (c • f) a = c • (f a) := by simp @[simp] lemma smul_comp {α : Type*} {β : Type*} [topological_space α] [topological_space β] [module R M] [has_continuous_smul R M] (r : R) (f : C(β, M)) (g : C(α, β)) : (r • f).comp g = r • (f.comp g) := by { ext, simp, } variables [has_continuous_add M] [module R M] [has_continuous_smul R M] variables [has_continuous_add M₂] [module R M₂] [has_continuous_smul R M₂] instance module : module R C(α, M) := { smul := (•), smul_add := λ c f g, by { ext, exact smul_add c (f x) (g x) }, add_smul := λ c₁ c₂ f, by { ext, exact add_smul c₁ c₂ (f x) }, mul_smul := λ c₁ c₂ f, by { ext, exact mul_smul c₁ c₂ (f x) }, one_smul := λ f, by { ext, exact one_smul R (f x) }, zero_smul := λ f, by { ext, exact zero_smul _ _ }, smul_zero := λ r, by { ext, exact smul_zero _ } } variables (R) /-- Composition on the left by a continuous linear map, as a `linear_map`. Similar to `linear_map.comp_left`. -/ @[simps] protected def _root_.continuous_linear_map.comp_left_continuous (α : Type*) [topological_space α] (g : M →L[R] M₂) : C(α, M) →ₗ[R] C(α, M₂) := { map_smul' := λ c f, ext $ λ x, g.map_smul' c _, .. g.to_linear_map.to_add_monoid_hom.comp_left_continuous α g.continuous } /-- Coercion to a function as a `linear_map`. -/ @[simps] def coe_fn_linear_map : C(α, M) →ₗ[R] (α → M) := { to_fun := coe_fn, map_smul' := coe_smul, ..(coe_fn_add_monoid_hom : C(α, M) →+ _) } end continuous_map end module_structure section algebra_structure /-! ### Algebra structure In this section we show that continuous functions valued in a topological algebra `A` over a ring `R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra is obtained by requiring that `A` be both a `has_continuous_smul` and a `topological_semiring`.-/ section subtype variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] /-- The `R`-subalgebra of continuous maps `α → A`. -/ def continuous_subalgebra : subalgebra R (α → A) := { carrier := { f : α → A | continuous f }, algebra_map_mem' := λ r, (continuous_const : continuous $ λ (x : α), algebra_map R A r), ..continuous_subsemiring α A } end subtype section continuous_map variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] {A₂ : Type*} [topological_space A₂] [semiring A₂] [algebra R A₂] [topological_semiring A₂] /-- Continuous constant functions as a `ring_hom`. -/ def continuous_map.C : R →+* C(α, A) := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } @[simp] lemma continuous_map.C_apply (r : R) (a : α) : continuous_map.C r a = algebra_map R A r := rfl variables [topological_space R] [has_continuous_smul R A] [has_continuous_smul R A₂] instance continuous_map.algebra : algebra R C(α, A) := { to_ring_hom := continuous_map.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, } variables (R) /-- Composition on the left by a (continuous) homomorphism of topological `R`-algebras, as an `alg_hom`. Similar to `alg_hom.comp_left`. -/ @[simps] protected def alg_hom.comp_left_continuous {α : Type*} [topological_space α] (g : A →ₐ[R] A₂) (hg : continuous g) : C(α, A) →ₐ[R] C(α, A₂) := { commutes' := λ c, continuous_map.ext $ λ _, g.commutes' _, .. g.to_ring_hom.comp_left_continuous α hg } /-- Coercion to a function as an `alg_hom`. -/ @[simps] def continuous_map.coe_fn_alg_hom : C(α, A) →ₐ[R] (α → A) := { to_fun := coe_fn, commutes' := λ r, rfl, -- `..(continuous_map.coe_fn_ring_hom : C(α, A) →+* _)` times out for some reason map_zero' := continuous_map.coe_zero, map_one' := continuous_map.coe_one, map_add' := continuous_map.coe_add, map_mul' := continuous_map.coe_mul } instance: is_scalar_tower R A C(α, A) := { smul_assoc := λ _ _ _, by { ext, simp } } variables {R} /-- A version of `separates_points` for subalgebras of the continuous functions, used for stating the Stone-Weierstrass theorem. -/ abbreviation subalgebra.separates_points (s : subalgebra R C(α, A)) : Prop := set.separates_points ((λ f : C(α, A), (f : α → A)) '' (s : set C(α, A))) lemma subalgebra.separates_points_monotone : monotone (λ s : subalgebra R C(α, A), s.separates_points) := λ s s' r h x y n, begin obtain ⟨f, m, w⟩ := h n, rcases m with ⟨f, ⟨m, rfl⟩⟩, exact ⟨_, ⟨f, ⟨r m, rfl⟩⟩, w⟩, end @[simp] lemma algebra_map_apply (k : R) (a : α) : algebra_map R C(α, A) k a = k • 1 := by { rw algebra.algebra_map_eq_smul_one, refl, } variables {𝕜 : Type*} [topological_space 𝕜] /-- A set of continuous maps "separates points strongly" if for each pair of distinct points there is a function with specified values on them. We give a slightly unusual formulation, where the specified values are given by some function `v`, and we ask `f x = v x ∧ f y = v y`. This avoids needing a hypothesis `x ≠ y`. In fact, this definition would work perfectly well for a set of non-continuous functions, but as the only current use case is in the Stone-Weierstrass theorem, writing it this way avoids having to deal with casts inside the set. (This may need to change if we do Stone-Weierstrass on non-compact spaces, where the functions would be continuous functions vanishing at infinity.) -/ def set.separates_points_strongly (s : set C(α, 𝕜)) : Prop := ∀ (v : α → 𝕜) (x y : α), ∃ f : s, (f x : 𝕜) = v x ∧ f y = v y variables [field 𝕜] [topological_ring 𝕜] /-- Working in continuous functions into a topological field, a subalgebra of functions that separates points also separates points strongly. By the hypothesis, we can find a function `f` so `f x ≠ f y`. By an affine transformation in the field we can arrange so that `f x = a` and `f x = b`. -/ lemma subalgebra.separates_points.strongly {s : subalgebra 𝕜 C(α, 𝕜)} (h : s.separates_points) : (s : set C(α, 𝕜)).separates_points_strongly := λ v x y, begin by_cases n : x = y, { subst n, use ((v x) • 1 : C(α, 𝕜)), { apply s.smul_mem, apply s.one_mem, }, { simp, }, }, obtain ⟨f, ⟨f, ⟨m, rfl⟩⟩, w⟩ := h n, replace w : f x - f y ≠ 0 := sub_ne_zero_of_ne w, let a := v x, let b := v y, let f' := ((b - a) * (f x - f y)⁻¹) • (continuous_map.C (f x) - f) + continuous_map.C a, refine ⟨⟨f', _⟩, _, _⟩, { simp only [f', set_like.mem_coe, subalgebra.mem_to_submodule], -- TODO should there be a tactic for this? -- We could add an attribute `@[subobject_mem]`, and a tactic -- ``def subobject_mem := `[solve_by_elim with subobject_mem { max_depth := 10 }]`` solve_by_elim [subalgebra.add_mem, subalgebra.smul_mem, subalgebra.sub_mem, subalgebra.algebra_map_mem] { max_depth := 6 }, }, { simp [f'], }, { simp [f', inv_mul_cancel_right' w], }, end end continuous_map -- TODO[gh-6025]: make this an instance once safe to do so lemma continuous_map.subsingleton_subalgebra (α : Type*) [topological_space α] (R : Type*) [comm_semiring R] [topological_space R] [topological_semiring R] [subsingleton α] : subsingleton (subalgebra R C(α, R)) := begin fsplit, intros s₁ s₂, by_cases n : nonempty α, { obtain ⟨x⟩ := n, ext f, have h : f = algebra_map R C(α, R) (f x), { ext x', simp only [mul_one, algebra.id.smul_eq_mul, algebra_map_apply], congr, }, rw h, simp only [subalgebra.algebra_map_mem], }, { ext f, have h : f = 0, { ext x', exact false.elim (n ⟨x'⟩), }, subst h, simp only [subalgebra.zero_mem], }, end end algebra_structure section module_over_continuous_functions /-! ### Structure as module over scalar functions If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M` is naturally a module over the ring of continuous functions from `α` to `R`. -/ namespace continuous_map instance has_scalar' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [module R M] [has_continuous_smul R M] : has_scalar C(α, R) C(α, M) := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_monoid M] [has_continuous_add M] [module R M] [has_continuous_smul R M] : module C(α, R) C(α, M) := { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x), zero_smul := λ f, by ext x; exact zero_smul _ _, smul_zero := λ r, by ext x; exact smul_zero _, } end continuous_map end module_over_continuous_functions /-! We now provide formulas for `f ⊓ g` and `f ⊔ g`, where `f g : C(α, β)`, in terms of `continuous_map.abs`. -/ section variables {R : Type*} [linear_ordered_field R] -- TODO: -- This lemma (and the next) could go all the way back in `algebra.ordered_field`, -- except that it is tedious to prove without tactics. -- Rather than stranding it at some intermediate location, -- it's here, immediately prior to the point of use. lemma min_eq_half_add_sub_abs_sub {x y : R} : min x y = 2⁻¹ * (x + y - abs (x - y)) := begin dsimp [min, max, abs], simp only [neg_le_self_iff, if_congr, sub_nonneg, neg_sub], split_ifs; ring_nf; linarith, end lemma max_eq_half_add_add_abs_sub {x y : R} : max x y = 2⁻¹ * (x + y + abs (x - y)) := begin dsimp [min, max, abs], simp only [neg_le_self_iff, if_congr, sub_nonneg, neg_sub], split_ifs; ring_nf; linarith, end end namespace continuous_map section lattice variables {α : Type*} [topological_space α] variables {β : Type*} [linear_ordered_field β] [topological_space β] [order_topology β] [topological_ring β] lemma inf_eq (f g : C(α, β)) : f ⊓ g = (2⁻¹ : β) • (f + g - (f - g).abs) := ext (λ x, by simpa using min_eq_half_add_sub_abs_sub) -- Not sure why this is grosser than `inf_eq`: lemma sup_eq (f g : C(α, β)) : f ⊔ g = (2⁻¹ : β) • (f + g + (f - g).abs) := ext (λ x, by simpa [mul_add] using @max_eq_half_add_add_abs_sub _ _ (f x) (g x)) end lattice end continuous_map
20a53cc364c13ed4b86a1f10f79d398e71649934
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love08_operational_semantics_homework_sheet.lean
7e2111e58be8c307b45b63792dab346c13efd834
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,496
lean
import .lovelib /- # LoVe Homework 8: Operational Semantics Homework must be done individually. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Question 1 (6 points + 1 bonus point): Semantics of the REPEAT Language We introduce REPEAT, a programming language that resembles the WHILE language but whose defining feature is a `repeat` loop. The Lean definition of its abstract syntax tree follows: -/ inductive stmt : Type | skip : stmt | assign : string → (state → ℕ) → stmt | seq : stmt → stmt → stmt | unless : (state → Prop) → stmt → stmt | repeat : ℕ → stmt → stmt infixr ` ;; ` : 90 := stmt.seq /- The `skip`, `assign`, and `S ;; T` statements have the same syntax and semantics as in the WHILE language. The `unless b S` statement executes `S` unless `b` is true—i.e., it executes `S` if `b` is false. Otherwise, `unless b S` does nothing. This construct is inspired by the Perl language. The `repeat n S` statement executes `S` exactly `n` times. Thus, `repeat 5 S` is equivalent to `S ;; S ;; S ;; S ;; S` (in terms of a big-step semantics at least) and `repeat 0 S` is equivalent to `skip`. 1.1 (1.5 points). Complete the following definition of a big-step semantics: -/ inductive big_step : stmt × state → state → Prop | skip {s} : big_step (stmt.skip, s) s -- enter the missing cases here infix ` ⟹ ` : 110 := big_step /- 1.2 (1.5 points). Complete the following definition of a small-step semantics: -/ inductive small_step : stmt × state → stmt × state → Prop | assign {x a s} : small_step (stmt.assign x a, s) (stmt.skip, s{x ↦ a s}) -- enter the missing cases here infixr ` ⇒ ` := small_step infixr ` ⇒* ` : 100 := star small_step /- 1.3 (1 point). We will now attempt to prove termination of the REPEAT language. More precisely, we will show that there cannot be infinite chains of the form `(S₀, s₀) ⇒ (S₁, s₁) ⇒ (S₂, s₂) ⇒ ⋯` Towards this goal, you are asked to define a __measure__ function: a function `mess` that takes a statement `S` and that returns a natural number indicating how "big" the statement is. The measure should be defined so that it strictly decreases with each small-step transition. -/ def mess : stmt → ℕ | stmt.skip := 0 -- enter the missing cases here /- 1.4 (1 point). Consider the following program `S₀`: -/ def incr (x : string) : stmt := stmt.assign x (λs, s x + 1) def S₀ : stmt := stmt.repeat 1 (incr "m" ;; incr "n") /- Check that `mess` strictly decreases with each step of its small-step evaluation, by giving `S₀`, `S₁`, `S₂`, …, as well as the corresponding values of `mess` (which you can obtain using `#eval`). -/ -- enter your answer here /- 1.5 (1 point). Prove that the measure decreases with each small-step transition. If necessary, revise your answer to question 1.3. -/ lemma small_step_mess_decreases {Ss Tt : stmt × state} (h : Ss ⇒ Tt) : mess (prod.fst Ss) > mess (prod.fst Tt) := sorry /- 1.6 (1 bonus point). Prove that the inverse of the `⇒` relation is well founded. The inverse is simply `λTt Ss, Ss ⇒ Tt`. A relation `≺` is well founded if there exist no infinite left-descending chains of the form `⋯ ≺ x₂ ≺ x₁ ≺ x₀` Proof strategy: The `measure` function from `mathlib` converts a function to `ℕ` to a relation, using `<` to compare two numbers. Hence, start by proving that `measure mess`, or rather `measure (mess ∘ prod.fst)`, is well founded. Here, `library_search` can help, or just search manually in `wf.lean`, close to the definition of `measure`. Then prove that `λTt Ss, Ss ⇒ Tt` is a subrelation of `measure (mess ∘ prod.fst)` (using lemma `small_step_mess_decreases` from question 1.4) and therefore (using another lemma from `wf.lean`) that it must be well founded. -/ lemma small_step_wf : well_founded (λTt Ss, Ss ⇒ Tt) := sorry /- ## Question 2 (3 points): Inversion Rules 2.1 (1 point). Prove the following inversion rule for the big-step semantics of `unless`. -/ lemma big_step_ite_iff {b S s t} : (stmt.unless b S, s) ⟹ t ↔ (b s ∧ s = t) ∨ (¬ b s ∧ (S, s) ⟹ t) := sorry /- 2.2 (2 points). Prove the following inversion rule for the big-step semantics of `repeat`. -/ lemma big_step_repeat_iff {n S s u} : (stmt.repeat n S, s) ⟹ u ↔ (n = 0 ∧ u = s) ∨ (∃m t, n = m + 1 ∧ (S, s) ⟹ t ∧ (stmt.repeat m S, t) ⟹ u) := sorry end LoVe
1b08b115c0dfbc739be242abb54d13d218009cc2
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/pnat/factors.lean
3ff5ca0efe6208d3ae8fd8876e23116da152008d
[ "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
14,072
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland -/ import tactic.basic import data.pnat.basic data.nat.prime data.multiset data.int.basic data.int.gcd algebra.group algebra.group_power algebra.ordered_ring /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and ℕ+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : lattice.distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : lattice.semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≤ v → u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p :: 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset → multiset ℕ := λ v, v.map (λ p, (p : ℕ)) instance coe_nat : has_coe prime_multiset (multiset ℕ) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_inj : function.injective (coe : prime_multiset → multiset ℕ) := multiset.injective_map nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ) = (p : ℕ) :: 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : ℕ) (h : p ∈ (v : multiset ℕ)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } def to_pnat_multiset : prime_multiset → multiset ℕ+ := λ v, v.map (λ p, (p : ℕ+)) instance coe_pnat : has_coe prime_multiset (multiset ℕ+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset → multiset ℕ+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_inj : function.injective (coe : prime_multiset → multiset ℕ+) := multiset.injective_map nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset ℕ+) = (p : ℕ+) :: 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : ℕ+) (h : p ∈ (v : multiset ℕ+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp' } instance coe_multiset_pnat_nat : has_coe (multiset ℕ+) (multiset ℕ) := ⟨λ v, v.map (λ n, (n : ℕ))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset ℕ+)) : (multiset ℕ)) = (v : multiset ℕ) := by { change (v.map (coe : nat.primes → ℕ+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } def prod (v : prime_multiset) : ℕ+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : ℕ) = (v : multiset ℕ).prod := begin let h : (v.prod : ℕ) = ((v.map coe).map coe).prod := (v.to_pnat_multiset.prod_hom coe).symm, rw [multiset.map_map] at h, have : (coe : ℕ+ → ℕ) ∘ (coe : nat.primes → ℕ+) = coe := funext (λ p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : ℕ+) := by { change multiset.prod ((p : ℕ+) :: 0) = (p : ℕ+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } def of_nat_multiset (v : multiset ℕ) (h : ∀ (p : ℕ), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ nat.primes nat.prime (λ p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h) : multiset ℕ) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (λ (p : ℕ) (h : p.prime), ((⟨p, h⟩ : nat.primes) : ℕ)) = (λ p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset ℕ) (h) : ((of_nat_multiset v h).prod : ℕ) = (v.prod : ℕ) := by rw[coe_prod, to_of_nat_multiset] def of_pnat_multiset (v : multiset ℕ+) (h : ∀ (p : ℕ+), p ∈ v → p.prime) : prime_multiset := @multiset.pmap ℕ+ nat.primes pnat.prime (λ p hp, ⟨(p : ℕ), hp⟩) v h theorem to_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h) : multiset ℕ+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (λ (p : ℕ+) (h : p.prime), ((coe : nat.primes → ℕ+) ⟨p, h⟩)) = (λ p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset ℕ+) (h) : ((of_pnat_multiset v h).prod : ℕ+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list ℕ) (h : ∀ (p : ℕ), p ∈ l → p.prime) : prime_multiset := of_nat_multiset (l : multiset ℕ) h theorem prod_of_nat_list (l : list ℕ) (h) : ((of_nat_list l h).prod : ℕ) = l.prod := by { have := prod_of_nat_multiset (l : multiset ℕ) h, rw [multiset.coe_prod] at this, exact this } def of_pnat_list (l : list ℕ+) (h : ∀ (p : ℕ+), p ∈ l → p.prime) : prime_multiset := of_pnat_multiset (l : multiset ℕ+) h theorem prod_of_pnat_list (l : list ℕ+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset ℕ+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid ℕ+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset → multiset ℕ+)], rw [multiset.prod_add] } theorem prod_smul (d : ℕ) (u : prime_multiset) : (add_monoid.smul d u).prod = u.prod ^ d := by { induction d with d ih, refl, rw[succ_smul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : ℕ+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : ℕ+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : ℕ+) : ((factor_multiset n) : (multiset ℕ)) = ((nat.factors n) : multiset ℕ) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_inj, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with l, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes → ℕ), have : ∀ (p : ℕ), p ∈ l' → p.prime := λ p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq ▸ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : ℕ+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid ℕ+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : ℕ+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : ℕ+) (m : ℕ) : factor_multiset (n ^ m) = add_monoid.smul m (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : ℕ+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : ℕ+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : ℕ+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : ℕ+} : factor_multiset m ≤ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd_intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : ℕ+} {v : prime_multiset}: factor_multiset m ≤ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≤ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : ℕ+} : u.prod ∣ n ↔ u ≤ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : ℕ+) : factor_multiset (gcd m n) = (factor_multiset m) ⊓ (factor_multiset n) := begin apply le_antisymm, { apply lattice.le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact lattice.inf_le_left, exact lattice.inf_le_right} end theorem factor_multiset_lcm (m n : ℕ+) : factor_multiset (lcm m n) = (factor_multiset m) ⊔ (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact lattice.le_sup_left, exact lattice.le_sup_right}, { apply lattice.sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : ℕ+) (p : nat.primes) (k : ℕ) : (p : ℕ+) ^ k ∣ m ↔ k ≤ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] }, { have : ∀ (m : ℕ), add_monoid.smul m (p::0) = multiset.repeat p m := λ m, by {induction m with m ih, { refl }, rw [succ_smul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u ⊓ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊓ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u ⊔ v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u ⊔ v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
28c2d5010336a1a7a19c3d5de0bf5b66d57bd480
43390109ab88557e6090f3245c47479c123ee500
/src/chris_hughes_various/blue_eyed_islanders.lean
6d6c2aec88c32db101ff54b60065c7c025280ce2
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,948
lean
import data.nat.basic tactic.finish open nat def island_rules : ℕ → ℕ → ℕ → Prop | 0 b B := (B = b ∨ B = b - 1) ∧ B > 0 | (succ d) b B := island_rules d b B ∧ ((∀ c, island_rules d b c → c = b) ↔ (∀ c, island_rules d B c → c = B)) theorem init_island {d b B} : island_rules d b B → (B = b ∨ B = b - 1) ∧ B > 0 := nat.rec_on d id (λ d ih, ih ∘ and.left) theorem blue_eyed_islander : ∀ d b, b > 0 → (d + 1 ≥ b ↔ ∀ B, island_rules d b B → B = b) := λ d, nat.rec_on d (λ b, nat.cases_on b (λ h, absurd h (dec_trivial : ¬0 > 0)) $ λ b, nat.cases_on b (λ h, ⟨λ h B hB, or.by_cases hB.left (λ h1, h1) (λ h1, false.elim $ (dec_trivial : ¬1 - 1 > 0) $ h1 ▸ hB.right), λ h, dec_trivial⟩) $ λ b h, ⟨λ h2, ((dec_trivial : ¬0 + 1 ≥ succ (succ b)) h2).elim, λ hB, false.elim $ (succ_ne_self $ succ b).symm $ hB (succ b) ⟨or.inr (succ_sub_one $ succ b).symm, dec_trivial⟩⟩) $ λ d hi b hb, ⟨λ hd, or.by_cases (lt_or_eq_of_le hd) (λ h B hB, (hi b hb).mp (le_of_succ_le_succ $ succ_le_of_lt h) B hB.left) $ λ h B hB, or.by_cases (init_island hB.left).left (λ h, h) $ λ h, hB.right.mpr ((hi B (init_island hB.left).right).mp $ le_of_succ_le_succ $ (((nat.sub_eq_iff_eq_add $ succ_le_of_lt hb).mp h.symm).trans $ add_one B) ▸ hd) B hB.left, λ hB, by_contradiction $ λ hd, Exists.rec_on (classical.not_forall.mp $ (iff_false_left $ not_le_of_gt $ lt_of_succ_lt $ lt_of_not_ge hd).mp $ hi b hb) $ λ B hB1, have hB2 : island_rules d b B ∧ ¬B = b := (@not_imp _ _ $ classical.prop_decidable _).mp hB1, hB2.right $ hB B ⟨hB2.left, iff.mpr (iff_false_left $ λ h, hB2.right $ h B hB2.left) $ (iff_false_left $ not_le_of_gt $ lt_of_succ_lt_succ (((nat.sub_eq_iff_eq_add $ succ_le_of_lt hb).mp (or.resolve_left (init_island hB2.left).left hB2.right).symm) ▸ (lt_of_not_ge hd) : succ (d + 1) < B + 1)).mp $ hi B (init_island hB2.left).right⟩⟩
853a1f0bcd0d427d412cba0ebf67cb6480fa1380
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/homotopy/default.hlean
6048262cf7ac7fe9de1b3175da9e0e2b64c3b976
[ "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
256
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .sphere2 .EM .torus .red_susp .quaternionic_hopf .smash .cellcomplex .interval .cylinder
624de2ae31c60f864e426d936972e757c3a8f0a1
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/free_comm_ring.lean
1dd9a511f3ff90e770645c4bbf821b44ebed56b0
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
15,910
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.equiv.functor import data.mv_polynomial import ring_theory.ideal_operations import ring_theory.free_ring noncomputable theory open_locale classical universes u v variables (α : Type u) def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [comm_ring β] (f : α → β) /-- Lift a map `α → R` to a ring homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : free_comm_ring α → β := free_abelian_group.lift $ λ s, (s.map f).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv_lhs { dsimp only [free_abelian_group.mul_def] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end /-- Lift of a map `f : α → β` to `free_comm_ring α` as a ring homomorphism. We don't use it as the canonical form because Lean fails to coerce it to a function. -/ def lift_hom : free_comm_ring α →+* β := ⟨lift f, lift_one f, lift_mul f, lift_zero f, lift_add f⟩ instance : is_ring_hom (lift f) := (lift_hom f).is_ring_hom @[simp] lemma coe_lift_hom : ⇑(lift_hom f : free_comm_ring α →+* β) = lift f := rfl @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := (lift_hom f).map_pow _ _ @[simp] lemma lift_comp_of (f : free_comm_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_comm_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α → free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift_hom $ of ∘ f lemma map_zero : map f 0 = 0 := rfl lemma map_one : map f 1 = 1 := rfl lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported def restriction (s : set α) [decidable_pred s] (x : free_comm_ring α) : free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) x section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ @[simp] lemma restriction_zero : restriction s 0 = 0 := lift_zero _ @[simp] lemma restriction_one : restriction s 1 = 1 := lift_one _ @[simp] lemma restriction_add : restriction s (x + y) = restriction s x + restriction s y := lift_add _ _ _ @[simp] lemma restriction_neg : restriction s (-x) = -restriction s x := lift_neg _ _ @[simp] lemma restriction_sub : restriction s (x - y) = restriction s x - restriction s y := lift_sub _ _ _ @[simp] lemma restriction_mul : restriction s (x * y) = restriction s x * restriction s y := lift_mul _ _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin haveI := classical.dec_pred s, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [lift_one], norm_cast }, { use -1, rw [lift_neg, lift_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [lift_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [lift_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw restriction_one, refl }, { rw [restriction_neg, map_neg, restriction_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, restriction_of, dif_pos hps, map_mul, map_of, ih] }, { intros x y ihx ihy, rw [restriction_add, map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) def to_free_comm_ring {α} : free_ring α → free_comm_ring α := free_ring.lift free_comm_ring.of instance to_free_comm_ring.is_ring_hom : is_ring_hom (@to_free_comm_ring α) := free_ring.is_ring_hom free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom _ @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := free_ring.lift_neg _ _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := free_ring.lift_add _ _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := free_ring.lift_sub _ _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := free_ring.lift_mul _ _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact free_ring.lift_add _ _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact free_ring.lift_mul _ _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := begin funext, apply @free_abelian_group.lift.ext _ _ _ (coe : free_ring α → free_comm_ring α) _ _ (free_abelian_group.lift.is_add_group_hom _), intros x, change free_ring.lift free_comm_ring.of (free_abelian_group.of x) = _, change _ = free_abelian_group.of (↑x), induction x with hd tl ih, {refl}, simp only [*, free_ring.lift, free_comm_ring.of, free_abelian_group.of, free_abelian_group.lift, free_group.of, free_group.to_group, free_group.to_group.aux, mul_one, free_group.quot_lift_mk, abelianization.lift.of, bool.cond_tt, list.prod_cons, cond, list.prod_nil, list.map] at *, refl end def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @ring_equiv.of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by rw [← (subsingleton_equiv_free_comm_ring α).left_inv (y * x), is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, mul_comm, ← is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, (subsingleton_equiv_free_comm_ring α).left_inv], .. free_ring.ring α } end free_ring def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ coe free_comm_ring.of, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, rw [free_abelian_group.lift.of], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ coe free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [free_comm_ring.lift_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [free_comm_ring.lift_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, int.cast_neg, int.cast_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [free_comm_ring.lift_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) ↑i = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [int.cast_zero, free_comm_ring.lift_zero, mv_polynomial.C_0]) (λ i ih, by rw [int.cast_add, int.cast_one, free_comm_ring.lift_add, free_comm_ring.lift_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [int.cast_sub, int.cast_one, free_comm_ring.lift_sub, free_comm_ring.lift_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, free_comm_ring.lift_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, free_comm_ring.lift_mul, free_comm_ring.lift_of, ih] } end, .. free_comm_ring.lift_hom $ λ a, mv_polynomial.X a } def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
93c881b28936f7b6f818674c7f80b821f985d291
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/lie/free.lean
9bb3c7bd5a2b9987d668c4bcd99bff0527f13689
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
10,004
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import algebra.lie.non_unital_non_assoc_algebra import algebra.lie.universal_enveloping import algebra.free_non_unital_non_assoc_algebra /-! # Free Lie algebras Given a commutative ring `R` and a type `X` we construct the free Lie algebra on `X` with coefficients in `R` together with its universal property. ## Main definitions * `free_lie_algebra` * `free_lie_algebra.lift` * `free_lie_algebra.of` * `free_lie_algebra.universal_enveloping_equiv_free_algebra` ## Implementation details ### Quotient of free non-unital, non-associative algebra We follow [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*](bourbaki1975) and construct the free Lie algebra as a quotient of the free non-unital, non-associative algebra. Since we do not currently have definitions of ideals, lattices of ideals, and quotients for `non_unital_non_assoc_semiring`, we construct our quotient using the low-level `quot` function on an inductively-defined relation. ### Alternative construction (needs PBW) An alternative construction of the free Lie algebra on `X` is to start with the free unital associative algebra on `X`, regard it as a Lie algebra via the ring commutator, and take its smallest Lie subalgebra containing `X`. I.e.: `lie_subalgebra.lie_span R (free_algebra R X) (set.range (free_algebra.ι R))`. However with this definition there does not seem to be an easy proof that the required universal property holds, and I don't know of a proof that avoids invoking the Poincaré–Birkhoff–Witt theorem. A related MathOverflow question is [this one](https://mathoverflow.net/questions/396680/). ## Tags lie algebra, free algebra, non-unital, non-associative, universal property, forgetful functor, adjoint functor -/ universes u v w noncomputable theory variables (R : Type u) (X : Type v) [comm_ring R] /-- We save characters by using Bourbaki's name `lib` (as in «libre») for `free_non_unital_non_assoc_algebra` in this file. -/ local notation `lib` := free_non_unital_non_assoc_algebra local notation `lib.lift` := free_non_unital_non_assoc_algebra.lift local notation `lib.of` := free_non_unital_non_assoc_algebra.of local notation `lib.lift_of_apply` := free_non_unital_non_assoc_algebra.lift_of_apply local notation `lib.lift_comp_of` := free_non_unital_non_assoc_algebra.lift_comp_of namespace free_lie_algebra /-- The quotient of `lib R X` by the equivalence relation generated by this relation will give us the free Lie algebra. -/ inductive rel : lib R X → lib R X → Prop | lie_self (a : lib R X) : rel (a * a) 0 | leibniz_lie (a b c : lib R X) : rel (a * (b * c)) (((a * b) * c) + (b * (a * c))) | smul (t : R) (a b : lib R X) : rel a b → rel (t • a) (t • b) | add_right (a b c : lib R X) : rel a b → rel (a + c) (b + c) | mul_left (a b c : lib R X) : rel b c → rel (a * b) (a * c) | mul_right (a b c : lib R X) : rel a b → rel (a * c) (b * c) variables {R X} lemma rel.add_left (a b c : lib R X) (h : rel R X b c) : rel R X (a + b) (a + c) := by { rw [add_comm _ b, add_comm _ c], exact rel.add_right _ _ _ h, } lemma rel.neg (a b : lib R X) (h : rel R X a b) : rel R X (-a) (-b) := h.smul (-1) _ _ end free_lie_algebra /-- The free Lie algebra on the type `X` with coefficients in the commutative ring `R`. -/ @[derive inhabited] def free_lie_algebra := quot (free_lie_algebra.rel R X) namespace free_lie_algebra instance : add_comm_group (free_lie_algebra R X) := { add := quot.map₂ (+) rel.add_left rel.add_right, add_comm := by { rintros ⟨a⟩ ⟨b⟩, change quot.mk _ _ = quot.mk _ _, rw add_comm, }, add_assoc := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, change quot.mk _ _ = quot.mk _ _, rw add_assoc, }, zero := quot.mk _ 0, zero_add := by { rintros ⟨a⟩, change quot.mk _ _ = _, rw zero_add, }, add_zero := by { rintros ⟨a⟩, change quot.mk _ _ = _, rw add_zero, }, neg := quot.map has_neg.neg rel.neg, add_left_neg := by { rintros ⟨a⟩, change quot.mk _ _ = quot.mk _ _ , rw add_left_neg, } } instance : module R (free_lie_algebra R X) := { smul := λ t, quot.map ((•) t) (rel.smul t), one_smul := by { rintros ⟨a⟩, change quot.mk _ _ = quot.mk _ _, rw one_smul, }, mul_smul := by { rintros t₁ t₂ ⟨a⟩, change quot.mk _ _ = quot.mk _ _, rw mul_smul, }, add_smul := by { rintros t₁ t₂ ⟨a⟩, change quot.mk _ _ = quot.mk _ _, rw add_smul, }, smul_add := by { rintros t ⟨a⟩ ⟨b⟩, change quot.mk _ _ = quot.mk _ _, rw smul_add, }, zero_smul := by { rintros ⟨a⟩, change quot.mk _ _ = quot.mk _ _, rw zero_smul, }, smul_zero := λ t, by { change quot.mk _ _ = quot.mk _ _, rw smul_zero, }, } /-- Note that here we turn the `has_mul` coming from the `non_unital_non_assoc_semiring` structure on `lib R X` into a `has_bracket` on `free_lie_algebra`. -/ instance : lie_ring (free_lie_algebra R X) := { bracket := quot.map₂ (*) rel.mul_left rel.mul_right, add_lie := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, change quot.mk _ _ = quot.mk _ _, rw add_mul, }, lie_add := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, change quot.mk _ _ = quot.mk _ _, rw mul_add, }, lie_self := by { rintros ⟨a⟩, exact quot.sound (rel.lie_self a), }, leibniz_lie := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, exact quot.sound (rel.leibniz_lie a b c), }, } instance : lie_algebra R (free_lie_algebra R X) := { lie_smul := begin rintros t ⟨a⟩ ⟨c⟩, change quot.mk _ (a • (t • c)) = quot.mk _ (t • (a • c)), rw ← smul_comm, end, } variables {X} /-- The embedding of `X` into the free Lie algebra of `X` with coefficients in the commutative ring `R`. -/ def of : X → free_lie_algebra R X := λ x, quot.mk _ (lib.of R x) variables {L : Type w} [lie_ring L] [lie_algebra R L] local attribute [instance] lie_ring.to_non_unital_non_assoc_semiring /-- An auxiliary definition used to construct the equivalence `lift` below. -/ def lift_aux (f : X → L) := lib.lift R f lemma lift_aux_map_smul (f : X → L) (t : R) (a : lib R X) : lift_aux R f (t • a) = t • lift_aux R f a := non_unital_alg_hom.map_smul _ t a lemma lift_aux_map_add (f : X → L) (a b : lib R X) : lift_aux R f (a + b) = (lift_aux R f a) + (lift_aux R f b) := non_unital_alg_hom.map_add _ a b lemma lift_aux_map_mul (f : X → L) (a b : lib R X) : lift_aux R f (a * b) = ⁅lift_aux R f a, lift_aux R f b⁆ := non_unital_alg_hom.map_mul _ a b lemma lift_aux_spec (f : X → L) (a b : lib R X) (h : free_lie_algebra.rel R X a b) : lift_aux R f a = lift_aux R f b := begin induction h, case rel.lie_self : a' { simp only [lift_aux_map_mul, non_unital_alg_hom.map_zero, lie_self], }, case rel.leibniz_lie : a' b' c' { simp only [lift_aux_map_mul, lift_aux_map_add, sub_add_cancel, lie_lie], }, case rel.smul : t a' b' h₁ h₂ { simp only [lift_aux_map_smul, h₂], }, case rel.add_right : a' b' c' h₁ h₂ { simp only [lift_aux_map_add, h₂], }, case rel.mul_left : a' b' c' h₁ h₂ { simp only [lift_aux_map_mul, h₂], }, case rel.mul_right : a' b' c' h₁ h₂ { simp only [lift_aux_map_mul, h₂], }, end /-- The quotient map as a `non_unital_alg_hom`. -/ def mk : non_unital_alg_hom R (lib R X) (free_lie_algebra R X) := { to_fun := quot.mk (rel R X), map_smul' := λ t a, rfl, map_zero' := rfl, map_add' := λ a b, rfl, map_mul' := λ a b, rfl, } /-- The functor `X ↦ free_lie_algebra R X` from the category of types to the category of Lie algebras over `R` is adjoint to the forgetful functor in the other direction. -/ def lift : (X → L) ≃ (free_lie_algebra R X →ₗ⁅R⁆ L) := { to_fun := λ f, { to_fun := λ c, quot.lift_on c (lift_aux R f) (lift_aux_spec R f), map_add' := by { rintros ⟨a⟩ ⟨b⟩, rw ← lift_aux_map_add, refl, }, map_smul' := by { rintros t ⟨a⟩, rw ← lift_aux_map_smul, refl, }, map_lie' := by { rintros ⟨a⟩ ⟨b⟩, rw ← lift_aux_map_mul, refl, }, }, inv_fun := λ F, F ∘ (of R), left_inv := λ f, by { ext x, simp only [lift_aux, of, quot.lift_on_mk, lie_hom.coe_mk, function.comp_app, lib.lift_of_apply], }, right_inv := λ F, begin ext ⟨a⟩, let F' := F.to_non_unital_alg_hom.comp (mk R), exact non_unital_alg_hom.congr_fun (lib.lift_comp_of R F') a, end, } @[simp] lemma lift_symm_apply (F : free_lie_algebra R X →ₗ⁅R⁆ L) : (lift R).symm F = F ∘ (of R) := rfl variables {R} @[simp] lemma of_comp_lift (f : X → L) : (lift R f) ∘ (of R) = f := (lift R).left_inv f @[simp] lemma lift_unique (f : X → L) (g : free_lie_algebra R X →ₗ⁅R⁆ L) : g ∘ (of R) = f ↔ g = lift R f := (lift R).symm_apply_eq attribute [irreducible] of lift @[simp] lemma lift_of_apply (f : X → L) (x) : lift R f (of R x) = f x := by rw [← function.comp_app (lift R f) (of R) x, of_comp_lift] @[simp] lemma lift_comp_of (F : free_lie_algebra R X →ₗ⁅R⁆ L) : lift R (F ∘ (of R)) = F := by { rw ← lift_symm_apply, exact (lift R).apply_symm_apply F, } @[ext] lemma hom_ext {F₁ F₂ : free_lie_algebra R X →ₗ⁅R⁆ L} (h : ∀ x, F₁ (of R x) = F₂ (of R x)) : F₁ = F₂ := have h' : (lift R).symm F₁ = (lift R).symm F₂, { ext, simp [h], }, (lift R).symm.injective h' variables (R X) /-- The universal enveloping algebra of the free Lie algebra is just the free unital associative algebra. -/ @[simps] def universal_enveloping_equiv_free_algebra : universal_enveloping_algebra R (free_lie_algebra R X) ≃ₐ[R] free_algebra R X := alg_equiv.of_alg_hom (universal_enveloping_algebra.lift R $ free_lie_algebra.lift R $ free_algebra.ι R) (free_algebra.lift R $ (universal_enveloping_algebra.ι R) ∘ (free_lie_algebra.of R)) (by { ext, simp, }) (by { ext, simp, }) end free_lie_algebra
21d5e1504026ba89c70d64e5822cf396a76ec5ba
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/answers/hw6_partial_key.lean
dbb952bded6ad6cb3baf2b8b09c0d981ff0947d6
[]
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
7,200
lean
import data.set /- 1. Exercise: Prove that for any set, L, L ∩ L = L. -/ theorem self_intersect (β : Type) (L: set β) : L ∩ L = L := begin /- By set extensionality it will suffice to have a proof of L ∩ L ↔ L. -/ apply set.ext, /- To prove it, first assume that we have an arbitrary value, x. -/ assume x, /- What now have to prove the biimplication in each direction: if x ∈ L ∩ L then it's in L, and if x ∈ L then it's in L ∩ L. -/ split, /- We'll start with the forward direction by assuming that x ∈ L ∩ L. -/ assume h, /- By the definition of ∩, this means x ∈ L and x ∈ L. If that's true then certainly x ∈ L (by ∧ elimination--but leave out these kinds of logical reasoning details now). We have thus proven x ∈ L ∩ L → x ∈ L. -/ cases h with l r, assumption, /- Now the reverse: x ∈ L → x ∈ L ∩ L. Assume x ∈ L and show is that x ∈ L ∩ L. -/ assume h, /- But that is true by the definition of ∩. x ∈ L ∩ L means (x ∈ L) and (x ∈ L). This in turn is true by the definition of and. This proves (x ∈ L) → (x ∈ L ∩ L), finishes the proof of (x ∈ L) ↔ (x ∈ L ∩ L). And by set extensionality we have = L ∩ L. -/ apply and.intro h h, -- QED. end /- 2. Exercise: Give a formal statement and proof, then an English language proof, that the union operator on sets is commutative. -/ theorem union_comm : ∀ (β : Type) {s1 s2 : set β}, s1 ∪ s2 = s2 ∪ s1 := begin intros, apply set.ext _, intro, split, -- forward assume h, -- by case analysis of h cases h, exact or.inr h, exact or.inl h, -- backward assume h, cases h, exact or.inr h, exact or.inl h, end /- Proof: To show that ∩ is commutative, we need to show that for all sets, A and B, and for all objects o, o ∈ A ∩ B ↔ o ∈ B ∩ A. Suppose that an object o is in A ∩ B. Then by the definition of ∩, it is in A *and* it is in B. As and is itself commutative, o ∈ B *and* o ∈ A, so o ∈ B ∩ A. The reverse proof is true by the same reasoning. The bi-implication holds, and it in turn suffices to prove the equality that we were to show. QED. -/ /- 3. Exercise: Prove that ⊆ is reflexive and transitive. Give a formal statement, a formal proof, and an English language (informal) proof of this fact. -/ theorem subset_refl_trans : ∀ (β : Type) (S L X: set β), (S ⊆ S) ∧ ((S ⊆ L) → (L ⊆ X) → (S ⊆ X)) := begin intros, split, -- apply and.intro _ _, -- left side of ∧ assume x h, assumption, -- right side of ∧ assume h k, assume v n, have l := h n, -- modus ponens have x := k l, -- modus ponens assumption, end /- To show (S ⊆ S) ∧ ((S ⊆ L) → (L ⊆ X) → (S ⊆ X)), it will suffice to prove (S ⊆ S) and S ⊆ L) → (L ⊆ X) → (S ⊆ X). To show S ⊆ S, it will suffice (by the definition of ⊆) to show ∀ o, o ∈ S → o ∈ S. To prove that, assume o is an arbitrary object and that o ∈ S. The conclusion, o ∈ S, is now true by assumption. So ∀ o, o ∈ S → o ∈ S, and this is the very definition of S ⊆ S. We now turn to the second conjunct. We are to show that (S ⊆ L) → (L ⊆ X) → (S ⊆ X). To prove it, we assume that (S ⊆ L) and (L ⊆ X) and we need to show that S ⊆ X. By the definition of ⊆, we have to show that ∀ o, o ∈ S → o ∈ X. To prove this we assume that o is an arbitrary object and that o ∈ S, and we must show o ∈ X. Combining o ∈ S with S ⊆ L, we can conclude that o ∈ L (again by applying the definition of ⊆). Combining this fact with the fact that L ⊆ X, we can conclude that o ∈ X. We have thus showing that for any object, o, if o ∈ S then o ∈ X, which is the definition of S ⊆ X, so ⊆ is transitive. -/ /- 4. Exercise: Prove that ∪ and ∩ are associative. Give a formal statement, a formal proof, and an English language (informal) proof of this fact. -/ lemma inter_assoc : ∀ {β : Type} (a b c: set β), (a ∩ b) ∩ c = a ∩ (b ∩ c) := begin intros, apply set.ext, assume x, split, -- forward assume h, cases h with l r, cases l with ll lr, exact and.intro ll (and.intro lr r), -- backward assume h, cases h with l r, cases r with rl rr, exact and.intro (and.intro l rl) rr, end lemma union_assoc : ∀ {β : Type} (a b c: set β), (a ∪ b) ∪ c = a ∪ (b ∪ c) := begin intros, apply set.ext, assume x, split, -- forward assume h, cases h with l r, cases l with ll lr, -- x ∈ a exact or.inl ll, -- x ∈ b exact or.inr (or.inl lr), -- x ∈ c exact or.inr (or.inr r), -- backward assume h, cases h with l r, -- x ∈ a apply or.inl _, -- what is associativity of ∨? apply or.inl _, assumption, -- x ∈ b ∪ c cases r with l r, -- x ∈ b apply or.inl _, exact or.inr l, -- x ∈ c apply or.inr _, assumption, end theorem inter_and_union_assoc : ∀ (β : Type) (a b c: set β), (a ∪ b) ∪ c = a ∪ (b ∪ c) ∧ (a ∩ b) ∩ c = a ∩ (b ∩ c) := begin intros, split, -- applies and.intro in this context exact union_assoc a b c, -- univ specialization exact inter_assoc a b c, -- univ specialization end /- This example illustrates an important point: it is often very helpful to prove a few mini- theorems, which we call lemmas, in a bottom-up manner, that can then be combined to give the desired overall proof. -/ /- Assignment: read (at least skim) the Sections 1 and 2 of the Wikipedia page on set identities: https://en.wikipedia.org/wiki/List_of_set_identities_and_relations There, , among *many* other facts, you will find definitions of left and right distributivity. To complete the remainder of this assignment, you need to understand what it means for one operator to be left- (or right-) distributive over another. -/ /- Exercise: Formally state, and prove, formally and informally, that ∩ is left-distributive over ∩. -/ theorem inter_left_over_inter : ∀ {β : Type} (a b c : set β), a ∩ (b ∩ c) = (a ∩ b) ∩ (a ∩ c) := begin intros, apply set.ext, assume x, split, assume h, cases h with xa xbc, cases xbc with xb xc, exact and.intro (and.intro _ _) (and.intro _ _) -- etc end /- Exercise: Formally state and prove, formally and informally that ∪ is left-distributive over ∩. -/ theorem union_left_over_inter : ∀ {β : Type} (a b c : set β), a ∩ (b ∩ c) = (a ∩ b) ∩ (a ∩ c) := begin intros, apply set.ext, assume x, split, assume h, cases h with xa xbc, cases xbc with xb xc, apply and.intro, apply and.intro, exact xa, exact xb, split, exact xa, exact xc, -- etc. admit, end example : ∀ {α : Type} (a: α) (L M N: set α), L ⊆ M ↔ (a ∈ L → a ∈ M) := begin intros, split, assume h k, exact h k, assume h, assume x xl, -- stuck end example : ∀ {α : Type} (L M: set α), L ⊆ M ↔ ∀ (a : α), (a ∈ L → a ∈ M) := begin intros, split, assume h, assumption, assume h, assumption, end
c19ccade421fe7db341ef4325d666954622de81b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/Mod_.lean
d3f89f976018c59df4ae571fed51b15de6175003
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,757
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.Mon_ /-! # The category of module objects over a monoid object. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes v₁ v₂ u₁ u₂ open category_theory open category_theory.monoidal_category variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] variables {C} /-- A module object for a monoid object, all internal to some monoidal category. -/ structure Mod_ (A : Mon_ C) := (X : C) (act : A.X ⊗ X ⟶ X) (one_act' : (A.one ⊗ 𝟙 X) ≫ act = (λ_ X).hom . obviously) (assoc' : (A.mul ⊗ 𝟙 X) ≫ act = (α_ A.X A.X X).hom ≫ (𝟙 A.X ⊗ act) ≫ act . obviously) restate_axiom Mod_.one_act' restate_axiom Mod_.assoc' attribute [simp, reassoc] Mod_.one_act Mod_.assoc namespace Mod_ variables {A : Mon_ C} (M : Mod_ A) lemma assoc_flip : (𝟙 A.X ⊗ M.act) ≫ M.act = (α_ A.X A.X M.X).inv ≫ (A.mul ⊗ 𝟙 M.X) ≫ M.act := by simp /-- A morphism of module objects. -/ @[ext] structure hom (M N : Mod_ A) := (hom : M.X ⟶ N.X) (act_hom' : M.act ≫ hom = (𝟙 A.X ⊗ hom) ≫ N.act . obviously) restate_axiom hom.act_hom' attribute [simp, reassoc] hom.act_hom /-- The identity morphism on a module object. -/ @[simps] def id (M : Mod_ A) : hom M M := { hom := 𝟙 M.X, } instance hom_inhabited (M : Mod_ A) : inhabited (hom M M) := ⟨id M⟩ /-- Composition of module object morphisms. -/ @[simps] def comp {M N O : Mod_ A} (f : hom M N) (g : hom N O) : hom M O := { hom := f.hom ≫ g.hom, } instance : category (Mod_ A) := { hom := λ M N, hom M N, id := id, comp := λ M N O f g, comp f g, } @[simp] lemma id_hom' (M : Mod_ A) : (𝟙 M : hom M M).hom = 𝟙 M.X := rfl @[simp] lemma comp_hom' {M N K : Mod_ A} (f : M ⟶ N) (g : N ⟶ K) : (f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl variables (A) /-- A monoid object as a module over itself. -/ @[simps] def regular : Mod_ A := { X := A.X, act := A.mul, } instance : inhabited (Mod_ A) := ⟨regular A⟩ /-- The forgetful functor from module objects to the ambient category. -/ def forget : Mod_ A ⥤ C := { obj := λ A, A.X, map := λ A B f, f.hom, } open category_theory.monoidal_category /-- A morphism of monoid objects induces a "restriction" or "comap" functor between the categories of module objects. -/ @[simps] def comap {A B : Mon_ C} (f : A ⟶ B) : Mod_ B ⥤ Mod_ A := { obj := λ M, { X := M.X, act := (f.hom ⊗ 𝟙 M.X) ≫ M.act, one_act' := begin slice_lhs 1 2 { rw [←comp_tensor_id], }, rw [f.one_hom, one_act], end, assoc' := begin -- oh, for homotopy.io in a widget! slice_rhs 2 3 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, rw id_tensor_comp, slice_rhs 4 5 { rw Mod_.assoc_flip, }, slice_rhs 3 4 { rw associator_inv_naturality, }, slice_rhs 2 3 { rw [←tensor_id, associator_inv_naturality], }, slice_rhs 1 3 { rw [iso.hom_inv_id_assoc], }, slice_rhs 1 2 { rw [←comp_tensor_id, tensor_id_comp_id_tensor], }, slice_rhs 1 2 { rw [←comp_tensor_id, ←f.mul_hom], }, rw [comp_tensor_id, category.assoc], end, }, map := λ M N g, { hom := g.hom, act_hom' := begin dsimp, slice_rhs 1 2 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_rhs 2 3 { rw ←g.act_hom, }, rw category.assoc, end }, } -- Lots more could be said about `comap`, e.g. how it interacts with -- identities, compositions, and equalities of monoid object morphisms. end Mod_
0673a9258f629a241e1e46cc3c877c256c270837
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finite/set.lean
9436d239c7d16b28b83e7bfac2e3ebf40e1253d7
[ "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
883
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 data.fintype.card /-! # Lemmas about `finite` and `set`s > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove two lemmas about `finite` and `set`s. ## Tags finiteness, finite sets -/ open set universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} lemma finite.set.finite_of_finite_image (s : set α) {f : α → β} (h : s.inj_on f) [finite (f '' s)] : finite s := finite.of_equiv _ (equiv.of_bijective _ h.bij_on_image.bijective).symm lemma finite.of_injective_finite_range {f : ι → α} (hf : function.injective f) [finite (range f)] : finite ι := finite.of_injective (set.range_factorization f) (hf.cod_restrict _)
fa92edcf2c9988d78ee722073d5479e608435e4c
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/examples/invoke.lean
e56fce347604f689f8bf07d7a4c16c1d12d55641
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
1,379
lean
import data.cpi.semantics.basic import data.cpi.semantics.with_normalise open cpi open cpi.species open_locale normalise def aff : affinity ℚ := { arity := 2, f := λ x y, if h : (x = 0 ∧ y = 1) ∨ (y = 0 ∧ x = 1) then some (1/2) else none, symm := λ x y, begin by_cases x = 0 ∧ y = 1 ∨ y = 0 ∧ x = 1, simp only [dif_pos h, dif_pos (or.swap h)], simp only [dif_neg h, dif_neg (h ∘ or.swap)], end } def ω : context := context.extend 0 $ context.extend 0 context.nil def A : reference 0 ω := reference.extend (reference.zero 0) def B : reference 0 ω := reference.zero 0 def Γ : context := context.extend aff.arity context.nil def a : name Γ := name.zero ⟨ 0, nat.succ_pos 1 ⟩ def b : name Γ := name.zero ⟨ 1, lt_add_one 1 ⟩ local notation a ` ⬝' ` b := whole.cons a b whole.empty def ℓ : lookup ℚ ω Γ | ._ (reference.zero n) := species.rename name.extend (a # ⬝' (apply A vector.nil |ₛ apply A vector.nil)) | ._ (reference.extend n) := species.rename name.extend (b # ⬝' nil) def C : choices ℚ ω Γ := (τ@(1/6) ⬝' apply B vector.nil) def conc := function.embedding.refl ℚ def immediate_ABC : process_space ℚ ℚ ω Γ := process_immediate aff ℓ conc (1 ◯ (apply A vector.nil) |ₚ 1 ◯ (apply B vector.nil) |ₚ 1 ◯ (Σ# C)) #eval immediate_ABC
ec3d83aaa6369d38d8d83128f804667162c64a88
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/lcnfBinderNameBug.lean
da8f895c4bdc57c63d8da4332d0a0e24b5e15102
[ "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
152
lean
import Lean def test (a : Nat) := let foo := match a with | .zero => a | .succ b => b Nat.add foo .zero #eval Lean.Compiler.compile #[``test]
8fb446f8c4894208e1b043fe2bab0b632f2ae777
43390109ab88557e6090f3245c47479c123ee500
/src/inner_product_spaces/norm_space.lean
e6df4c27d3f899c21d54c4ab4dfd1a90cdf88b67
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,972
lean
import linear_algebra.basic algebra.field data.complex.basic data.real.basic analysis.metric_space analysis.topology.uniform_space open vector_space field set complex real universes u v w class semi_norm_space (V : Type u) extends module ℂ V := (N : V → ℝ) (semi_norm_nonneg : ∀ (x : V), N(x) ≥ 0) (semi_norm_sub_add : ∀ (x y : V), N(x + y) ≤ N(x) + N(y)) (semi_norm_abs_hom : ∀ (x : V), ∀ (a : ℂ), N(a • x) = abs(a)*N(x)) class norm_space (V : Type u) extends module ℂ V := (N : V → ℝ) (norm_nonneg : ∀ (x : V), N(x) ≥ 0) (norm_sub_add : ∀ (x y : V), N(x + y) ≤ N(x) + N(y)) (norm_abs_hom : ∀ (x : V), ∀ (a : ℂ), N(a • x) = abs(a)*N(x)) (norm_pos_def : ∀ (x : V), N(x) = (0 : ℝ) ↔ x = (0 : V)) open norm_space variables {V : Type u} [norm_space V] @[simp] lemma norm_zero : N(0 : V) = 0 := (norm_pos_def 0).mpr (refl 0) @[simp] lemma norm_neg (x : V) : N(-x) = N(x) := begin rw ←neg_one_smul, rw norm_abs_hom, simp, end lemma norm_ne_zero_iff_ne_zero (x : V) : N(x) ≠ 0 ↔ x ≠ 0 := --⟨λ H, (iff_false_left H).mp (norm_pos_def x), λ H, (iff_false_right H).mp (norm_pos_def x)⟩ begin split, intros H, exact (iff_false_left H).mp (norm_pos_def x), intros H, exact (iff_false_right H).mp (norm_pos_def x), end theorem norm_sub_le_sub_norm (x y : V) : complex.abs(N(x) - N(y)) ≤ N(x - y) := begin rw ←of_real_sub, rw abs_of_real, rw abs_le, split, ring, have Hy : N((y - x) + x) = N(y), simp, have H1 : N((y - x) + x) ≤ N(y - x) + N(x), exact norm_sub_add (y - x) (x), rw Hy at H1, rw ←(add_le_add_iff_right (-N(x))) at H1, ring at H1, rw [←neg_sub, norm_neg], rw neg_le, ring, exact H1, have Hx : N((x - y) + y) = N(x), simp, have H2 : N((x - y) + y) ≤ N(x - y) + N(y), exact norm_sub_add (x - y) (y), rw Hx at H2, rw ←(add_le_add_iff_right (-N(y))) at H2, ring at H2, exact H2, end noncomputable def norm_dist (x y : V) := N(x - y) noncomputable instance to_metric_space : has_coe (norm_space V) (metric_space V) := ⟨λh, { dist := norm_dist, dist_self := begin intros, dunfold norm_dist, simp, end, eq_of_dist_eq_zero := begin dunfold norm_dist, intros x y H, exact sub_eq_zero.mp ((norm_pos_def (x - y)).mp H), end, dist_comm := begin intros, dunfold norm_dist, rw ←neg_sub, rw norm_neg, end, dist_triangle := begin dunfold norm_dist, intros, have H : x - z = (x - y) + (y - z), simp, rw H, exact norm_sub_add (x - y) (y - z), end, } ⟩ def is_normalised (x : V) := N(x) = 1 noncomputable def normalise (x : V) := ↑(N(x))⁻¹ • x def normalise_set : set V → set V := image(normalise) lemma normalised_linear_indep (s : set V) : linear_independent s → linear_independent (normalise_set s) := begin dunfold linear_independent, intros H1 l H3 H4, have H5 : ∀ (x : V), x ∉ s → x ∈ normalise_set s, intros x hx, end #print finsupp.sum #print finsupp #print coe_fn lemma normalised_span_spans (s : set V) : span s = span (normalise_set s) := begin rw set_eq_def, intros, dunfold span, split, intros H, rw mem_set_of_eq at H, apply exists.elim H, intros v Hv, admit, admit, end theorem exists_normalised_basis : ∃ (b : set V), is_basis b ∧ ∀ (x : V), x ∈ b → is_normalised x := begin have H1 : ∃ (b : set V), is_basis b, exact exists_is_basis V, apply exists.elim H1, intros b Hb, exact exists.intro (normalise_set b) (and.intro (normalised_basis_is_basis b Hb) (normalise_set_normalises b (zero_not_mem_of_linear_independent (zero_ne_one ℂ) Hb.left))), end noncomputable instance complex_is_norm_space : norm_space ℂ := { N := abs, norm_nonneg := abs_nonneg, norm_sub_add := by exact abs_add, norm_abs_hom := by simp, norm_pos_def := by simp; exact abs_eq_zero, }
1a622605460da62f5a37e8042a7f187580c48a46
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/choose/basic.lean
811b306c9c83d2c6bf353738504917b1a17b43f0
[ "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
12,021
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Bhavik Mehta -/ import data.nat.factorial.basic /-! # Binomial coefficients This file defines binomial coefficients and proves simple lemmas (i.e. those not requiring more imports). ## Main definition and results * `nat.choose`: binomial coefficients, defined inductively * `nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)` * `nat.choose_symm`: symmetry of binomial coefficients * `nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k` * `nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2` * `nat.desc_factorial_eq_factorial_mul_choose`: Relates binomial coefficients to the descending factorial. This is used to prove `nat.choose_le_pow` and variants. We provide similar statements for the ascending factorial. -/ open_locale nat namespace nat /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, add_tsub_cancel_right, mul_comm], cases n; refl, apply zero_lt_succ end /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [nat.eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_factorial_mul_factorial : ∀ {n k}, k ≤ n → choose n k * k! * (n - k)! = n! | 0 _ hk := by simp [nat.eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * k.succ! * (n-k)! = (k + 1) * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk); simp [factorial_succ, mul_comm, mul_left_comm], have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ], have h₂ : choose n (succ k) * k.succ! * ((n - k) * (n - k.succ)!) = (n - k) * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁); simp [factorial_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * n! ≤ n * n! := nat.mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, add_mul, tsub_mul, factorial_succ, ← add_tsub_assoc_of_le h₃, add_assoc, ← add_mul, add_tsub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, tsub_self] } end lemma choose_mul {n k s : ℕ} (hkn : k ≤ n) (hsk : s ≤ k) : n.choose k * k.choose s = n.choose s * (n - s).choose (k - s) := begin have h : 0 < (n - k)! * (k - s)! * s! := mul_pos (mul_pos (factorial_pos _) (factorial_pos _)) (factorial_pos _), refine eq_of_mul_eq_mul_right h _, calc n.choose k * k.choose s * ((n - k)! * (k - s)! * s!) = n.choose k * (k.choose s * s! * (k - s)!) * (n - k)! : by rw [mul_assoc, mul_assoc, mul_assoc, mul_assoc _ s!, mul_assoc, mul_comm (n - k)!, mul_comm s!] ... = n! : by rw [choose_mul_factorial_mul_factorial hsk, choose_mul_factorial_mul_factorial hkn] ... = n.choose s * s! * ((n - s).choose (k - s) * (k - s)! * (n - s - (k - s))!) : by rw [choose_mul_factorial_mul_factorial (tsub_le_tsub_right hkn _), choose_mul_factorial_mul_factorial (hsk.trans hkn)] ... = n.choose s * (n - s).choose (k - s) * ((n - k)! * (k - s)! * s!) : by rw [tsub_tsub_tsub_cancel_right hsk, mul_assoc, mul_left_comm s!, mul_assoc, mul_comm (k - s)!, mul_comm s!, mul_right_comm, ←mul_assoc] end theorem choose_eq_factorial_div_factorial {n k : ℕ} (hk : k ≤ n) : choose n k = n! / (k! * (n - k)!) := begin rw [← choose_mul_factorial_mul_factorial hk, mul_assoc], exact (mul_div_left _ (mul_pos (factorial_pos _) (factorial_pos _))).symm end lemma add_choose (i j : ℕ) : (i + j).choose j = (i + j)! / (i! * j!) := by rw [choose_eq_factorial_div_factorial (nat.le_add_left j i), add_tsub_cancel_right, mul_comm] lemma add_choose_mul_factorial_mul_factorial (i j : ℕ) : (i + j).choose j * i! * j! = (i + j)! := by rw [← choose_mul_factorial_mul_factorial (nat.le_add_left _ _), add_tsub_cancel_right, mul_right_comm] theorem factorial_mul_factorial_dvd_factorial {n k : ℕ} (hk : k ≤ n) : k! * (n - k)! ∣ n! := by rw [←choose_mul_factorial_mul_factorial hk, mul_assoc]; exact dvd_mul_left _ _ lemma factorial_mul_factorial_dvd_factorial_add (i j : ℕ) : i! * j! ∣ (i + j)! := begin convert factorial_mul_factorial_dvd_factorial (le.intro rfl), rw add_tsub_cancel_left end @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_factorial_div_factorial hk, choose_eq_factorial_div_factorial (nat.sub_le _ _), tsub_tsub_cancel_of_le hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw add_tsub_cancel_right} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_symm_half (m : ℕ) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by { apply choose_symm_of_eq_add, rw [add_comm m 1, add_assoc 1 m m, add_comm (2 * m) 1, two_mul m] } lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← tsub_eq_of_eq_add_rev e, mul_comm, ← mul_tsub, add_tsub_add_eq_tsub_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, obtain hk | hk := le_or_lt (k + 1) (n + 1), { rw [choose_succ_succ, add_mul, succ_sub_succ, ←choose_succ_right_eq, ←succ_sub_succ, mul_tsub, add_tsub_cancel_of_le (nat.mul_le_mul_left _ hk)] }, rw [choose_eq_zero_of_lt hk, choose_eq_zero_of_lt (n.lt_succ_self.trans hk), zero_mul, zero_mul], end lemma asc_factorial_eq_factorial_mul_choose (n k : ℕ) : n.asc_factorial k = k! * (n + k).choose k := begin rw mul_comm, apply mul_right_cancel₀ (factorial_ne_zero (n + k - k)), rw [choose_mul_factorial_mul_factorial, add_tsub_cancel_right, ←factorial_mul_asc_factorial, mul_comm], exact nat.le_add_left k n, end lemma factorial_dvd_asc_factorial (n k : ℕ) : k! ∣ n.asc_factorial k := ⟨(n+k).choose k, asc_factorial_eq_factorial_mul_choose _ _⟩ lemma choose_eq_asc_factorial_div_factorial (n k : ℕ) : (n + k).choose k = n.asc_factorial k / k! := begin apply mul_left_cancel₀ (factorial_ne_zero k), rw ←asc_factorial_eq_factorial_mul_choose, exact (nat.mul_div_cancel' $ factorial_dvd_asc_factorial _ _).symm, end lemma desc_factorial_eq_factorial_mul_choose (n k : ℕ) : n.desc_factorial k = k! * n.choose k := begin obtain h | h := nat.lt_or_ge n k, { rw [desc_factorial_eq_zero_iff_lt.2 h, choose_eq_zero_of_lt h, mul_zero] }, rw mul_comm, apply mul_right_cancel₀ (factorial_ne_zero (n - k)), rw [choose_mul_factorial_mul_factorial h, ←factorial_mul_desc_factorial h, mul_comm], end lemma factorial_dvd_desc_factorial (n k : ℕ) : k! ∣ n.desc_factorial k := ⟨n.choose k, desc_factorial_eq_factorial_mul_choose _ _⟩ lemma choose_eq_desc_factorial_div_factorial (n k : ℕ) : n.choose k = n.desc_factorial k / k! := begin apply mul_left_cancel₀ (factorial_ne_zero k), rw ←desc_factorial_eq_factorial_mul_choose, exact (nat.mul_div_cancel' $ factorial_dvd_desc_factorial _ _).symm, end /-! ### Inequalities -/ /-- Show that `nat.choose` is increasing for small values of the right argument. -/ lemma choose_le_succ_of_lt_half_left {r n : ℕ} (h : r < n/2) : choose n r ≤ choose n (r+1) := begin refine le_of_mul_le_mul_right _ (lt_tsub_iff_left.mpr (lt_of_lt_of_le h (n.div_le_self 2))), rw ← choose_succ_right_eq, apply nat.mul_le_mul_left, rw [← nat.lt_iff_add_one_le, lt_tsub_iff_left, ← mul_two], exact lt_of_lt_of_le (mul_lt_mul_of_pos_right h zero_lt_two) (n.div_mul_le_self 2), end /-- Show that for small values of the right argument, the middle value is largest. -/ private lemma choose_le_middle_of_le_half_left {n r : ℕ} (hr : r ≤ n/2) : choose n r ≤ choose n (n/2) := decreasing_induction (λ _ k a, (eq_or_lt_of_le a).elim (λ t, t.symm ▸ le_refl _) (λ h, (choose_le_succ_of_lt_half_left h).trans (k h))) hr (λ _, le_rfl) hr /-- `choose n r` is maximised when `r` is `n/2`. -/ lemma choose_le_middle (r n : ℕ) : choose n r ≤ choose n (n/2) := begin cases le_or_gt r n with b b, { cases le_or_lt r (n/2) with a h, { apply choose_le_middle_of_le_half_left a }, { rw ← choose_symm b, apply choose_le_middle_of_le_half_left, rw [div_lt_iff_lt_mul' zero_lt_two] at h, rw [le_div_iff_mul_le' zero_lt_two, tsub_mul, tsub_le_iff_tsub_le, mul_two, add_tsub_cancel_right], exact le_of_lt h } }, { rw choose_eq_zero_of_lt b, apply zero_le } end /-! #### Inequalities about increasing the first argument -/ lemma choose_le_succ (a c : ℕ) : choose a c ≤ choose a.succ c := by cases c; simp [nat.choose_succ_succ] lemma choose_le_add (a b c : ℕ) : choose a c ≤ choose (a + b) c := begin induction b with b_n b_ih, { simp, }, exact le_trans b_ih (choose_le_succ (a + b_n) c), end lemma choose_le_choose {a b : ℕ} (c : ℕ) (h : a ≤ b) : choose a c ≤ choose b c := (add_tsub_cancel_of_le h) ▸ choose_le_add a (b - a) c lemma choose_mono (b : ℕ) : monotone (λ a, choose a b) := λ _ _, choose_le_choose b end nat
3969c1d23e75e033f702a15efeae640eeb495772
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/algebra/ordered_field.lean
ce1f099a7554e1a9efd0c51c64458341d5d5e992
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,326
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis -/ import algebra.ordered_ring algebra.field open eq eq.ops namespace algebra structure linear_ordered_field [class] (A : Type) extends linear_ordered_ring A, field A section linear_ordered_field variable {A : Type} variables [s : linear_ordered_field A] {a b c d : A} include s -- helpers for following theorem mul_zero_lt_mul_inv_of_pos (H : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : mul_inv_cancel (ne.symm (ne_of_lt H)) ... = a * (1 / a) : inv_eq_one_div theorem mul_zero_lt_mul_inv_of_neg (H : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : mul_inv_cancel (ne_of_lt H) ... = a * (1 / a) : inv_eq_one_div theorem one_div_pos_of_pos (H : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos H) (le_of_lt H) theorem one_div_neg_of_neg (H : a < 0) : 1 / a < 0 := gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg H) (le_of_lt H) theorem le_mul_of_ge_one_right (Hb : b ≥ 0) (H : a ≥ 1) : b ≤ b * a := mul_one _ ▸ (mul_le_mul_of_nonneg_left H Hb) theorem lt_mul_of_gt_one_right (Hb : b > 0) (H : a > 1) : b < b * a := mul_one _ ▸ (mul_lt_mul_of_pos_left H Hb) theorem one_le_div_iff_le (a : A) {b : A} (Hb : b > 0) : 1 ≤ a / b ↔ b ≤ a := have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb), iff.intro (assume H : 1 ≤ a / b, calc b = b : refl ... ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt Hb) H ... = a : mul_div_cancel' Hb') (assume H : b ≤ a, have Hbinv : 1 / b > 0, from one_div_pos_of_pos Hb, calc 1 = b * (1 / b) : mul_one_div_cancel Hb' ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt Hbinv) ... = a / b : div_eq_mul_one_div) theorem le_of_one_le_div (Hb : b > 0) (H : 1 ≤ a / b) : b ≤ a := (iff.mp (!one_le_div_iff_le Hb)) H theorem one_le_div_of_le (Hb : b > 0) (H : b ≤ a) : 1 ≤ a / b := (iff.mpr (!one_le_div_iff_le Hb)) H theorem one_lt_div_iff_lt (a : A) {b : A} (Hb : b > 0) : 1 < a / b ↔ b < a := have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb), iff.intro (assume H : 1 < a / b, calc b < b * (a / b) : lt_mul_of_gt_one_right Hb H ... = a : mul_div_cancel' Hb') (assume H : b < a, have Hbinv : 1 / b > 0, from one_div_pos_of_pos Hb, calc 1 = b * (1 / b) : mul_one_div_cancel Hb' ... < a * (1 / b) : mul_lt_mul_of_pos_right H Hbinv ... = a / b : div_eq_mul_one_div) theorem lt_of_one_lt_div (Hb : b > 0) (H : 1 < a / b) : b < a := (iff.mp (!one_lt_div_iff_lt Hb)) H theorem one_lt_div_of_lt (Hb : b > 0) (H : b < a) : 1 < a / b := (iff.mpr (!one_lt_div_iff_lt Hb)) H theorem exists_lt (a : A) : ∃ x, x < a := have H : a - 1 < a, from add_lt_of_le_of_neg (le.refl _) zero_gt_neg_one, exists.intro _ H theorem exists_gt (a : A) : ∃ x, x > a := have H : a + 1 > a, from lt_add_of_le_of_pos (le.refl _) zero_lt_one, exists.intro _ H -- the following theorems amount to four iffs, for <, ≤, ≥, >. theorem mul_le_of_le_div (Hc : 0 < c) (H : a ≤ b / c) : a * c ≤ b := !div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_le_mul_of_nonneg_right H (le_of_lt Hc) theorem le_div_of_mul_le (Hc : 0 < c) (H : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : !mul_mul_div (ne.symm (ne_of_lt Hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hc)) ... = b / c : div_eq_mul_one_div theorem mul_lt_of_lt_div (Hc : 0 < c) (H : a < b / c) : a * c < b := !div_mul_cancel (ne.symm (ne_of_lt Hc)) ▸ mul_lt_mul_of_pos_right H Hc theorem lt_div_of_mul_lt (Hc : 0 < c) (H : a * c < b) : a < b / c := calc a = a * c * (1 / c) : !mul_mul_div (ne.symm (ne_of_lt Hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc) ... = b / c : div_eq_mul_one_div theorem mul_le_of_div_le_of_neg (Hc : c < 0) (H : b / c ≤ a) : a * c ≤ b := !div_mul_cancel (ne_of_lt Hc) ▸ mul_le_mul_of_nonpos_right H (le_of_lt Hc) theorem div_le_of_mul_le_of_neg (Hc : c < 0) (H : a * c ≤ b) : b / c ≤ a := calc a = a * c * (1 / c) : !mul_mul_div (ne_of_lt Hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right H (le_of_lt (one_div_neg_of_neg Hc)) ... = b / c : div_eq_mul_one_div theorem mul_lt_of_gt_div_of_neg (Hc : c < 0) (H : a > b / c) : a * c < b := !div_mul_cancel (ne_of_lt Hc) ▸ mul_lt_mul_of_neg_right H Hc theorem div_lt_of_mul_gt_of_neg (Hc : c < 0) (H : a * c < b) : b / c < a := calc a = a * c * (1 / c) : !mul_mul_div (ne_of_lt Hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right H (one_div_neg_of_neg Hc) ... = b / c : div_eq_mul_one_div theorem div_le_of_le_mul (Hb : b > 0) (H : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hb)) ... = (b * c) / b : div_eq_mul_one_div ... = c : mul_div_cancel_left (ne.symm (ne_of_lt Hb)) theorem le_mul_of_div_le (Hc : c > 0) (H : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : !div_mul_cancel (ne.symm (ne_of_lt Hc)) ... ≤ b * c : mul_le_mul_of_nonneg_right H (le_of_lt Hc) -- following these in the isabelle file, there are 8 biconditionals for the above with - signs -- skipping for now theorem mul_sub_mul_div_mul_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c < b / d) : (a * d - b * c) / (c * d) < 0 := have H1 : a / c - b / d < 0, from calc a / c - b / d < b / d - b / d : sub_lt_sub_right H ... = 0 : sub_self, calc 0 > a / c - b / d : H1 ... = (a * d - c * b) / (c * d) : !div_sub_div Hc Hd ... = (a * d - b * c) / (c * d) : mul.comm theorem mul_sub_mul_div_mul_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c ≤ b / d) : (a * d - b * c) / (c * d) ≤ 0 := have H1 : a / c - b / d ≤ 0, from calc a / c - b / d ≤ b / d - b / d : sub_le_sub_right H ... = 0 : sub_self, calc 0 ≥ a / c - b / d : H1 ... = (a * d - c * b) / (c * d) : !div_sub_div Hc Hd ... = (a * d - b * c) / (c * d) : mul.comm theorem div_lt_div_of_mul_sub_mul_div_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : (a * d - b * c) / (c * d) < 0) : a / c < b / d := assert H1 : (a * d - c * b) / (c * d) < 0, by rewrite [mul.comm c b]; exact H, assert H2 : a / c - b / d < 0, by rewrite [!div_sub_div Hc Hd]; exact H1, assert H3 : a / c - b / d + b / d < 0 + b / d, from add_lt_add_right H2 _, begin rewrite [zero_add at H3, sub_eq_add_neg at H3, neg_add_cancel_right at H3], exact H3 end theorem div_le_div_of_mul_sub_mul_div_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := assert H1 : (a * d - c * b) / (c * d) ≤ 0, by rewrite [mul.comm c b]; exact H, assert H2 : a / c - b / d ≤ 0, by rewrite [!div_sub_div Hc Hd]; exact H1, assert H3 : a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right H2 _, begin rewrite [zero_add at H3, sub_eq_add_neg at H3, neg_add_cancel_right at H3], exact H3 end theorem div_pos_of_pos_of_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a / b := begin rewrite div_eq_mul_one_div, apply mul_pos, exact Ha, apply one_div_pos_of_pos, exact Hb end theorem div_nonneg_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 ≤ a / b := begin rewrite div_eq_mul_one_div, apply mul_nonneg, exact Ha, apply le_of_lt, apply one_div_pos_of_pos, exact Hb end theorem div_neg_of_neg_of_pos (Ha : a < 0) (Hb : 0 < b) : a / b < 0:= begin rewrite div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, exact Ha, apply one_div_pos_of_pos, exact Hb end theorem div_nonpos_of_nonpos_of_pos (Ha : a ≤ 0) (Hb : 0 < b) : a / b ≤ 0 := begin rewrite div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, exact Ha, apply le_of_lt, apply one_div_pos_of_pos, exact Hb end theorem div_neg_of_pos_of_neg (Ha : 0 < a) (Hb : b < 0) : a / b < 0 := begin rewrite div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, exact Ha, apply one_div_neg_of_neg, exact Hb end theorem div_nonpos_of_nonneg_of_neg (Ha : 0 ≤ a) (Hb : b < 0) : a / b ≤ 0 := begin rewrite div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, exact Ha, apply le_of_lt, apply one_div_neg_of_neg, exact Hb end theorem div_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a / b := begin rewrite div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, exact Ha, apply one_div_neg_of_neg, exact Hb end theorem div_nonneg_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : 0 ≤ a / b := begin rewrite div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, exact Ha, apply le_of_lt, apply one_div_neg_of_neg, exact Hb end theorem div_lt_div_of_lt_of_pos (H : a < b) (Hc : 0 < c) : a / c < b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc) end theorem div_le_div_of_le_of_pos (H : a ≤ b) (Hc : 0 < c) : a / c ≤ b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hc)) end theorem div_lt_div_of_lt_of_neg (H : b < a) (Hc : c < 0) : a / c < b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_lt_mul_of_neg_right H (one_div_neg_of_neg Hc) end theorem div_le_div_of_le_of_neg (H : b ≤ a) (Hc : c < 0) : a / c ≤ b / c := begin rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div], exact mul_le_mul_of_nonpos_right H (le_of_lt (one_div_neg_of_neg Hc)) end theorem two_pos : (1 : A) + 1 > 0 := add_pos zero_lt_one zero_lt_one theorem one_add_one_ne_zero : 1 + 1 ≠ (0:A) := ne.symm (ne_of_lt two_pos) theorem two_ne_zero : 2 ≠ (0:A) := by unfold bit0; apply one_add_one_ne_zero theorem add_halves (a : A) : a / 2 + a / 2 = a := calc a / 2 + a / 2 = (a + a) / 2 : by rewrite div_add_div_same ... = (a * 1 + a * 1) / 2 : by rewrite mul_one ... = (a * (1 + 1)) / 2 : by rewrite left_distrib ... = (a * 2) / 2 : by rewrite one_add_one_eq_two ... = a : by rewrite [@mul_div_cancel A _ _ _ two_ne_zero] theorem sub_self_div_two (a : A) : a - a / 2 = a / 2 := by rewrite [-{a}add_halves at {1}, add_sub_cancel] theorem add_midpoint {a b : A} (H : a < b) : a + (b - a) / 2 < b := begin rewrite [-div_sub_div_same, sub_eq_add_neg, {b / 2 + _}add.comm, -add.assoc, -sub_eq_add_neg], apply add_lt_of_lt_sub_right, rewrite *sub_self_div_two, apply div_lt_div_of_lt_of_pos H two_pos end theorem div_two_sub_self (a : A) : a / 2 - a = - (a / 2) := by rewrite [-{a}add_halves at {2}, sub_add_eq_sub_sub, sub_self, zero_sub] theorem add_self_div_two (a : A) : (a + a) / 2 = a := symm (iff.mpr (!eq_div_iff_mul_eq (ne_of_gt (add_pos zero_lt_one zero_lt_one))) (by krewrite [left_distrib, *mul_one])) theorem two_ge_one : (2:A) ≥ 1 := calc (2:A) = 1+1 : one_add_one_eq_two ... ≥ 1+0 : add_le_add_left (le_of_lt zero_lt_one) ... = 1 : add_zero theorem mul_le_mul_of_mul_div_le (H : a * (b / c) ≤ d) (Hc : c > 0) : b * a ≤ d * c := begin rewrite [-mul_div_assoc at H, mul.comm b], apply le_mul_of_div_le Hc H end theorem div_two_lt_of_pos (H : a > 0) : a / (1 + 1) < a := have Ha : a / (1 + 1) > 0, from div_pos_of_pos_of_pos H (add_pos zero_lt_one zero_lt_one), calc a / (1 + 1) < a / (1 + 1) + a / (1 + 1) : lt_add_of_pos_left Ha ... = a : add_halves theorem div_mul_le_div_mul_of_div_le_div_pos {e : A} (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b ≤ c / d) (He : e > 0) : a / (b * e) ≤ c / (d * e) := begin rewrite [!field.div_mul_eq_div_mul_one_div Hb (ne_of_gt He), !field.div_mul_eq_div_mul_one_div Hd (ne_of_gt He)], apply mul_le_mul_of_nonneg_right H, apply le_of_lt, apply one_div_pos_of_pos He end theorem exists_add_lt_and_pos_of_lt (H : b < a) : ∃ c : A, b + c < a ∧ c > 0 := exists.intro ((a - b) / (1 + 1)) (and.intro (assert H2 : a + a > (b + b) + (a - b), from calc a + a > b + a : add_lt_add_right H ... = b + a + b - b : add_sub_cancel ... = b + b + a - b : add.right_comm ... = (b + b) + (a - b) : add_sub, assert H3 : (a + a) / 2 > ((b + b) + (a - b)) / 2, from div_lt_div_of_lt_of_pos H2 two_pos, by rewrite [one_add_one_eq_two, sub_eq_add_neg, add_self_div_two at H3, -div_add_div_same at H3, add_self_div_two at H3]; exact H3) (div_pos_of_pos_of_pos (iff.mpr !sub_pos_iff_lt H) two_pos)) theorem ge_of_forall_ge_sub {a b : A} (H : ∀ ε : A, ε > 0 → a ≥ b - ε) : a ≥ b := begin apply le_of_not_gt, intro Hb, cases exists_add_lt_and_pos_of_lt Hb with [c, Hc], let Hc' := H c (and.right Hc), apply (not_le_of_gt (and.left Hc)) (iff.mpr !le_add_iff_sub_right_le Hc') end end linear_ordered_field structure discrete_linear_ordered_field [class] (A : Type) extends linear_ordered_field A, decidable_linear_ordered_comm_ring A := (inv_zero : inv zero = zero) section discrete_linear_ordered_field variable {A : Type} variables [s : discrete_linear_ordered_field A] {a b c : A} include s definition dec_eq_of_dec_lt : ∀ x y : A, decidable (x = y) := take x y, decidable.by_cases (assume H : x < y, decidable.inr (ne_of_lt H)) (assume H : ¬ x < y, decidable.by_cases (assume H' : y < x, decidable.inr (ne.symm (ne_of_lt H'))) (assume H' : ¬ y < x, decidable.inl (le.antisymm (le_of_not_gt H') (le_of_not_gt H)))) definition discrete_linear_ordered_field.to_discrete_field [trans_instance] [reducible] : discrete_field A := ⦃ discrete_field, s, has_decidable_eq := dec_eq_of_dec_lt⦄ theorem pos_of_one_div_pos (H : 0 < 1 / a) : 0 < a := have H1 : 0 < 1 / (1 / a), from one_div_pos_of_pos H, have H2 : 1 / a ≠ 0, from (assume H3 : 1 / a = 0, have H4 : 1 / (1 / a) = 0, from H3⁻¹ ▸ !div_zero, absurd H4 (ne.symm (ne_of_lt H1))), (division_ring.one_div_one_div (ne_zero_of_one_div_ne_zero H2)) ▸ H1 theorem neg_of_one_div_neg (H : 1 / a < 0) : a < 0 := have H1 : 0 < - (1 / a), from neg_pos_of_neg H, have Ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt H), have H2 : 0 < 1 / (-a), from (division_ring.one_div_neg_eq_neg_one_div Ha)⁻¹ ▸ H1, have H3 : 0 < -a, from pos_of_one_div_pos H2, neg_of_neg_pos H3 theorem le_of_one_div_le_one_div (H : 0 < a) (Hl : 1 / a ≤ 1 / b) : b ≤ a := have Hb : 0 < b, from pos_of_one_div_pos (calc 0 < 1 / a : one_div_pos_of_pos H ... ≤ 1 / b : Hl), have H' : 1 ≤ a / b, from (calc 1 = a / a : div_self (ne.symm (ne_of_lt H)) ... = a * (1 / a) : div_eq_mul_one_div ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_left Hl (le_of_lt H) ... = a / b : div_eq_mul_one_div ), le_of_one_le_div Hb H' theorem le_of_one_div_le_one_div_of_neg (H : b < 0) (Hl : 1 / a ≤ 1 / b) : b ≤ a := assert Ha : a ≠ 0, from ne_of_lt (neg_of_one_div_neg (calc 1 / a ≤ 1 / b : Hl ... < 0 : one_div_neg_of_neg H)), have H' : -b > 0, from neg_pos_of_neg H, have Hl' : - (1 / b) ≤ - (1 / a), from neg_le_neg Hl, have Hl'' : 1 / - b ≤ 1 / - a, from calc 1 / -b = - (1 / b) : by rewrite [division_ring.one_div_neg_eq_neg_one_div (ne_of_lt H)] ... ≤ - (1 / a) : Hl' ... = 1 / -a : by rewrite [division_ring.one_div_neg_eq_neg_one_div Ha], le_of_neg_le_neg (le_of_one_div_le_one_div H' Hl'') theorem lt_of_one_div_lt_one_div (H : 0 < a) (Hl : 1 / a < 1 / b) : b < a := have Hb : 0 < b, from pos_of_one_div_pos (calc 0 < 1 / a : one_div_pos_of_pos H ... < 1 / b : Hl), have H : 1 < a / b, from (calc 1 = a / a : div_self (ne.symm (ne_of_lt H)) ... = a * (1 / a) : div_eq_mul_one_div ... < a * (1 / b) : mul_lt_mul_of_pos_left Hl H ... = a / b : div_eq_mul_one_div), lt_of_one_lt_div Hb H theorem lt_of_one_div_lt_one_div_of_neg (H : b < 0) (Hl : 1 / a < 1 / b) : b < a := have H1 : b ≤ a, from le_of_one_div_le_one_div_of_neg H (le_of_lt Hl), have Hn : b ≠ a, from (assume Hn' : b = a, have Hl' : 1 / a = 1 / b, from Hn' ▸ refl _, absurd Hl' (ne_of_lt Hl)), lt_of_le_of_ne H1 Hn theorem one_div_lt_one_div_of_lt (Ha : 0 < a) (H : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume H', absurd H (not_lt_of_ge (le_of_one_div_le_one_div Ha H'))) theorem one_div_le_one_div_of_le (Ha : 0 < a) (H : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume H', absurd H (not_le_of_gt (lt_of_one_div_lt_one_div Ha H'))) theorem one_div_lt_one_div_of_lt_of_neg (Hb : b < 0) (H : a < b) : 1 / b < 1 / a := lt_of_not_ge (assume H', absurd H (not_lt_of_ge (le_of_one_div_le_one_div_of_neg Hb H'))) theorem one_div_le_one_div_of_le_of_neg (Hb : b < 0) (H : a ≤ b) : 1 / b ≤ 1 / a := le_of_not_gt (assume H', absurd H (not_le_of_gt (lt_of_one_div_lt_one_div_of_neg Hb H'))) theorem one_lt_one_div (H1 : 0 < a) (H2 : a < 1) : 1 < 1 / a := one_div_one ▸ one_div_lt_one_div_of_lt H1 H2 theorem one_le_one_div (H1 : 0 < a) (H2 : a ≤ 1) : 1 ≤ 1 / a := one_div_one ▸ one_div_le_one_div_of_le H1 H2 theorem one_div_lt_neg_one (H1 : a < 0) (H2 : -1 < a) : 1 / a < -1 := one_div_neg_one_eq_neg_one ▸ one_div_lt_one_div_of_lt_of_neg H1 H2 theorem one_div_le_neg_one (H1 : a < 0) (H2 : -1 ≤ a) : 1 / a ≤ -1 := one_div_neg_one_eq_neg_one ▸ one_div_le_one_div_of_le_of_neg H1 H2 theorem div_lt_div_of_pos_of_lt_of_pos (Hb : 0 < b) (H : b < a) (Hc : 0 < c) : c / a < c / b := begin apply iff.mp !sub_neg_iff_lt, rewrite [div_eq_mul_one_div, {c / b}div_eq_mul_one_div, -mul_sub_left_distrib], apply mul_neg_of_pos_of_neg, exact Hc, apply iff.mpr !sub_neg_iff_lt, apply one_div_lt_one_div_of_lt, repeat assumption end theorem div_mul_le_div_mul_of_div_le_div_pos' {d e : A} (H : a / b ≤ c / d) (He : e > 0) : a / (b * e) ≤ c / (d * e) := begin rewrite [2 div_mul_eq_div_mul_one_div], apply mul_le_mul_of_nonneg_right H, apply le_of_lt, apply one_div_pos_of_pos He end theorem abs_one_div (a : A) : abs (1 / a) = 1 / abs a := if H : a > 0 then by rewrite [abs_of_pos H, abs_of_pos (one_div_pos_of_pos H)] else (if H' : a < 0 then by rewrite [abs_of_neg H', abs_of_neg (one_div_neg_of_neg H'), -(division_ring.one_div_neg_eq_neg_one_div (ne_of_lt H'))] else assert Heq : a = 0, from eq_of_le_of_ge (le_of_not_gt H) (le_of_not_gt H'), by rewrite [Heq, div_zero, *abs_zero, div_zero]) theorem sign_eq_div_abs (a : A) : sign a = a / (abs a) := decidable.by_cases (suppose a = 0, by subst a; rewrite [zero_div, sign_zero]) (suppose a ≠ 0, have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H), !eq_div_of_mul_eq this !eq_sign_mul_abs⁻¹) end discrete_linear_ordered_field end algebra
946c31e4ddfbba35048feb6874863c8278fc2121
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/derivative.lean
e965a9a62c093dd65a54dd208b9ff40a950598b0
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,303
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import algebra.hom.iterate import data.polynomial.eval /-! # The derivative map on polynomials ## Main definitions * `polynomial.derivative`: The formal derivative of polynomials, expressed as a linear map. -/ noncomputable theory open finset open_locale big_operators classical polynomial namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ} section derivative section semiring variables [semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative : R[X] →ₗ[R] R[X] := { to_fun := λ p, p.sum (λ n a, C (a * n) * X^(n-1)), map_add' := λ p q, by rw sum_add_index; simp only [add_mul, forall_const, ring_hom.map_add, eq_self_iff_true, zero_mul, ring_hom.map_zero], map_smul' := λ a p, by dsimp; rw sum_smul_index; simp only [mul_sum, ← C_mul', mul_assoc, coeff_C_mul, ring_hom.map_mul, forall_const, zero_mul, ring_hom.map_zero, sum] } lemma derivative_apply (p : R[X]) : derivative p = p.sum (λn a, C (a * n) * X^(n - 1)) := rfl lemma coeff_derivative (p : R[X]) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative_apply], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [sum, finset.sum_eq_single (n + 1)], simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul], }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { rw [if_pos (add_tsub_cancel_right n 1).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff], intro h, push_neg at h, simp [h], }, end @[simp] lemma derivative_zero : derivative (0 : R[X]) = 0 := derivative.map_zero @[simp] lemma iterate_derivative_zero {k : ℕ} : derivative^[k] (0 : R[X]) = 0 := begin induction k with k ih, { simp, }, { simp [ih], }, end @[simp] lemma derivative_monomial (a : R) (n : ℕ) : derivative (monomial n a) = monomial (n - 1) (a * n) := by { rw [derivative_apply, sum_monomial_index, C_mul_X_pow_eq_monomial], simp } lemma derivative_C_mul_X_pow (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [C_mul_X_pow_eq_monomial, C_mul_X_pow_eq_monomial, derivative_monomial] @[simp] lemma derivative_X_pow (n : ℕ) : derivative (X ^ n : R[X]) = (n : R[X]) * X ^ (n - 1) := by convert derivative_C_mul_X_pow (1 : R) n; simp @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := by simp [derivative_apply] lemma derivative_of_nat_degree_zero {p : R[X]} (hp : p.nat_degree = 0) : p.derivative = 0 := by rw [eq_C_of_nat_degree_eq_zero hp, derivative_C] @[simp] lemma derivative_X : derivative (X : R[X]) = 1 := (derivative_monomial _ _).trans $ by simp @[simp] lemma derivative_one : derivative (1 : R[X]) = 0 := derivative_C @[simp] lemma derivative_bit0 {a : R[X]} : derivative (bit0 a) = bit0 (derivative a) := by simp [bit0] @[simp] lemma derivative_bit1 {a : R[X]} : derivative (bit1 a) = bit0 (derivative a) := by simp [bit1] @[simp] lemma derivative_add {f g : R[X]} : derivative (f + g) = derivative f + derivative g := derivative.map_add f g @[simp] lemma iterate_derivative_add {f g : R[X]} {k : ℕ} : derivative^[k] (f + g) = (derivative^[k] f) + (derivative^[k] g) := derivative.to_add_monoid_hom.iterate_map_add _ _ _ @[simp] lemma derivative_sum {s : finset ι} {f : ι → R[X]} : derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) := derivative.map_sum @[simp] lemma derivative_smul {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) (p : R[X]) : derivative (s • p) = s • derivative p := derivative.map_smul_of_tower s p @[simp] lemma iterate_derivative_smul {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) (p : R[X]) (k : ℕ) : derivative^[k] (s • p) = s • (derivative^[k] p) := begin induction k with k ih generalizing p, { simp, }, { simp [ih], }, end @[simp] lemma iterate_derivative_C_mul (a : R) (p : R[X]) (k : ℕ) : derivative^[k] (C a * p) = C a * (derivative^[k] p) := by simp_rw [← smul_eq_C_mul, iterate_derivative_smul] theorem of_mem_support_derivative {p : R[X]} {n : ℕ} (h : n ∈ p.derivative.support) : n + 1 ∈ p.support := mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), mem_support_iff.1 h $ show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul] theorem degree_derivative_lt {p : R[X]} (hp : p ≠ 0) : p.derivative.degree < p.degree := (finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le (with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp theorem degree_derivative_le {p : R[X]} : p.derivative.degree ≤ p.degree := if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else (degree_derivative_lt H).le theorem nat_degree_derivative_lt {p : R[X]} (hp : p.nat_degree ≠ 0) : p.derivative.nat_degree < p.nat_degree := begin cases eq_or_ne p.derivative 0 with hp' hp', { rw [hp', polynomial.nat_degree_zero], exact hp.bot_lt }, { rw nat_degree_lt_nat_degree_iff hp', exact degree_derivative_lt (λ h, hp (h.symm ▸ nat_degree_zero)) } end lemma nat_degree_derivative_le (p : R[X]) : p.derivative.nat_degree ≤ p.nat_degree - 1 := begin by_cases p0 : p.nat_degree = 0, { simp [p0, derivative_of_nat_degree_zero] }, { exact nat.le_pred_of_lt (nat_degree_derivative_lt p0) } end @[simp] lemma derivative_cast_nat {n : ℕ} : derivative (n : R[X]) = 0 := begin rw ← map_nat_cast C n, exact derivative_C, end lemma iterate_derivative_eq_zero {p : R[X]} {x : ℕ} (hx : p.nat_degree < x) : polynomial.derivative^[x] p = 0 := begin induction h : p.nat_degree using nat.strong_induction_on with _ ih generalizing p x, subst h, obtain ⟨t, rfl⟩ := nat.exists_eq_succ_of_ne_zero (pos_of_gt hx).ne', rw [function.iterate_succ_apply], by_cases hp : p.nat_degree = 0, { rw [derivative_of_nat_degree_zero hp, iterate_derivative_zero] }, have := nat_degree_derivative_lt hp, exact ih _ this (this.trans_le $ nat.le_of_lt_succ hx) rfl end theorem nat_degree_eq_zero_of_derivative_eq_zero [no_zero_divisors R] [char_zero R] {f : R[X]} (h : f.derivative = 0) : f.nat_degree = 0 := begin rcases eq_or_ne f 0 with rfl | hf, { exact nat_degree_zero }, rw nat_degree_eq_zero_iff_degree_le_zero, by_contra' f_nat_degree_pos, rw [←nat_degree_pos_iff_degree_pos] at f_nat_degree_pos, let m := f.nat_degree - 1, have hm : m + 1 = f.nat_degree := tsub_add_cancel_of_le f_nat_degree_pos, have h2 := coeff_derivative f m, rw polynomial.ext_iff at h, rw [h m, coeff_zero, zero_eq_mul] at h2, replace h2 := h2.resolve_right (λ h2, by norm_cast at h2), rw [hm, ←leading_coeff, leading_coeff_eq_zero] at h2, exact hf h2 end @[simp] lemma derivative_mul {f g : R[X]} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, (n + m) • (C (a * b) * X^((n + m) - 1)))) : begin rw mul_eq_sum_sum, transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact monomial_eq_C_mul_X }, dsimp, rw [← smul_mul_assoc, smul_C, nsmul_eq_mul'], exact derivative_C_mul_X_pow _ _ end ... = f.sum (λn a, g.sum (λm b, (n • (C a * X^(n - 1))) * (C b * X^m) + (C a * X^n) * (m • (C b * X^(m - 1))))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by cases n; cases m; simp_rw [add_smul, mul_smul_comm, smul_mul_assoc, X_pow_mul_assoc, ← mul_assoc, ← C_mul, mul_assoc, ← pow_add]; simp only [nat.add_succ, nat.succ_add, nat.succ_sub_one, zero_smul, add_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, simp only [sum, sum_add_distrib, finset.mul_sum, finset.sum_mul, derivative_apply], simp_rw [← smul_mul_assoc, smul_C, nsmul_eq_mul'], end end semiring section comm_semiring variables [comm_semiring R] lemma derivative_eval (p : R[X]) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp only [derivative_apply, eval_sum, eval_pow, eval_C, eval_X, eval_nat_cast, eval_mul] theorem derivative_pow_succ (p : R[X]) (n : ℕ) : (p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative := nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih, by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul, add_mul (n.succ : R[X]), one_mul, pow_succ', mul_assoc, n.cast_succ] theorem derivative_pow (p : R[X]) (n : ℕ) : (p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative := nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n, by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ] lemma derivative_comp (p q : R[X]) : (p.comp q).derivative = q.derivative * p.derivative.comp q := begin apply polynomial.induction_on' p, { intros p₁ p₂ h₁ h₂, simp [h₁, h₂, mul_add], }, { intros n r, simp only [derivative_pow, derivative_mul, monomial_comp, derivative_monomial, derivative_C, zero_mul, C_eq_nat_cast, zero_add, ring_hom.map_mul], -- is there a tactic for this? (a multiplicative `abel`): rw [mul_comm (derivative q)], simp only [mul_assoc], } end @[simp] theorem derivative_map [comm_semiring S] (p : R[X]) (f : R →+* S) : (p.map f).derivative = p.derivative.map f := polynomial.induction_on p (λ r, by rw [map_C, derivative_C, derivative_C, polynomial.map_zero]) (λ p q ihp ihq, by rw [polynomial.map_add, derivative_add, ihp, ihq, derivative_add, polynomial.map_add]) (λ n r ih, by rw [polynomial.map_mul, polynomial.map_C, polynomial.map_pow, polynomial.map_X, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, polynomial.map_mul, polynomial.map_C, polynomial.map_mul, polynomial.map_pow, polynomial.map_add, polynomial.map_nat_cast, polynomial.map_one, polynomial.map_X]) @[simp] theorem iterate_derivative_map [comm_semiring S] (p : R[X]) (f : R →+* S) (k : ℕ): polynomial.derivative^[k] (p.map f) = (polynomial.derivative^[k] p).map f := begin induction k with k ih generalizing p, { simp, }, { simp [ih], }, end /-- Chain rule for formal derivative of polynomials. -/ theorem derivative_eval₂_C (p q : R[X]) : (p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative := polynomial.induction_on p (λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul]) (λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul]) (λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih, @derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X, add_mul, mul_right_comm]) theorem derivative_prod {s : multiset ι} {f : ι → R[X]} : (multiset.map f s).prod.derivative = (multiset.map (λ i, (multiset.map f (s.erase i)).prod * (f i).derivative) s).sum := begin refine multiset.induction_on s (by simp) (λ i s h, _), rw [multiset.map_cons, multiset.prod_cons, derivative_mul, multiset.map_cons _ i s, multiset.sum_cons, multiset.erase_cons_head, mul_comm (f i).derivative], congr, rw [h, ← add_monoid_hom.coe_mul_left, (add_monoid_hom.mul_left (f i)).map_multiset_sum _, add_monoid_hom.coe_mul_left], simp only [function.comp_app, multiset.map_map], refine congr_arg _ (multiset.map_congr rfl (λ j hj, _)), rw [← mul_assoc, ← multiset.prod_cons, ← multiset.map_cons], by_cases hij : i = j, { simp [hij, ← multiset.prod_cons, ← multiset.map_cons, multiset.cons_erase hj] }, { simp [hij] } end @[simp] lemma iterate_derivative_cast_nat_mul {n k : ℕ} {f : R[X]} : derivative^[k] (n * f) = n * (derivative^[k] f) := by induction k with k ih generalizing f; simp* end comm_semiring section ring variables [ring R] @[simp] lemma derivative_neg (f : R[X]) : derivative (-f) = - derivative f := linear_map.map_neg derivative f @[simp] lemma iterate_derivative_neg {f : R[X]} {k : ℕ} : derivative^[k] (-f) = - (derivative^[k] f) := (@derivative R _).to_add_monoid_hom.iterate_map_neg _ _ @[simp] lemma derivative_sub {f g : R[X]} : derivative (f - g) = derivative f - derivative g := linear_map.map_sub derivative f g @[simp] lemma iterate_derivative_sub {k : ℕ} {f g : R[X]} : derivative^[k] (f - g) = (derivative^[k] f) - (derivative^[k] g) := by induction k with k ih generalizing f g; simp* end ring section comm_ring variables [comm_ring R] lemma derivative_comp_one_sub_X (p : R[X]) : (p.comp (1-X)).derivative = -p.derivative.comp (1-X) := by simp [derivative_comp] @[simp] lemma iterate_derivative_comp_one_sub_X (p : R[X]) (k : ℕ) : derivative^[k] (p.comp (1-X)) = (-1)^k * (derivative^[k] p).comp (1-X) := begin induction k with k ih generalizing p, { simp, }, { simp [ih p.derivative, iterate_derivative_neg, derivative_comp, pow_succ], }, end lemma eval_multiset_prod_X_sub_C_derivative {S : multiset R} {r : R} (hr : r ∈ S) : eval r (multiset.map (λ a, X - C a) S).prod.derivative = (multiset.map (λ a, r - a) (S.erase r)).prod := begin nth_rewrite 0 [← multiset.cons_erase hr], simpa using (eval_ring_hom r).map_multiset_prod (multiset.map (λ a, X - C a) (S.erase r)), end end comm_ring section no_zero_divisors variables [ring R] [no_zero_divisors R] lemma mem_support_derivative [char_zero R] (p : R[X]) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [mem_support_iff, coeff_derivative, ne.def, mul_eq_zero], by { rw [nat.cast_eq_zero], simp only [nat.succ_ne_zero, or_false] } @[simp] lemma degree_derivative_eq [char_zero R] (p : R[X]) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := begin have h0 : p ≠ 0, { contrapose! hp, simp [hp] }, apply le_antisymm, { rw derivative_apply, apply le_trans (degree_sum_le _ _) (sup_le (λ n hn, _)), apply le_trans (degree_C_mul_X_pow_le _ _) (with_bot.coe_le_coe.2 (tsub_le_tsub_right _ _)), apply le_nat_degree_of_mem_supp _ hn }, { refine le_sup _, rw [mem_support_derivative, tsub_add_cancel_of_le, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp } end end no_zero_divisors end derivative end polynomial
41cd5d51cfd2e8d501db6214e2b90436ebbd7f5d
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world10/level4.lean
8d2d2079516c00606f9328a73e9fea3c1e8e4089
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
262
lean
import game.world10.level3 -- hide namespace mynat -- hide /- # Inequality world. ## Level 4: `zero_le` Another easy one. -/ /- Lemma For all naturals $a$, $0\leq a$. -/ lemma zero_le (a : mynat) : 0 ≤ a := begin [nat_num_game] end end mynat -- hide
8951e614da7411b9935cc5d536a933c3308687bc
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/collectDepsIssue.lean
349f2244fc7996435f116377a7a316f81ab11616
[ "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
245
lean
variables {α : Type} in def f (a : α) : List α := _ variable (P : List Nat → List Nat → Prop) in theorem foo (xs : List Nat) : (ns : List Nat) → P xs ns | [] => sorry | (n::ns) => by { cases xs; exact sorry; exact sorry }
52811e9845ab2c758de68d9cf48aec32745d648a
bf532e3e865883a676110e756f800e0ddeb465be
/data/nat/basic.lean
cb28c13821cd7228af9d08f520258b9aaf14ee6f
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,839
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, Leonardo de Moura, Jeremy Avigad, Mario Carneiro Basic operations on the natural numbers. -/ import logic.basic algebra.order data.option universe u namespace nat variables {m n k : ℕ} theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl theorem pos_iff_ne_zero : n > 0 ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ theorem pos_iff_ne_zero' : 0 < n ↔ n ≠ 0 := pos_iff_ne_zero protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : n ≥ m) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] protected theorem lt_of_sub_pos (h : n - m > 0) : m < n := lt_of_not_ge (assume : m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := le_imp_le_iff_lt_imp_lt.1 (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := le_imp_le_iff_lt_imp_lt.1 (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_iff_lt_imp_lt.2 nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_iff_lt_imp_lt.2 nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := le_imp_le_iff_lt_imp_lt.1 nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := le_imp_le_iff_lt_imp_lt.1 nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_iff_lt_imp_lt.2 nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_iff_lt_imp_lt.2 nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt (H : m ≤ k) : n < k - m ↔ m + n < k := ⟨λ h, by have := nat.add_le_add_left h m; rwa [nat.add_sub_cancel' H] at this, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt (H : n ≤ k) : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt H, add_comm] theorem sub_le_left_iff_le_add (H : n ≤ m) : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 (nat.lt_sub_left_iff_add_lt H) theorem sub_le_right_iff_le_add (H : k ≤ m) : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add H, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := le_iff_le_iff_lt_iff_lt.1 (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := le_iff_le_iff_lt_iff_lt.1 (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n ≤ k ↔ m - k ≤ n := (nat.sub_le_left_iff_le_add h₁).trans (nat.sub_le_right_iff_le_add h₂).symm protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma lt_pred_of_succ_lt {n m : ℕ} : succ n < m → n < pred m := @nat.lt_sub_right_of_add_lt n m 1 protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 attribute [simp] nat.div_self protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_right_inj {a b c : ℕ} (ha : a > 0) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : a > 0) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : a > 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_left_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : c > 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_right_inj hc] theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := by dsimp; apply option.bind_eq_some.trans; simp [psub_eq_some] theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, monad.bind_assoc] /- pow -/ theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ, mul_assoc] theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl /- foldl & foldr -/ /-- `foldl op n a` is the `n`-times iterate of `op` on `a`. -/ @[simp] def foldl {α : Sort*} (op : α → α) : ℕ → α → α | 0 a := a | (succ k) a := foldl k (op a) /-- `foldr op n a` is the `n`-times iterate of `op` on `a`. It is provably the same as `foldl` but has different definitional equalities. -/ @[simp] def foldr {α : Sort*} (op : α → α) (a : α) : ℕ → α | 0 := a | (succ k) := op (foldr k) /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, refl end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply le_imp_le_iff_lt_imp_lt.1 (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero'] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl theorem fact_pos : ∀ n, fact n > 0 | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, m > 0 → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) end nat
e7895ce788f8ac9ea5d826ccaaff34e1406516f4
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/borrowBug.lean
fe170eb02ffa58152056ed5a59bd2862f116c7c6
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
359
lean
@[noinline] def g (x : Nat) : Nat × Nat := (x, x) @[noinline] def p (x : Nat) : Bool := x > 10 set_option trace.compiler.ir.rc true def f (x : Nat) (y : Nat) : Bool := let jp (x : Nat) : Bool := -- x must be owned p x || p (x+1); match x with | 0 => let z := g y; jp z.1 | _ => let z := g x; jp z.1 def h (x : Nat) : Bool := -- x must be borrowed x > 5
d160779b6bb596647ea335d520751bc372f92a5b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/buffer/parser/numeral_auto.lean
46903c5977ff44a7a79c340d26cbe15a646317c5
[]
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
3,643
lean
/- Copyright (c) 2020 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.card import Mathlib.PostPort namespace Mathlib /-! # Numeral parsers This file expands on the existing `nat : parser ℕ` to provide parsers into any type `α` that can be represented by a numeral, which relies on `α` having a 0, 1, and addition operation. There are also convenience parsers that ensure that the numeral parsed in is not larger than the cardinality of the type `α` , if it is known that `fintype α`. Additionally, there are convenience parsers that parse in starting from "1", which can be useful for positive ordinals; or parser from a given character or character range. ## Main definitions * 'numeral` : The parser which uses `nat.cast` to map the result of `parser.nat` to the desired `α` * `numeral.of_fintype` : The parser which `guard`s to make sure the parsed numeral is within the cardinality of the target `fintype` type `α`. ## Implementation details When the `numeral` or related parsers are invoked, the desired type is provided explicitly. In many cases, it can be inferred, so one can write, for example ```lean def get_fin : string → fin 5 := sum.elim (λ _, 0) id ∘ parser.run_string (parser.numeral.of_fintype _) ``` In the definitions of the parsers (except for `numeral`), there is an explicit `nat.bin_cast` instead an explicit or implicit `nat.cast` -/ namespace parser /-- Parse a string of digits as a numeral while casting it to target type `α`. -/ def numeral (α : Type) [HasZero α] [HasOne α] [Add α] : parser α := nat.bin_cast <$> nat /-- Parse a string of digits as a numeral while casting it to target type `α`, which has a `[fintype α]` constraint. The parser ensures that the numeral parsed in is within the cardinality of the type `α`. -/ def numeral.of_fintype (α : Type) [HasZero α] [HasOne α] [Add α] [fintype α] : parser α := sorry /-- Parse a string of digits as a numeral while casting it to target type `α`. The parsing starts at "1", so `"1"` is parsed in as `nat.cast 0`. Providing `"0"` to the parser causes a failure. -/ def numeral.from_one (α : Type) [HasZero α] [HasOne α] [Add α] : parser α := sorry /-- Parse a string of digits as a numeral while casting it to target type `α`, which has a `[fintype α]` constraint. The parser ensures that the numeral parsed in is within the cardinality of the type `α`. The parsing starts at "1", so `"1"` is parsed in as `nat.cast 0`. Providing `"0"` to the parser causes a failure. -/ def numeral.from_one.of_fintype (α : Type) [HasZero α] [HasOne α] [Add α] [fintype α] : parser α := sorry /-- Parse a character as a numeral while casting it to target type `α`, The parser ensures that the character parsed in is within the bounds set by `fromc` and `toc`, and subtracts the value of `fromc` from the parsed in character. -/ def numeral.char (α : Type) [HasZero α] [HasOne α] [Add α] (fromc : char) (toc : char) : parser α := sorry /-- Parse a character as a numeral while casting it to target type `α`, which has a `[fintype α]` constraint. The parser ensures that the character parsed in is greater or equal to `fromc` and and subtracts the value of `fromc` from the parsed in character. There is also a check that the resulting value is within the cardinality of the type `α`. -/ def numeral.char.of_fintype (α : Type) [HasZero α] [HasOne α] [Add α] [fintype α] (fromc : char) : parser α := sorry end Mathlib
1b7c3a1da6b664c1c8f17a423d216c8465ebf5e8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/hom/embedding.lean
978feccc9e497b9da2a80986a29ef06b3222e6fa
[ "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
1,548
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group.defs import logic.embedding.basic /-! # The embedding of a cancellative semigroup into itself by multiplication by a fixed element. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/764 > Any changes to this file require a corresponding PR to mathlib4. -/ variables {R : Type*} section left_or_right_cancel_semigroup /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[to_additive "The embedding of a left cancellative additive semigroup into itself by left translation by a fixed element.", simps] def mul_left_embedding {G : Type*} [left_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, g * h, inj' := mul_right_injective g } /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ @[to_additive "The embedding of a right cancellative additive semigroup into itself by right translation by a fixed element.", simps] def mul_right_embedding {G : Type*} [right_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, h * g, inj' := mul_left_injective g } @[to_additive] lemma mul_left_embedding_eq_mul_right_embedding {G : Type*} [cancel_comm_monoid G] (g : G) : mul_left_embedding g = mul_right_embedding g := by { ext, exact mul_comm _ _ } end left_or_right_cancel_semigroup
5bc6ce805985e856d49cb6094b42c108fbed0054
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebraic_geometry/locally_ringed_space/has_colimits.lean
cdb16170c412f49a5bc82332a9cd129667a7f667
[ "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
12,852
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.locally_ringed_space import algebra.category.Ring.constructions import algebraic_geometry.open_immersion import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # Colimits of LocallyRingedSpace We construct the explicit coproducts and coequalizers of `LocallyRingedSpace`. It then follows that `LocallyRingedSpace` has all colimits, and `forget_to_SheafedSpace` preserves them. -/ namespace algebraic_geometry universes v u open category_theory category_theory.limits opposite topological_space namespace SheafedSpace variables {C : Type u} [category.{v} C] [has_limits C] variables {J : Type v} [category.{v} J] (F : J ⥤ SheafedSpace C) lemma is_colimit_exists_rep {c : cocone F} (hc : is_colimit c) (x : c.X) : ∃ (i : J) (y : F.obj i), (c.ι.app i).base y = x := concrete.is_colimit_exists_rep (F ⋙ SheafedSpace.forget _) (is_colimit_of_preserves (SheafedSpace.forget _) hc) x lemma colimit_exists_rep (x : colimit F) : ∃ (i : J) (y : F.obj i), (colimit.ι F i).base y = x := concrete.is_colimit_exists_rep (F ⋙ SheafedSpace.forget _) (is_colimit_of_preserves (SheafedSpace.forget _) (colimit.is_colimit F)) x instance {X Y : SheafedSpace C} (f g : X ⟶ Y) : epi (coequalizer.π f g).base := begin erw ← (show _ = (coequalizer.π f g).base, from ι_comp_coequalizer_comparison f g (SheafedSpace.forget C)), rw ← preserves_coequalizer.iso_hom, apply epi_comp end end SheafedSpace namespace LocallyRingedSpace section has_coproducts variables {ι : Type u} (F : discrete ι ⥤ LocallyRingedSpace.{u}) /-- The explicit coproduct for `F : discrete ι ⥤ LocallyRingedSpace`. -/ noncomputable def coproduct : LocallyRingedSpace := { to_SheafedSpace := colimit (F ⋙ forget_to_SheafedSpace : _), local_ring := λ x, begin obtain ⟨i, y, ⟨⟩⟩ := SheafedSpace.colimit_exists_rep (F ⋙ forget_to_SheafedSpace) x, haveI : _root_.local_ring (((F ⋙ forget_to_SheafedSpace).obj i).to_PresheafedSpace.stalk y) := (F.obj i).local_ring _, exact (as_iso (PresheafedSpace.stalk_map (colimit.ι (F ⋙ forget_to_SheafedSpace) i : _) y) ).symm.CommRing_iso_to_ring_equiv.local_ring end } /-- The explicit coproduct cofan for `F : discrete ι ⥤ LocallyRingedSpace`. -/ noncomputable def coproduct_cofan : cocone F := { X := coproduct F, ι := { app := λ j, ⟨colimit.ι (F ⋙ forget_to_SheafedSpace) j, infer_instance⟩, naturality' := λ j j' f, by { cases j, cases j', tidy, }, } } /-- The explicit coproduct cofan constructed in `coproduct_cofan` is indeed a colimit. -/ noncomputable def coproduct_cofan_is_colimit : is_colimit (coproduct_cofan F) := { desc := λ s, ⟨colimit.desc (F ⋙ forget_to_SheafedSpace) (forget_to_SheafedSpace.map_cocone s), begin intro x, obtain ⟨i, y, ⟨⟩⟩ := SheafedSpace.colimit_exists_rep (F ⋙ forget_to_SheafedSpace) x, have := PresheafedSpace.stalk_map.comp (colimit.ι (F ⋙ forget_to_SheafedSpace) i : _) (colimit.desc (F ⋙ forget_to_SheafedSpace) (forget_to_SheafedSpace.map_cocone s)) y, rw ← is_iso.comp_inv_eq at this, erw [← this, PresheafedSpace.stalk_map.congr_hom _ _ (colimit.ι_desc (forget_to_SheafedSpace.map_cocone s) i : _)], haveI : is_local_ring_hom (PresheafedSpace.stalk_map ((forget_to_SheafedSpace.map_cocone s).ι.app i) y) := (s.ι.app i).2 y, apply_instance end⟩, fac' := λ s j, subtype.eq (colimit.ι_desc _ _), uniq' := λ s f h, subtype.eq (is_colimit.uniq _ (forget_to_SheafedSpace.map_cocone s) f.1 (λ j, congr_arg subtype.val (h j))) } instance : has_coproducts.{u} LocallyRingedSpace.{u} := λ ι, ⟨λ F, ⟨⟨⟨_, coproduct_cofan_is_colimit F⟩⟩⟩⟩ noncomputable instance (J : Type*) : preserves_colimits_of_shape (discrete J) forget_to_SheafedSpace := ⟨λ G, preserves_colimit_of_preserves_colimit_cocone (coproduct_cofan_is_colimit G) ((colimit.is_colimit _).of_iso_colimit (cocones.ext (iso.refl _) (λ j, category.comp_id _)))⟩ end has_coproducts section has_coequalizer variables {X Y : LocallyRingedSpace.{v}} (f g : X ⟶ Y) namespace has_coequalizer instance coequalizer_π_app_is_local_ring_hom (U : topological_space.opens ((coequalizer f.val g.val).carrier)) : is_local_ring_hom ((coequalizer.π f.val g.val : _).c.app (op U)) := begin have := ι_comp_coequalizer_comparison f.1 g.1 SheafedSpace.forget_to_PresheafedSpace, rw ← preserves_coequalizer.iso_hom at this, erw SheafedSpace.congr_app this.symm (op U), rw [PresheafedSpace.comp_c_app, ← PresheafedSpace.colimit_presheaf_obj_iso_componentwise_limit_hom_π], apply_instance end /-! We roughly follow the construction given in [MR0302656]. Given a pair `f, g : X ⟶ Y` of morphisms of locally ringed spaces, we want to show that the stalk map of `π = coequalizer.π f g` (as sheafed space homs) is a local ring hom. It then follows that `coequalizer f g` is indeed a locally ringed space, and `coequalizer.π f g` is a morphism of locally ringed space. Given a germ `⟨U, s⟩` of `x : coequalizer f g` such that `π꙳ x : Y` is invertible, we ought to show that `⟨U, s⟩` is invertible. That is, there exists an open set `U' ⊆ U` containing `x` such that the restriction of `s` onto `U'` is invertible. This `U'` is given by `π '' V`, where `V` is the basic open set of `π⋆x`. Since `f ⁻¹' V = Y.basic_open (f ≫ π)꙳ x = Y.basic_open (g ≫ π)꙳ x = g ⁻¹' V`, we have `π ⁻¹' (π '' V) = V` (as the underlying set map is merely the set-theoretic coequalizer). This shows that `π '' V` is indeed open, and `s` is invertible on `π '' V` as the components of `π꙳` are local ring homs. -/ variable (U : opens ((coequalizer f.1 g.1).carrier)) variable (s : (coequalizer f.1 g.1).presheaf.obj (op U)) /-- (Implementation). The basic open set of the section `π꙳ s`. -/ noncomputable def image_basic_open : opens Y := (Y.to_RingedSpace.basic_open (show Y.presheaf.obj (op (unop _)), from ((coequalizer.π f.1 g.1).c.app (op U)) s)) lemma image_basic_open_image_preimage : (coequalizer.π f.1 g.1).base ⁻¹' ((coequalizer.π f.1 g.1).base '' (image_basic_open f g U s).1) = (image_basic_open f g U s).1 := begin fapply types.coequalizer_preimage_image_eq_of_preimage_eq f.1.base g.1.base, { ext, simp_rw [types_comp_apply, ← Top.comp_app, ← PresheafedSpace.comp_base], congr' 2, exact coequalizer.condition f.1 g.1 }, { apply is_colimit_cofork_map_of_is_colimit (forget Top), apply is_colimit_cofork_map_of_is_colimit (SheafedSpace.forget _), exact coequalizer_is_coequalizer f.1 g.1 }, { suffices : (topological_space.opens.map f.1.base).obj (image_basic_open f g U s) = (topological_space.opens.map g.1.base).obj (image_basic_open f g U s), { injection this }, delta image_basic_open, rw [preimage_basic_open f, preimage_basic_open g], dsimp only [functor.op, unop_op], rw [← comp_apply, ← SheafedSpace.comp_c_app', ← comp_apply, ← SheafedSpace.comp_c_app', SheafedSpace.congr_app (coequalizer.condition f.1 g.1), comp_apply], erw X.to_RingedSpace.basic_open_res, apply inf_eq_right.mpr, refine (RingedSpace.basic_open_subset _ _).trans _, rw coequalizer.condition f.1 g.1, exact λ _ h, h } end lemma image_basic_open_image_open : is_open ((coequalizer.π f.1 g.1).base '' (image_basic_open f g U s).1) := begin rw [← (Top.homeo_of_iso (preserves_coequalizer.iso (SheafedSpace.forget _) f.1 g.1)) .is_open_preimage, Top.coequalizer_is_open_iff, ← set.preimage_comp], erw ← coe_comp, rw [preserves_coequalizer.iso_hom, ι_comp_coequalizer_comparison], dsimp only [SheafedSpace.forget], rw image_basic_open_image_preimage, exact (image_basic_open f g U s).2 end instance coequalizer_π_stalk_is_local_ring_hom (x : Y) : is_local_ring_hom (PresheafedSpace.stalk_map (coequalizer.π f.val g.val : _) x) := begin constructor, rintros a ha, rcases Top.presheaf.germ_exist _ _ a with ⟨U, hU, s, rfl⟩, erw PresheafedSpace.stalk_map_germ_apply (coequalizer.π f.1 g.1 : _) U ⟨_, hU⟩ at ha, let V := image_basic_open f g U s, have hV : (coequalizer.π f.1 g.1).base ⁻¹' ((coequalizer.π f.1 g.1).base '' V.1) = V.1 := image_basic_open_image_preimage f g U s, have hV' : V = ⟨(coequalizer.π f.1 g.1).base ⁻¹' ((coequalizer.π f.1 g.1).base '' V.1), hV.symm ▸ V.2⟩ := subtype.eq hV.symm, have V_open : is_open (((coequalizer.π f.val g.val).base) '' V.val) := image_basic_open_image_open f g U s, have VleU : (⟨((coequalizer.π f.val g.val).base) '' V.val, V_open⟩ : topological_space.opens _) ≤ U, { exact set.image_subset_iff.mpr (Y.to_RingedSpace.basic_open_subset _) }, have hxV : x ∈ V := ⟨⟨_, hU⟩, ha, rfl⟩, erw ← (coequalizer f.val g.val).presheaf.germ_res_apply (hom_of_le VleU) ⟨_, @set.mem_image_of_mem _ _ (coequalizer.π f.val g.val).base x V.1 hxV⟩ s, apply ring_hom.is_unit_map, rw [← is_unit_map_iff ((coequalizer.π f.val g.val : _).c.app _), ← comp_apply, nat_trans.naturality, comp_apply, Top.presheaf.pushforward_obj_map, ← is_unit_map_iff (Y.presheaf.map (eq_to_hom hV').op), ← comp_apply, ← functor.map_comp], convert @RingedSpace.is_unit_res_basic_open Y.to_RingedSpace (unop _) (((coequalizer.π f.val g.val).c.app (op U)) s), apply_instance end end has_coequalizer /-- The coequalizer of two locally ringed space in the category of sheafed spaces is a locally ringed space. -/ noncomputable def coequalizer : LocallyRingedSpace := { to_SheafedSpace := coequalizer f.1 g.1, local_ring := λ x, begin obtain ⟨y, rfl⟩ := (Top.epi_iff_surjective (coequalizer.π f.val g.val).base).mp infer_instance x, exact (PresheafedSpace.stalk_map (coequalizer.π f.val g.val : _) y).domain_local_ring end } /-- The explicit coequalizer cofork of locally ringed spaces. -/ noncomputable def coequalizer_cofork : cofork f g := @cofork.of_π _ _ _ _ f g (coequalizer f g) ⟨coequalizer.π f.1 g.1, infer_instance⟩ (subtype.eq (coequalizer.condition f.1 g.1)) lemma is_local_ring_hom_stalk_map_congr {X Y : RingedSpace} (f g : X ⟶ Y) (H : f = g) (x) (h : is_local_ring_hom (PresheafedSpace.stalk_map f x)) : is_local_ring_hom (PresheafedSpace.stalk_map g x) := by { rw PresheafedSpace.stalk_map.congr_hom _ _ H.symm x, apply_instance } /-- The cofork constructed in `coequalizer_cofork` is indeed a colimit cocone. -/ noncomputable def coequalizer_cofork_is_colimit : is_colimit (coequalizer_cofork f g) := begin apply cofork.is_colimit.mk', intro s, have e : f.val ≫ s.π.val = g.val ≫ s.π.val := by injection s.condition, use coequalizer.desc s.π.1 e, { intro x, rcases (Top.epi_iff_surjective (coequalizer.π f.val g.val).base).mp infer_instance x with ⟨y, rfl⟩, apply is_local_ring_hom_of_comp _ (PresheafedSpace.stalk_map (coequalizer_cofork f g).π.1 _), change is_local_ring_hom (_ ≫ PresheafedSpace.stalk_map (coequalizer_cofork f g).π.val y), erw ← PresheafedSpace.stalk_map.comp, apply is_local_ring_hom_stalk_map_congr _ _ (coequalizer.π_desc s.π.1 e).symm y, apply_instance }, split, exact subtype.eq (coequalizer.π_desc _ _), intros m h, replace h : (coequalizer_cofork f g).π.1 ≫ m.1 = s.π.1 := by { rw ← h, refl }, apply subtype.eq, apply (colimit.is_colimit (parallel_pair f.1 g.1)).uniq (cofork.of_π s.π.1 e) m.1, rintro ⟨⟩, { rw [← (colimit.cocone (parallel_pair f.val g.val)).w walking_parallel_pair_hom.left, category.assoc], change _ ≫ _ ≫ _ = _ ≫ _, congr, exact h }, { exact h } end instance : has_coequalizer f g := ⟨⟨⟨_, coequalizer_cofork_is_colimit f g⟩⟩⟩ instance : has_coequalizers LocallyRingedSpace := has_coequalizers_of_has_colimit_parallel_pair _ noncomputable instance preserves_coequalizer : preserves_colimits_of_shape walking_parallel_pair forget_to_SheafedSpace.{v} := ⟨λ F, begin apply preserves_colimit_of_iso_diagram _ (diagram_iso_parallel_pair F).symm, apply preserves_colimit_of_preserves_colimit_cocone (coequalizer_cofork_is_colimit _ _), apply (is_colimit_map_cocone_cofork_equiv _ _).symm _, dsimp only [forget_to_SheafedSpace], exact coequalizer_is_coequalizer _ _ end⟩ end has_coequalizer instance : has_colimits LocallyRingedSpace := has_colimits_of_has_coequalizers_and_coproducts noncomputable instance : preserves_colimits LocallyRingedSpace.forget_to_SheafedSpace := preserves_colimits_of_preserves_coequalizers_and_coproducts _ end LocallyRingedSpace end algebraic_geometry
cdb7412330630a47e26ed221f99b1b95beabfb5e
92b50235facfbc08dfe7f334827d47281471333b
/tests/lean/hott/433.hlean
b4fdf00d3adc8e3ca5c0ad4637caa6e9862ec601
[ "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
4,867
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import types.sigma open eq equiv is_equiv funext namespace pi universe variables l k variables {A A' : Type.{l}} {B : A → Type.{k}} {B' : A' → Type.{k}} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ∼ g]. This equivalence, however, is just the combination of [apD10] and function extensionality [funext], and as such, [path_forall], et seq. are given in axioms.funext and path: -/ /- Now we show how these things compute. -/ definition apd10_path_pi (H : funext) (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) definition path_pi_eta (H : funext) (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p print classes definition path_pi_idp (H : funext) : eq_of_homotopy (λx : A, refl (f x)) = refl f := path_pi_eta H _ /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition path_equiv_homotopy (H : funext) (f g : Πx, B x) : (f = g) ≃ (f ~ g) := equiv.mk _ !is_equiv_apd definition is_equiv_path_pi [instance] (H : funext) (f g : Πx, B x) : is_equiv (@eq_of_homotopy _ _ f g) := is_equiv_inv apd10 definition homotopy_equiv_path (H : funext) (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk _ (is_equiv_path_pi H f g) /- Transport -/ protected definition transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, transport (C a') !tr_inv_tr (transportD _ p _ (f (p⁻¹ ▸ b)))) := eq.rec_on p (λx, idp) /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) : (eq.transport (λa, Π(b : A'), C a b) p f) ~ (λb, eq.transport (λa, C a b) p (f b)) := eq.rec_on p (λx, idp) /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD (H : funext) {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply (path_pi_idp H) end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (eq.transport B p b)) ≃ (eq.transport (λa, Π(b : B a), C a b) p f = g) -/ definition dpath_pi (H : funext) (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, homotopy_equiv_path H f g) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), eq.transport C (sigma.path p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (eq.transport B p b)) -/ definition dpath_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma.sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), p ▸D (f b) = g (p ▸ b)) := eq.rec_on p (λg, !equiv.refl) g end variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') definition transport_V [reducible] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition functor_pi : (Π(a:A), B a) → (Π(a':A'), B' a') := (λg a', f1 a' (g (f0 a'))) /- Equivalences -/ definition isequiv_functor_pi [instance] (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') [H0 : is_equiv f0] [H1 : Πa', @is_equiv (B (f0 a')) (B' a') (f1 a')] : is_equiv (functor_pi f0 f1) := begin apply (adjointify (functor_pi f0 f1) (functor_pi (f0⁻¹) (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), intro h, apply eq_of_homotopy, esimp [functor_pi, function.compose], -- simplify (and unfold function_pi and function.compose) --first subgoal intro a', esimp, rewrite adj, rewrite -transport_compose, rewrite {f1 a' _}(fn_tr_eq_tr_fn _ f1 _), rewrite (right_inv (f1 _) _), apply apd, intro h, beta, apply eq_of_homotopy, intro a, esimp, apply (transport_V (λx, right_inv f0 a ▸ x = h a) (left_inv (f1 _) _)), esimp [function.id], apply apd end end pi
22577ad1ada72583a1aa2b9b805df9ae4255f329
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/rb_map.lean
5ecd0a6d6aa63d44188d5fb22c47437c954f6bb3
[ "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
8,117
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, Jeremy Avigad -/ prelude import init.data.ordering.basic init.function init.meta.name init.meta.format init.control.monad open format private meta def format_key {key} [has_to_format key] (k : key) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k namespace native meta constant {u₁ u₂} rb_map : Type u₁ → Type u₂ → Type (max u₁ u₂) namespace rb_map meta constant mk_core {key : Type} (data : Type) : (key → key → ordering) → rb_map key data meta constant size {key : Type} {data : Type} : rb_map key data → nat meta constant empty {key : Type} {data : Type} : rb_map key data → bool meta constant insert {key : Type} {data : Type} : rb_map key data → key → data → rb_map key data meta constant erase {key : Type} {data : Type} : rb_map key data → key → rb_map key data meta constant contains {key : Type} {data : Type} : rb_map key data → key → bool meta constant find {key : Type} {data : Type} : rb_map key data → key → option data meta constant min {key : Type} {data : Type} : rb_map key data → option data meta constant max {key : Type} {data : Type} : rb_map key data → option data meta constant fold {key : Type} {data : Type} {α :Type} : rb_map key data → α → (key → data → α → α) → α attribute [inline] meta def mk (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : rb_map key data := mk_core data cmp open list section variables {key data : Type} meta def keys (m : rb_map key data) : list key := fold m [] (λk v ks, k :: ks) meta def values {key : Type} {data : Type} (m : rb_map key data) : list data := fold m [] (λk v vs, v :: vs) meta def to_list {key : Type} {data : Type} (m : rb_map key data) : list (key × data) := fold m [] (λk v res, (k, v) :: res) meta def mfold {key data α :Type} {m : Type → Type} [monad m] (mp : rb_map key data) (a : α) (fn : key → data → α → m α) : m α := mp.fold (return a) (λ k d act, act >>= fn k d) end section variables {key data data' : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] meta def of_list : list (key × data) → rb_map key data | [] := mk key data | ((k, v)::ls) := insert (of_list ls) k v meta def set_of_list : list key → rb_map key unit | [] := mk _ _ | (x::xs) := insert (set_of_list xs) x () meta def map (f : data → data') (m : rb_map key data) : rb_map key data' := fold m (mk _ _) (λk v res, insert res k (f v)) meta def for (m : rb_map key data) (f : data → data') : rb_map key data' := map f m meta def filter (m : rb_map key data) (f : data → Prop) [decidable_pred f] := fold m (mk _ _) $ λa b m', if f b then insert m' a b else m' end end rb_map meta def mk_rb_map {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : rb_map key data := rb_map.mk key data @[reducible] meta def nat_map (data : Type) := rb_map nat data namespace nat_map export rb_map (mk_core size empty insert erase contains find min max fold keys values to_list mfold of_list set_of_list map for filter) meta def mk (data : Type) : nat_map data := rb_map.mk nat data end nat_map meta def mk_nat_map {data : Type} : nat_map data := nat_map.mk data open rb_map prod section variables {key : Type} {data : Type} [has_to_format key] [has_to_format data] private meta def format_key_data (k : key) (d : data) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k ++ space ++ to_fmt "←" ++ space ++ to_fmt d meta instance : has_to_format (rb_map key data) := ⟨λ m, group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ k d p, (fst p ++ format_key_data k d (snd p), ff)))) ++ to_fmt "⟩"⟩ end section variables {key : Type} {data : Type} [has_to_string key] [has_to_string data] private meta def key_data_to_string (k : key) (d : data) (first : bool) : string := (if first then "" else ", ") ++ to_string k ++ " ← " ++ to_string d meta instance : has_to_string (rb_map key data) := ⟨λ m, "⟨" ++ (fst (fold m ("", tt) (λ k d p, (fst p ++ key_data_to_string k d (snd p), ff)))) ++ "⟩"⟩ end /-- a variant of rb_maps that stores a list of elements for each key. `find` returns the list of elements in the opposite order that they were inserted. -/ meta def rb_lmap (key : Type) (data : Type) : Type := rb_map key (list data) namespace rb_lmap protected meta def mk (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : rb_lmap key data := rb_map.mk key (list data) meta def insert {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) (d : data) : rb_lmap key data := match (rb_map.find rbl k) with | none := rb_map.insert rbl k [d] | (some l) := rb_map.insert (rb_map.erase rbl k) k (d :: l) end meta def erase {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : rb_lmap key data := rb_map.erase rbl k meta def contains {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : bool := rb_map.contains rbl k meta def find {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : list data := match (rb_map.find rbl k) with | none := [] | (some l) := l end end rb_lmap meta def rb_set (key) := rb_map key unit meta def mk_rb_set {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : rb_set key := mk_rb_map namespace rb_set meta def insert {key} (s : rb_set key) (k : key) : rb_set key := rb_map.insert s k () meta def erase {key} (s : rb_set key) (k : key) : rb_set key := rb_map.erase s k meta def contains {key} (s : rb_set key) (k : key) : bool := rb_map.contains s k meta def size {key} (s : rb_set key) : nat := rb_map.size s meta def empty {key : Type} (s : rb_set key) : bool := rb_map.empty s meta def fold {key α : Type} (s : rb_set key) (a : α) (fn : key → α → α) : α := rb_map.fold s a (λ k _ a, fn k a) meta def mfold {key α :Type} {m : Type → Type} [monad m] (s : rb_set key) (a : α) (fn : key → α → m α) : m α := s.fold (return a) (λ k act, act >>= fn k) meta def to_list {key : Type} (s : rb_set key) : list key := s.fold [] list.cons meta instance {key} [has_to_format key] : has_to_format (rb_set key) := ⟨λ m, group $ to_fmt "{" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ k p, (fst p ++ format_key k (snd p), ff)))) ++ to_fmt "}"⟩ end rb_set end native open native @[reducible] meta def name_map (data : Type) := rb_map name data namespace name_map export native.rb_map (mk_core size empty insert erase contains find min max fold keys values to_list mfold of_list set_of_list map for filter) meta def mk (data : Type) : name_map data := rb_map.mk_core data name.cmp end name_map meta def mk_name_map {data : Type} : name_map data := name_map.mk data /-- An rb_map of `name`s. -/ meta constant name_set : Type meta constant mk_name_set : name_set namespace name_set meta constant insert : name_set → name → name_set meta constant erase : name_set → name → name_set meta constant contains : name_set → name → bool meta constant size : name_set → nat meta constant empty : name_set → bool meta constant fold {α :Type} : name_set → α → (name → α → α) → α meta def union (l r : name_set) : name_set := r.fold l (λ ns n, name_set.insert n ns) meta def to_list (s : name_set) : list name := s.fold [] list.cons meta instance : has_to_format name_set := ⟨λ m, group $ to_fmt "{" ++ nest 1 (fold m (to_fmt "", tt) (λ k p, (p.1 ++ format_key k p.2, ff))).1 ++ to_fmt "}"⟩ meta def of_list (l : list name) : name_set := list.foldl name_set.insert mk_name_set l meta def mfold {α :Type} {m : Type → Type} [monad m] (ns : name_set) (a : α) (fn : name → α → m α) : m α := ns.fold (return a) (λ k act, act >>= fn k) end name_set
41c724125f0e56947985ade50ba4cf15ccfcffdb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/mixedMacroRules.lean
8bfa03eb0a5d90ec7b89432944fdb2865020b4f6
[ "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
180
lean
syntax:65 term "+!+" term:65 : term syntax:70 term "*!*" term:70 : term macro_rules | `($a +!+ $b) => `($a + $b) | `($a *!* $b) => `($a * $b) #check 10 +!+ 20 #check 10 *!* 20
e02c2b3581b2067f5cc877de35526832a12387ea
69d4931b605e11ca61881fc4f66db50a0a875e39
/test/integration.lean
315f4c20aa778e90743f2042bcaeb183eb22d3f5
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
2,800
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import analysis.special_functions.integrals open interval_integral real open_locale real /-! ### Simple functions -/ /- constants -/ example : ∫ x : ℝ in 8..11, (1 : ℝ) = 3 := by norm_num example : ∫ x : ℝ in 5..19, (12 : ℝ) = 168 := by norm_num /- the identity function -/ example : ∫ x : ℝ in (-1)..4, x = 15 / 2 := by norm_num example : ∫ x : ℝ in 4..5, x * 2 = 9 := by norm_num /- inverse -/ example : ∫ x : ℝ in 2..3, x⁻¹ = log (3 / 2) := by norm_num /- natural powers -/ example : ∫ x : ℝ in 2..4, x ^ (3 : ℕ) = 60 := by norm_num /- trigonometric functions -/ example : ∫ x in 0..π, sin x = 2 := by norm_num example : ∫ x in 0..π/4, cos x = sqrt 2 / 2 := by simp example : ∫ x in 0..π, 2 * sin x = 4 := by norm_num example : ∫ x in 0..π/2, cos x / 2 = 1 / 2 := by simp example : ∫ x : ℝ in 0..1, 1 / (1 + x ^ 2) = π/4 := by simp example : ∫ x in 0..2*π, sin x ^ 2 = π := by simp [mul_div_cancel_left] example : ∫ x in 0..π/2, cos x ^ 2 / 2 = π/8 := by norm_num [div_div_eq_div_mul] example : ∫ x in 0..π, cos x ^ 2 - sin x ^ 2 = 0 := by simp [integral_cos_sq_sub_sin_sq] /- the exponential function -/ example : ∫ x in 0..2, -exp x = 1 - exp 2 := by simp /- linear combinations (e.g. polynomials) -/ example : ∫ x : ℝ in 0..2, 6*x^5 + 3*x^4 + x^3 - 2*x^2 + x - 7 = 1048 / 15 := by norm_num example : ∫ x : ℝ in 0..1, exp x + 9 * x^8 + x^3 - x/2 + (1 + x^2)⁻¹ = exp 1 + π / 4 := by norm_num /-! ### Functions composed with multiplication by and/or addition of a constant -/ /- many examples are computable by `norm_num` -/ example : ∫ x in 0..2, -exp (-x) = exp (-2) - 1 := by norm_num example : ∫ x in 1..2, exp (5*x - 5) = 1/5 * (exp 5 - 1) := by norm_num example : ∫ x in 0..π, cos (x/2) = 2 := by norm_num example : ∫ x in 0..π/4, sin (2*x) = 1/2 := by norm_num [mul_div_comm, mul_one_div] example (ω φ : ℝ) : ω * ∫ θ in 0..π, sin (ω*θ + φ) = cos φ - cos (ω*π + φ) := by simp /- some examples may require a bit of algebraic massaging -/ example {L : ℝ} (h : L ≠ 0) : ∫ x in 0..2/L*π, sin (L/2 * x) = 4 / L := begin norm_num [div_ne_zero h, ← mul_assoc], field_simp [h, mul_div_cancel], norm_num, end /- you may need to provide `norm_num` with the composition lemma you are invoking if it has a difficult time recognizing the function you are trying to integrate -/ example : ∫ x : ℝ in 0..2, 3 * (x + 1) ^ 2 = 26 := by norm_num [integral_comp_add_right (λ x, x ^ 2)] example : ∫ x : ℝ in -1..0, (1 + (x + 1) ^ 2)⁻¹ = π/4 := by simp [integral_comp_add_right (λ x, (1 + x ^ 2)⁻¹)]
cb8be9513fdc052940fb35798fa288f647ba2214
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/polynomial/derivative.lean
0efea9d676cd0644b115eed42333b07dfe10b37d
[ "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
13,972
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 data.polynomial.eval /-! # The derivative map on polynomials ## Main definitions * `polynomial.derivative`: The formal derivative of polynomials, expressed as a linear map. -/ noncomputable theory open finset open_locale big_operators classical namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {A : Type z} {a b : R} {n : ℕ} section derivative section semiring variables [semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative : polynomial R →ₗ[R] polynomial R := { to_fun := λ p, p.sum (λ n a, C (a * n) * X^(n-1)), map_add' := λ p q, by rw sum_add_index; simp only [add_mul, forall_const, ring_hom.map_add, eq_self_iff_true, zero_mul, ring_hom.map_zero], map_smul' := λ a p, by dsimp; rw sum_smul_index; simp only [mul_sum, ← C_mul', mul_assoc, coeff_C_mul, ring_hom.map_mul, forall_const, zero_mul, ring_hom.map_zero, sum] } lemma derivative_apply (p : polynomial R) : derivative p = p.sum (λn a, C (a * n) * X^(n - 1)) := rfl lemma coeff_derivative (p : polynomial R) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative_apply], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [sum, finset.sum_eq_single (n + 1)], simp only [nat.add_succ_sub_one, add_zero, mul_one, if_true, eq_self_iff_true], norm_cast, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul], }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one, mem_support_iff], intro h, push_neg at h, simp [h], }, end @[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 := derivative.map_zero @[simp] lemma iterate_derivative_zero {k : ℕ} : derivative^[k] (0 : polynomial R) = 0 := begin induction k with k ih, { simp, }, { simp [ih], }, end @[simp] lemma derivative_monomial (a : R) (n : ℕ) : derivative (monomial n a) = monomial (n - 1) (a * n) := by { rw [derivative_apply, sum_monomial_index, C_mul_X_pow_eq_monomial], simp } lemma derivative_C_mul_X_pow (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [C_mul_X_pow_eq_monomial, C_mul_X_pow_eq_monomial, derivative_monomial] @[simp] lemma derivative_X_pow (n : ℕ) : derivative (X ^ n : polynomial R) = (n : polynomial R) * X ^ (n - 1) := by convert derivative_C_mul_X_pow (1 : R) n; simp @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := by simp [derivative_apply] @[simp] lemma derivative_X : derivative (X : polynomial R) = 1 := (derivative_monomial _ _).trans $ by simp @[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 := derivative_C @[simp] lemma derivative_bit0 {a : polynomial R} : derivative (bit0 a) = bit0 (derivative a) := by simp [bit0] @[simp] lemma derivative_bit1 {a : polynomial R} : derivative (bit1 a) = bit0 (derivative a) := by simp [bit1] @[simp] lemma derivative_add {f g : polynomial R} : derivative (f + g) = derivative f + derivative g := derivative.map_add f g @[simp] lemma iterate_derivative_add {f g : polynomial R} {k : ℕ} : derivative^[k] (f + g) = (derivative^[k] f) + (derivative^[k] g) := derivative.to_add_monoid_hom.iterate_map_add _ _ _ @[simp] lemma derivative_neg {R : Type*} [ring R] (f : polynomial R) : derivative (-f) = - derivative f := linear_map.map_neg derivative f @[simp] lemma iterate_derivative_neg {R : Type*} [ring R] {f : polynomial R} {k : ℕ} : derivative^[k] (-f) = - (derivative^[k] f) := (@derivative R _).to_add_monoid_hom.iterate_map_neg _ _ @[simp] lemma derivative_sub {R : Type*} [ring R] {f g : polynomial R} : derivative (f - g) = derivative f - derivative g := linear_map.map_sub derivative f g @[simp] lemma iterate_derivative_sub {R : Type*} [ring R] {k : ℕ} {f g : polynomial R} : derivative^[k] (f - g) = (derivative^[k] f) - (derivative^[k] g) := begin induction k with k ih generalizing f g, { simp [nat.iterate], }, { simp [nat.iterate, ih], } end @[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} : derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) := derivative.map_sum @[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p := derivative.map_smul _ _ @[simp] lemma iterate_derivative_smul (r : R) (p : polynomial R) (k : ℕ) : derivative^[k] (r • p) = r • (derivative^[k] p) := begin induction k with k ih generalizing p, { simp, }, { simp [ih], }, end /-- We can't use `derivative_mul` here because we want to prove this statement also for noncommutative rings.-/ @[simp] lemma derivative_C_mul (a : R) (p : polynomial R) : derivative (C a * p) = C a * derivative p := by convert derivative_smul a p; apply C_mul' @[simp] lemma iterate_derivative_C_mul (a : R) (p : polynomial R) (k : ℕ) : derivative^[k] (C a * p) = C a * (derivative^[k] p) := by convert iterate_derivative_smul a p k; apply C_mul' end semiring section comm_semiring variables [comm_semiring R] lemma derivative_eval (p : polynomial R) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp only [derivative_apply, eval_sum, eval_pow, eval_C, eval_X, eval_nat_cast, eval_mul] @[simp] lemma derivative_mul {f g : polynomial R} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin rw mul_eq_sum_sum, transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact monomial_eq_C_mul_X }, exact derivative_C_mul_X_pow _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.add_succ, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, simp only [sum, sum_add_distrib, finset.mul_sum, finset.sum_mul, derivative_apply] end theorem derivative_pow_succ (p : polynomial R) (n : ℕ) : (p ^ (n + 1)).derivative = (n + 1) * (p ^ n) * p.derivative := nat.rec_on n (by rw [pow_one, nat.cast_zero, zero_add, one_mul, pow_zero, one_mul]) $ λ n ih, by rw [pow_succ', derivative_mul, ih, mul_right_comm, ← add_mul, add_mul (n.succ : polynomial R), one_mul, pow_succ', mul_assoc, n.cast_succ] theorem derivative_pow (p : polynomial R) (n : ℕ) : (p ^ n).derivative = n * (p ^ (n - 1)) * p.derivative := nat.cases_on n (by rw [pow_zero, derivative_one, nat.cast_zero, zero_mul, zero_mul]) $ λ n, by rw [p.derivative_pow_succ n, n.succ_sub_one, n.cast_succ] lemma derivative_comp (p q : polynomial R) : (p.comp q).derivative = q.derivative * p.derivative.comp q := begin apply polynomial.induction_on' p, { intros p₁ p₂ h₁ h₂, simp [h₁, h₂, mul_add], }, { intros n r, simp only [derivative_pow, derivative_mul, monomial_comp, derivative_monomial, derivative_C, zero_mul, C_eq_nat_cast, zero_add, ring_hom.map_mul], -- is there a tactic for this? (a multiplicative `abel`): rw [mul_comm (derivative q)], simp only [mul_assoc], } end @[simp] theorem derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) : (p.map f).derivative = p.derivative.map f := polynomial.induction_on p (λ r, by rw [map_C, derivative_C, derivative_C, map_zero]) (λ p q ihp ihq, by rw [map_add, derivative_add, ihp, ihq, derivative_add, map_add]) (λ n r ih, by rw [map_mul, map_C, map_pow, map_X, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, derivative_mul, derivative_pow_succ, derivative_C, zero_mul, zero_add, derivative_X, mul_one, map_mul, map_C, map_mul, map_pow, map_add, map_nat_cast, map_one, map_X]) @[simp] theorem iterate_derivative_map [comm_semiring S] (p : polynomial R) (f : R →+* S) (k : ℕ): polynomial.derivative^[k] (p.map f) = (polynomial.derivative^[k] p).map f := begin induction k with k ih generalizing p, { simp, }, { simp [ih], }, end /-- Chain rule for formal derivative of polynomials. -/ theorem derivative_eval₂_C (p q : polynomial R) : (p.eval₂ C q).derivative = p.derivative.eval₂ C q * q.derivative := polynomial.induction_on p (λ r, by rw [eval₂_C, derivative_C, eval₂_zero, zero_mul]) (λ p₁ p₂ ih₁ ih₂, by rw [eval₂_add, derivative_add, ih₁, ih₂, derivative_add, eval₂_add, add_mul]) (λ n r ih, by rw [pow_succ', ← mul_assoc, eval₂_mul, eval₂_X, derivative_mul, ih, @derivative_mul _ _ _ X, derivative_X, mul_one, eval₂_add, @eval₂_mul _ _ _ _ X, eval₂_X, add_mul, mul_right_comm]) theorem of_mem_support_derivative {p : polynomial R} {n : ℕ} (h : n ∈ p.derivative.support) : n + 1 ∈ p.support := mem_support_iff.2 $ λ (h1 : p.coeff (n+1) = 0), mem_support_iff.1 h $ show p.derivative.coeff n = 0, by rw [coeff_derivative, h1, zero_mul] theorem degree_derivative_lt {p : polynomial R} (hp : p ≠ 0) : p.derivative.degree < p.degree := (finset.sup_lt_iff $ bot_lt_iff_ne_bot.2 $ mt degree_eq_bot.1 hp).2 $ λ n hp, lt_of_lt_of_le (with_bot.some_lt_some.2 n.lt_succ_self) $ finset.le_sup $ of_mem_support_derivative hp theorem nat_degree_derivative_lt {p : polynomial R} (hp : p.derivative ≠ 0) : p.derivative.nat_degree < p.nat_degree := have hp1 : p ≠ 0, from λ h, hp $ by rw [h, derivative_zero], with_bot.some_lt_some.1 $ begin rw [nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp, nat_degree, option.get_or_else_of_ne_none $ mt degree_eq_bot.1 hp1], exact degree_derivative_lt hp1 end theorem degree_derivative_le {p : polynomial R} : p.derivative.degree ≤ p.degree := if H : p = 0 then le_of_eq $ by rw [H, derivative_zero] else le_of_lt $ degree_derivative_lt H /-- The formal derivative of polynomials, as linear homomorphism. -/ def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R := { to_fun := derivative, map_add' := λ p q, derivative_add, map_smul' := λ r p, derivative_smul r p } @[simp] lemma derivative_lhom_coe {R : Type*} [comm_ring R] : (polynomial.derivative_lhom R : polynomial R → polynomial R) = polynomial.derivative := rfl @[simp] lemma derivative_cast_nat {n : ℕ} : derivative (n : polynomial R) = 0 := begin rw ← C.map_nat_cast n, exact derivative_C, end @[simp] lemma iterate_derivative_cast_nat_mul {n k : ℕ} {f : polynomial R} : derivative^[k] (n * f) = n * (derivative^[k] f) := begin induction k with k ih generalizing f, { simp [nat.iterate], }, { simp [nat.iterate, ih], } end end comm_semiring section comm_ring variables [comm_ring R] lemma derivative_comp_one_sub_X (p : polynomial R) : (p.comp (1-X)).derivative = -p.derivative.comp (1-X) := by simp [derivative_comp] @[simp] lemma iterate_derivative_comp_one_sub_X (p : polynomial R) (k : ℕ) : derivative^[k] (p.comp (1-X)) = (-1)^k * (derivative^[k] p).comp (1-X) := begin induction k with k ih generalizing p, { simp, }, { simp [ih p.derivative, iterate_derivative_neg, derivative_comp, pow_succ], }, end end comm_ring section domain variables [comm_ring R] [integral_domain R] lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [mem_support_iff, coeff_derivative, ne.def, mul_eq_zero], by { rw [nat.cast_eq_zero], simp only [nat.succ_ne_zero, or_false] } @[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := begin have h0 : p ≠ 0, { contrapose! hp, simp [hp] }, apply le_antisymm, { rw derivative_apply, apply le_trans (degree_sum_le _ _) (sup_le (λ n hn, _)), apply le_trans (degree_C_mul_X_pow_le _ _) (with_bot.coe_le_coe.2 (nat.sub_le_sub_right _ _)), apply le_nat_degree_of_mem_supp _ hn }, { refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp } end theorem nat_degree_eq_zero_of_derivative_eq_zero [char_zero R] {f : polynomial R} (h : f.derivative = 0) : f.nat_degree = 0 := begin by_cases hf : f = 0, { exact (congr_arg polynomial.nat_degree hf).trans rfl }, { rw nat_degree_eq_zero_iff_degree_le_zero, by_contra absurd, have f_nat_degree_pos : 0 < f.nat_degree, { rwa [not_le, ←nat_degree_pos_iff_degree_pos] at absurd }, let m := f.nat_degree - 1, have hm : m + 1 = f.nat_degree := nat.sub_add_cancel f_nat_degree_pos, have h2 := coeff_derivative f m, rw polynomial.ext_iff at h, rw [h m, coeff_zero, zero_eq_mul] at h2, cases h2, { rw [hm, ←leading_coeff, leading_coeff_eq_zero] at h2, exact hf h2, }, { norm_cast at h2 } } end end domain end derivative end polynomial
a93ca0636e57bfd894fe3ceddc3ff76490d023bf
2d041ea7f2e9b29093ffd7c99b11decfaa8b20ca
/em_dne.lean
1f005a3bae00736e69fe70a0940738a3476336c1
[]
no_license
0xpr/lean_tutorial
1a66577602baa9a52c2b01130b9d70089653ea37
56ef609d8df9e392916012db5354bf182cbbb8d8
refs/heads/master
1,606,955,421,810
1,499,014,388,000
1,499,014,388,000
96,036,899
1
0
null
null
null
null
UTF-8
Lean
false
false
694
lean
open classical -- Proving double negation implies excluded middle variables p q : Prop theorem dne {p : Prop} (H : ¬¬p) : p := or.elim (em p) (assume Hp : p, Hp) (assume Hnp : ¬p, absurd Hnp H) theorem help3 (negated : ¬(p ∨ ¬p)) : ¬p ∧ ¬¬p := and.intro (assume Hp : p, show false, from negated (or.intro_left (¬p) Hp)) (assume Hp : ¬p, show false, from negated (or.intro_right p Hp)) theorem help2 (single_negated : ¬(p ∨ ¬p)) : false := have Hp : ¬p ∧ ¬¬p, from help3 p single_negated, show false, from (and.elim_right Hp (and.elim_left Hp)) theorem emm_ : p ∨ ¬p := dne (help2 p) check emm_
139ca5f3c9d78b77078e9555dc65c415b3f67089
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set/intervals/with_bot_top.lean
6f4c2ee095456ae6dbb30c3534e02551f686f67b
[ "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
7,190
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.set.intervals.basic /-! # Intervals in `with_top α` and `with_bot α` In this file we prove various lemmas about `set.image`s and `set.preimage`s of intervals under `coe : α → with_top α` and `coe : α → with_bot α`. -/ open set variables {α : Type*} /-! ### `with_top` -/ namespace with_top @[simp] lemma preimage_coe_top : (coe : α → with_top α) ⁻¹' {⊤} = (∅ : set α) := eq_empty_of_subset_empty $ λ a, coe_ne_top variables [partial_order α] {a b : α} lemma range_coe : range (coe : α → with_top α) = Iio ⊤ := begin ext x, rw [mem_Iio, lt_top_iff_ne_top, mem_range, ← none_eq_top, option.ne_none_iff_exists], refl, end @[simp] lemma preimage_coe_Ioi : (coe : α → with_top α) ⁻¹' (Ioi a) = Ioi a := ext $ λ x, coe_lt_coe @[simp] lemma preimage_coe_Ici : (coe : α → with_top α) ⁻¹' (Ici a) = Ici a := ext $ λ x, coe_le_coe @[simp] lemma preimage_coe_Iio : (coe : α → with_top α) ⁻¹' (Iio a) = Iio a := ext $ λ x, coe_lt_coe @[simp] lemma preimage_coe_Iic : (coe : α → with_top α) ⁻¹' (Iic a) = Iic a := ext $ λ x, coe_le_coe @[simp] lemma preimage_coe_Icc : (coe : α → with_top α) ⁻¹' (Icc a b) = Icc a b := by simp [← Ici_inter_Iic] @[simp] lemma preimage_coe_Ico : (coe : α → with_top α) ⁻¹' (Ico a b) = Ico a b := by simp [← Ici_inter_Iio] @[simp] lemma preimage_coe_Ioc : (coe : α → with_top α) ⁻¹' (Ioc a b) = Ioc a b := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_coe_Ioo : (coe : α → with_top α) ⁻¹' (Ioo a b) = Ioo a b := by simp [← Ioi_inter_Iio] @[simp] lemma preimage_coe_Iio_top : (coe : α → with_top α) ⁻¹' (Iio ⊤) = univ := by rw [← range_coe, preimage_range] @[simp] lemma preimage_coe_Ico_top : (coe : α → with_top α) ⁻¹' (Ico a ⊤) = Ici a := by simp [← Ici_inter_Iio] @[simp] lemma preimage_coe_Ioo_top : (coe : α → with_top α) ⁻¹' (Ioo a ⊤) = Ioi a := by simp [← Ioi_inter_Iio] lemma image_coe_Ioi : (coe : α → with_top α) '' (Ioi a) = Ioo a ⊤ := by rw [← preimage_coe_Ioi, image_preimage_eq_inter_range, range_coe, Ioi_inter_Iio] lemma image_coe_Ici : (coe : α → with_top α) '' (Ici a) = Ico a ⊤ := by rw [← preimage_coe_Ici, image_preimage_eq_inter_range, range_coe, Ici_inter_Iio] lemma image_coe_Iio : (coe : α → with_top α) '' (Iio a) = Iio a := by rw [← preimage_coe_Iio, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (Iio_subset_Iio le_top)] lemma image_coe_Iic : (coe : α → with_top α) '' (Iic a) = Iic a := by rw [← preimage_coe_Iic, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (Iic_subset_Iio.2 $ coe_lt_top a)] lemma image_coe_Icc : (coe : α → with_top α) '' (Icc a b) = Icc a b := by rw [← preimage_coe_Icc, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Icc_subset_Iic_self $ Iic_subset_Iio.2 $ coe_lt_top b)] lemma image_coe_Ico : (coe : α → with_top α) '' (Ico a b) = Ico a b := by rw [← preimage_coe_Ico, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Ico_subset_Iio_self $ Iio_subset_Iio le_top)] lemma image_coe_Ioc : (coe : α → with_top α) '' (Ioc a b) = Ioc a b := by rw [← preimage_coe_Ioc, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Ioc_subset_Iic_self $ Iic_subset_Iio.2 $ coe_lt_top b)] lemma image_coe_Ioo : (coe : α → with_top α) '' (Ioo a b) = Ioo a b := by rw [← preimage_coe_Ioo, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Ioo_subset_Iio_self $ Iio_subset_Iio le_top)] end with_top /-! ### `with_bot` -/ namespace with_bot @[simp] lemma preimage_coe_bot : (coe : α → with_bot α) ⁻¹' {⊥} = (∅ : set α) := @with_top.preimage_coe_top αᵒᵈ variables [partial_order α] {a b : α} lemma range_coe : range (coe : α → with_bot α) = Ioi ⊥ := @with_top.range_coe αᵒᵈ _ @[simp] lemma preimage_coe_Ioi : (coe : α → with_bot α) ⁻¹' (Ioi a) = Ioi a := ext $ λ x, coe_lt_coe @[simp] lemma preimage_coe_Ici : (coe : α → with_bot α) ⁻¹' (Ici a) = Ici a := ext $ λ x, coe_le_coe @[simp] lemma preimage_coe_Iio : (coe : α → with_bot α) ⁻¹' (Iio a) = Iio a := ext $ λ x, coe_lt_coe @[simp] lemma preimage_coe_Iic : (coe : α → with_bot α) ⁻¹' (Iic a) = Iic a := ext $ λ x, coe_le_coe @[simp] lemma preimage_coe_Icc : (coe : α → with_bot α) ⁻¹' (Icc a b) = Icc a b := by simp [← Ici_inter_Iic] @[simp] lemma preimage_coe_Ico : (coe : α → with_bot α) ⁻¹' (Ico a b) = Ico a b := by simp [← Ici_inter_Iio] @[simp] lemma preimage_coe_Ioc : (coe : α → with_bot α) ⁻¹' (Ioc a b) = Ioc a b := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_coe_Ioo : (coe : α → with_bot α) ⁻¹' (Ioo a b) = Ioo a b := by simp [← Ioi_inter_Iio] @[simp] lemma preimage_coe_Ioi_bot : (coe : α → with_bot α) ⁻¹' (Ioi ⊥) = univ := by rw [← range_coe, preimage_range] @[simp] lemma preimage_coe_Ioc_bot : (coe : α → with_bot α) ⁻¹' (Ioc ⊥ a) = Iic a := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_coe_Ioo_bot : (coe : α → with_bot α) ⁻¹' (Ioo ⊥ a) = Iio a := by simp [← Ioi_inter_Iio] lemma image_coe_Iio : (coe : α → with_bot α) '' (Iio a) = Ioo ⊥ a := by rw [← preimage_coe_Iio, image_preimage_eq_inter_range, range_coe, inter_comm, Ioi_inter_Iio] lemma image_coe_Iic : (coe : α → with_bot α) '' (Iic a) = Ioc ⊥ a := by rw [← preimage_coe_Iic, image_preimage_eq_inter_range, range_coe, inter_comm, Ioi_inter_Iic] lemma image_coe_Ioi : (coe : α → with_bot α) '' (Ioi a) = Ioi a := by rw [← preimage_coe_Ioi, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (Ioi_subset_Ioi bot_le)] lemma image_coe_Ici : (coe : α → with_bot α) '' (Ici a) = Ici a := by rw [← preimage_coe_Ici, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (Ici_subset_Ioi.2 $ bot_lt_coe a)] lemma image_coe_Icc : (coe : α → with_bot α) '' (Icc a b) = Icc a b := by rw [← preimage_coe_Icc, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Icc_subset_Ici_self $ Ici_subset_Ioi.2 $ bot_lt_coe a)] lemma image_coe_Ioc : (coe : α → with_bot α) '' (Ioc a b) = Ioc a b := by rw [← preimage_coe_Ioc, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Ioc_subset_Ioi_self $ Ioi_subset_Ioi bot_le)] lemma image_coe_Ico : (coe : α → with_bot α) '' (Ico a b) = Ico a b := by rw [← preimage_coe_Ico, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Ico_subset_Ici_self $ Ici_subset_Ioi.2 $ bot_lt_coe a)] lemma image_coe_Ioo : (coe : α → with_bot α) '' (Ioo a b) = Ioo a b := by rw [← preimage_coe_Ioo, image_preimage_eq_inter_range, range_coe, inter_eq_self_of_subset_left (subset.trans Ioo_subset_Ioi_self $ Ioi_subset_Ioi bot_le)] end with_bot
6c3a03b4b12ff2fe1b2b3c3cb672f15e861ca21f
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/algebra/order.lean
0ba02f9998b92d52cd492d1b77ea8a3f49303371
[ "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
9,651
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.logic /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u variables {α : Type u} class weak_order (α : Type u) extends has_le α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) class linear_weak_order (α : Type u) extends weak_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) class strict_order (α : Type u) extends has_lt α := (lt_irrefl : ∀ a : α, ¬ a < a) (lt_trans : ∀ a b c : α, a < b → b < c → a < c) /- structures with a weak and a strict order -/ class order_pair (α : Type u) extends weak_order α, has_lt α := (le_of_lt : ∀ a b : α, a < b → a ≤ b) (lt_of_lt_of_le : ∀ a b c : α, a < b → b ≤ c → a < c) (lt_of_le_of_lt : ∀ a b c : α, a ≤ b → b < c → a < c) (lt_irrefl : ∀ a : α, ¬ a < a) class strong_order_pair (α : Type u) extends weak_order α, has_lt α := (le_iff_lt_or_eq : ∀ a b : α, a ≤ b ↔ a < b ∨ a = b) (lt_irrefl : ∀ a : α, ¬ a < a) class linear_order_pair (α : Type u) extends order_pair α, linear_weak_order α class linear_strong_order_pair (α : Type u) extends strong_order_pair α, linear_weak_order α @[refl] lemma le_refl [weak_order α] : ∀ a : α, a ≤ a := weak_order.le_refl @[trans] lemma le_trans [weak_order α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := weak_order.le_trans lemma le_antisymm [weak_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := weak_order.le_antisymm lemma le_of_eq [weak_order α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a @[trans] lemma ge_trans [weak_order α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_weak_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_weak_order.le_total lemma le_of_not_ge [linear_weak_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le [linear_weak_order α] {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma lt_irrefl [strict_order α] : ∀ a : α, ¬ a < a := strict_order.lt_irrefl lemma gt_irrefl [strict_order α] : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans [strict_order α] : ∀ {a b c : α}, a < b → b < c → a < c := strict_order.lt_trans def lt.trans := @lt_trans @[trans] lemma gt_trans [strict_order α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ def gt.trans := @gt_trans lemma ne_of_lt [strict_order α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [strict_order α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [strict_order α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [strict_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [order_pair α] : ∀ {a b : α}, a < b → a ≤ b := order_pair.le_of_lt @[trans] lemma lt_of_lt_of_le [order_pair α] : ∀ {a b c : α}, a < b → b ≤ c → a < c := order_pair.lt_of_lt_of_le @[trans] lemma lt_of_le_of_lt [order_pair α] : ∀ {a b c : α}, a ≤ b → b < c → a < c := order_pair.lt_of_le_of_lt @[trans] lemma gt_of_gt_of_ge [order_pair α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt [order_pair α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ instance order_pair.to_strict_order [s : order_pair α] : strict_order α := { s with lt_irrefl := order_pair.lt_irrefl, lt_trans := λ a b c h₁ h₂, lt_of_lt_of_le h₁ (le_of_lt h₂) } lemma not_le_of_gt [order_pair α] {a b : α} (h : a > b) : ¬ a ≤ b := λ h₁, lt_irrefl b (lt_of_lt_of_le h h₁) lemma not_lt_of_ge [order_pair α] {a b : α} (h : a ≥ b) : ¬ a < b := λ h₁, lt_irrefl b (lt_of_le_of_lt h h₁) lemma le_iff_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b := strong_order_pair.le_iff_lt_or_eq lemma lt_or_eq_of_le [strong_order_pair α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b := λ a b h, iff.mp le_iff_lt_or_eq h lemma le_of_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b := λ a b h, iff.mpr le_iff_lt_or_eq h lemma lt_of_le_of_ne [strong_order_pair α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, or.resolve_right (lt_or_eq_of_le h₁) h₂ private lemma lt_irrefl' [strong_order_pair α] : ∀ a : α, ¬ a < a := strong_order_pair.lt_irrefl private lemma le_of_lt' [strong_order_pair α] ⦃a b : α⦄ (h : a < b) : a ≤ b := le_of_lt_or_eq (or.inl h) private lemma lt_of_lt_of_le' [strong_order_pair α] (a b c : α) (h₁ : a < b) (h₂ : b ≤ c) : a < c := have a ≤ c, from le_trans (le_of_lt' h₁) h₂, or.elim (lt_or_eq_of_le this) (λ h : a < c, h) (λ h : a = c, have b ≤ a, from h^.symm ▸ h₂, have a = b, from le_antisymm (le_of_lt' h₁) this, absurd h₁ (this ▸ lt_irrefl' a)) private lemma lt_of_le_of_lt' [strong_order_pair α] (a b c : α) (h₁ : a ≤ b) (h₂ : b < c) : a < c := have a ≤ c, from le_trans h₁ (le_of_lt' h₂), or.elim (lt_or_eq_of_le this) (λ h : a < c, h) (λ h : a = c, have c ≤ b, from h ▸ h₁, have c = b, from le_antisymm this (le_of_lt' h₂), absurd h₂ (this ▸ lt_irrefl' c)) instance strong_order_pair.to_order_pair [s : strong_order_pair α] : order_pair α := { s with lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le'} instance linear_strong_order_pair.to_linear_order_pair [s : linear_strong_order_pair α] : linear_order_pair α := { s with lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le'} lemma lt_trichotomy [linear_strong_order_pair α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h^.symm))) lemma le_of_not_gt [linear_strong_order_pair α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_strong_order_pair α] {a b : α} (h : ¬ a ≥ b) : a < b := match lt_trichotomy a b with | or.inl hlt := hlt | or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h | or.inr (or.inr hgt) := absurd (le_of_lt hgt) h end lemma lt_or_ge [linear_strong_order_pair α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_strong_order_pair α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_strong_order_pair α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end /- The following lemma can be used when defining a decidable_linear_order instance, and the concrete structure does not have its own definition for decidable le -/ def decidable_le_of_decidable_lt [linear_strong_order_pair α] [∀ a b : α, decidable (a < b)] (a b : α) : decidable (a ≤ b) := if h₁ : a < b then is_true (le_of_lt h₁) else if h₂ : b < a then is_false (not_le_of_gt h₂) else is_true (le_of_not_gt h₂) /- The following lemma can be used when defining a decidable_linear_order instance, and the concrete structure does not have its own definition for decidable le -/ def decidable_eq_of_decidable_lt [linear_strong_order_pair α] [∀ a b : α, decidable (a < b)] (a b : α) : decidable (a = b) := match decidable_le_of_decidable_lt a b with | is_true h₁ := match decidable_le_of_decidable_lt b a with | is_true h₂ := is_true (le_antisymm h₁ h₂) | is_false h₂ := is_false (λ he : a = b, h₂ (he ▸ le_refl a)) end | is_false h₁ := is_false (λ he : a = b, h₁ (he ▸ le_refl a)) end class decidable_linear_order (α : Type u) extends linear_strong_order_pair α := (decidable_lt : decidable_rel lt) (decidable_le : decidable_rel le) -- TODO(Leo): add default value using decidable_le_of_decidable_lt (decidable_eq : decidable_eq α) -- TODO(Leo): add default value using decidable_eq_of_decidable_lt instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt α a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := decidable_linear_order.decidable_le α a b instance [decidable_linear_order α] (a b : α) : decidable (a = b) := decidable_linear_order.decidable_eq α a b lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁)))
744ed15aef3804649e6d1fb200fa2a1c537e658d
26ac254ecb57ffcb886ff709cf018390161a9225
/src/tactic/linarith/elimination.lean
93cee426079d2c49bdb9aa3c3bf217bd626694a7
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
14,008
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.linarith.datatypes /-! # The Fourier-Motzkin elimination procedure The Fourier-Motzkin procedure is a variable elimination method for linear inequalities. <https://en.wikipedia.org/wiki/Fourier%E2%80%93Motzkin_elimination> Given a set of linear inequalities `comps = {tᵢ Rᵢ 0}`, we aim to eliminate a single variable `a` from the set. We partition `comps` into `comps_pos`, `comps_neg`, and `comps_zero`, where `comps_pos` contains the comparisons `tᵢ Rᵢ 0` in which the coefficient of `a` in `tᵢ` is positive, and similar. For each pair of comparisons `tᵢ Rᵢ 0 ∈ comps_pos`, `tⱼ Rⱼ 0 ∈ comps_neg`, we compute coefficients `vᵢ, vⱼ ∈ ℕ` such that `vᵢ*tᵢ + vⱼ*tⱼ` cancels out `a`. We collect these sums `vᵢ*tᵢ + vⱼ*tⱼ R' 0` in a set `S` and set `comps' = S ∪ comps_zero`, a new set of comparisons in which `a` has been eliminated. Theorem: `comps` and `comps'` are equisatisfiable. We recursively eliminate all variables from the system. If we derive an empty clause `0 < 0`, we conclude that the original system was unsatisfiable. -/ open native namespace linarith /-! ### Datatypes The `comp_source` and `pcomp` datatypes are specific to the FM elimination routine; they are not shared with other components of `linarith`. -/ /-- `comp_source` tracks the source of a comparison. The atomic source of a comparison is an assumption, indexed by a natural number. Two comparisons can be added to produce a new comparison, and one comparison can be scaled by a natural number to produce a new comparison. -/ @[derive inhabited] inductive comp_source : Type | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source /-- Given a `comp_source` `cs`, `cs.flatten` maps an assumption index to the number of copies of that assumption that appear in the history of `cs`. For example, suppose `cs` is produced by scaling assumption 2 by 5, and adding to that the sum of assumptions 1 and 2. `cs.flatten` maps `1 ↦ 1, 2 ↦ 6`. -/ 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) /-- Formats a `comp_source` for printing. -/ 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⟩ /-- A `pcomp` stores a linear comparison `Σ cᵢ*xᵢ R 0`, along with information about how this comparison was derived. The original expressions fed into `linarith` are each assigned a unique natural number label. The *historical set* `pcomp.history` stores the labels of expressions that were used in deriving the current `pcomp`. Variables are also indexed by natural numbers. The sets `pcomp.effective`, `pcomp.implicit`, and `pcomp.vars` contain variable indices. * `pcomp.vars` contains the variables that appear in `pcomp.c`. We store them in `pcomp` to avoid recomputing the set, which requires folding over a list. (TODO: is this really needed?) * `pcomp.effective` contains the variables that have been effectively eliminated from `pcomp`. A variable `n` is said to be *effectively eliminated* in `pcomp` if the elimination of `n` produced at least one of the ancestors of `pcomp`. * `pcomp.implicit` contains the variables that have been implicitly eliminated from `pcomp`. A variable `n` is said to be *implicitly eliminated* in `pcomp` if it satisfies the following properties: - There is some `ancestor` of `pcomp` such that `n` appears in `ancestor.vars`. - `n` does not appear in `pcomp.vars`. - `n` was not effectively eliminated. We track these sets in order to compute whether the history of a `pcomp` is *minimal*. Checking this directly is expensive, but effective approximations can be defined in terms of these sets. During the variable elimination process, a `pcomp` with non-minimal history can be discarded. -/ meta structure pcomp : Type := (c : comp) (src : comp_source) (history : rb_set ℕ) (effective : rb_set ℕ) (implicit : rb_set ℕ) (vars : rb_set ℕ) /-- Any comparison whose history is not minimal is redundant, and need not be included in the new set of comparisons. `elimed_ge : ℕ` is a natural number such that all variables with index ≥ `elimed_ge` have been removed from the system. This test is an overapproximation to minimality. It gives necessary but not sufficient conditions. If the history of `c` is minimal, then `c.maybe_minimal` is true, but `c.maybe_minimal` may also be true for some `c` with minimal history. Thus, if `c.maybe_minimal` is false, `c` is known not to be minimal and must be redundant. See http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.51.493&rep=rep1&type=pdf p.13 (Theorem 7). The condition described there considers only implicitly eliminated variables that have been officially eliminated from the system. This is not the case for every implicitly eliminated variable. Consider eliminating `z` from `{x + y + z < 0, x - y - z < 0}`. The result is the set `{2*x < 0}`; `y` is implicitly but not officially eliminated. This implementation of Fourier-Motzkin elimination processes variables in decreasing order of indices. Immediately after a step that eliminates variable `k`, variable `k'` has been eliminated iff `k' ≥ k`. Thus we can compute the intersection of officially and implicitly eliminated variables by taking the set of implicitly eliminated variables with indices ≥ `elimed_ge`. -/ meta def pcomp.maybe_minimal (c : pcomp) (elimed_ge : ℕ) : bool := c.history.size ≤ 1 + ((c.implicit.filter (≥ elimed_ge)).union c.effective).size /-- The `comp_source` field is ignored when comparing `pcomp`s. Two `pcomp`s proving the same comparison, with different sources, are considered equivalent. -/ meta def pcomp.cmp (p1 p2 : pcomp) : ordering := p1.c.cmp p2.c /-- `pcomp.scale c n` scales the coefficients of `c` by `n` and notes this in the `comp_source`. -/ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := {c with c := c.c.scale n, src := c.src.scale n} /-- `pcomp.add c1 c2 elim_var` creates the result of summing the linear comparisons `c1` and `c2`, during the process of eliminating the variable `elim_var`. The computation assumes, but does not enforce, that `elim_var` appears in both `c1` and `c2` and does not appear in the sum. Computing the sum of the two comparisons is easy; the complicated details lie in tracking the additional fields of `pcomp`. * The historical set `pcomp.history` of `c1 + c2` is the union of the two historical sets. * We recompute the variables that appear in `c1 + c2` from the newly created `linexp`, since some may have been implicitly eliminated. * The effectively eliminated variables of `c1 + c2` are the union of the two effective sets, with `elim_var` inserted. * The implicitly eliminated variables of `c1 + c2` are those that appear in at least one of `c1.vars` and `c2.vars` but not in `(c1 + c2).vars`, excluding `elim_var`. -/ meta def pcomp.add (c1 c2 : pcomp) (elim_var : ℕ) : pcomp := let c := c1.c.add c2.c, src := c1.src.add c2.src, history := c1.history.union c2.history, vars := native.rb_set.of_list c.vars, effective := (c1.effective.union c2.effective).insert elim_var, implicit := ((c1.vars.union c2.vars).sdiff vars).erase elim_var in ⟨c, src, history, effective, implicit, vars⟩ /-- `pcomp.assump c n` creates a `pcomp` whose comparison is `c` and whose source is `comp_source.assump n`, that is, `c` is derived from the `n`th hypothesis. The history is the singleton set `{n}`. No variables have been eliminated (effectively or implicitly). -/ meta def pcomp.assump (c : comp) (n : ℕ) : pcomp := { c := c, src := comp_source.assump n, history := mk_rb_set.insert n, effective := mk_rb_set, implicit := mk_rb_set, vars := rb_set.of_list c.vars } meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ /-- Creates an empty set of `pcomp`s, sorted using `pcomp.cmp`. This should always be used instead of `mk_rb_map` for performance reasons. -/ meta def mk_pcomp_set : rb_set pcomp := rb_map.mk_core unit pcomp.cmp /-! ### Elimination procedure -/ /-- If `c1` and `c2` both contain variable `a` with opposite coefficients, produces `v1` and `v2` such that `a` has been cancelled in `v1*c1 + v2*c2`. -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ) := 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'⟩ else none /-- `pelim_var p1 p2` calls `elim_var` on the `comp` components of `p1` and `p2`. If this returns `v1` and `v2`, it creates a new `pcomp` equal to `v1*p1 + v2*p2`, and tracks this in the `comp_source`. -/ meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2) ← elim_var p1.c p2.c a, return $ (p1.scale n1).add (p2.scale n2) a /-- A `pcomp` represents a contradiction if its `comp` field represents a contradiction. -/ meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr /-- `elim_var_with_set a p comps` collects the result of calling `pelim_var p p' a` for every `p' ∈ comps`. -/ meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := comps.fold mk_pcomp_set $ λ pc s, match pelim_var p pc a with | some pc := if pc.maybe_minimal a then s.insert pc else s | none := s end /-- The state for the elimination monad. * `max_var`: the largest variable index that has not been eliminated. * `comps`: a set of comparisons The elimination procedure proceeds by eliminating variable `v` from `comps` progressively in decreasing order. -/ meta structure linarith_structure : Type := (max_var : ℕ) (comps : rb_set pcomp) /-- The linarith monad extends an exceptional monad with a `linarith_structure` state. An exception produces a contradictory `pcomp`. -/ @[reducible, derive [monad, monad_except pcomp]] meta def linarith_monad : Type → Type := state_t linarith_structure (except_t pcomp id) /-- Returns the current max variable. -/ meta def get_max_var : linarith_monad ℕ := linarith_structure.max_var <$> get /-- Return the current comparison set. -/ meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get /-- Throws an exception if a contradictory `pcomp` is contained in the current state. -/ 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 /-- Updates the current state with a new max variable and comparisons, and calls `validate` to check for a contradiction. -/ meta def update (max_var : ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨max_var, comps⟩ >> validate /-- `split_set_by_var_sign a comps` partitions the set `comps` into three parts. * `pos` contains the elements of `comps` in which `a` has a positive coefficient. * `neg` contains the elements of `comps` in which `a` has a negative coefficient. * `not_present` contains the elements of `comps` in which `a` has coefficient 0. Returns `(pos, neg, not_present)`. -/ meta def split_set_by_var_sign (a : ℕ) (comps : rb_set pcomp) : rb_set pcomp × rb_set pcomp × rb_set pcomp := comps.fold ⟨mk_pcomp_set, mk_pcomp_set, mk_pcomp_set⟩ $ λ pc ⟨pos, neg, not_present⟩, let n := pc.c.coeff_of a in if n > 0 then ⟨pos.insert pc, neg, not_present⟩ else if n < 0 then ⟨pos, neg.insert pc, not_present⟩ else ⟨pos, neg, not_present.insert pc⟩ /-- `monad.elim_var a` performs one round of Fourier-Motzkin elimination, eliminating the variable `a` from the `linarith` state. -/ meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_max_var, when (a ≤ vs) $ do ⟨pos, neg, not_present⟩ ← split_set_by_var_sign a <$> get_comps, let cs' := pos.fold not_present (λ p s, s.union (elim_with_set a p neg)), update (vs - 1) cs' /-- `elim_all_vars` eliminates all variables from the linarith state, leaving it with a set of ground comparisons. If this succeeds without exception, the original `linarith` state is consistent. -/ meta def elim_all_vars : linarith_monad unit := do mv ← get_max_var, (list.range $ mv + 1).reverse.mmap' monad.elim_var /-- `mk_linarith_structure hyps vars` takes a list of hypotheses and the largest variable present in those hypotheses. It produces an initial state for the elimination monad. -/ meta def mk_linarith_structure (hyps : list comp) (max_var : ℕ) : linarith_structure := let pcomp_list : list pcomp := hyps.enum.map $ λ ⟨n, cmp⟩, pcomp.assump cmp n, pcomp_set := rb_set.of_list_core mk_pcomp_set pcomp_list in ⟨max_var, pcomp_set⟩ /-- `produce_certificate hyps vars` tries to derive a contradiction from the comparisons in `hyps` by eliminating all variables ≤ `max_var`. If successful, it returns a map `coeff : ℕ → ℕ` as a certificate. This map represents that we can find a contradiction by taking the sum `∑ (coeff i) * hyps[i]`. -/ meta def fourier_motzkin.produce_certificate (hyps : list comp) (max_var : ℕ) : option (rb_map ℕ ℕ) := let state := mk_linarith_structure hyps max_var in match except_t.run (state_t.run (validate >> elim_all_vars) state) with | (except.ok (a, _)) := none | (except.error contr) := contr.src.flatten end end linarith
15707518cb3dae83ee0acd4b8bf0760a7b227b0a
32317185abf7e7c963f4c67c190aec61af6b3628
/tests/lean/extra/bag.lean
7ed165ae7bae1b512328b25b0a385e5a466c63f5
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,421
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 Finite bags. -/ import data.nat data.list.perm algebra.binary open nat quot list subtype binary function eq.ops algebra open [decl] perm variable {A : Type} definition bag.setoid [instance] (A : Type) : setoid (list A) := setoid.mk (@perm A) (mk_equivalence (@perm A) (@perm.refl A) (@perm.symm A) (@perm.trans A)) definition bag (A : Type) : Type := quot (bag.setoid A) namespace bag definition of_list (l : list A) : bag A := ⟦l⟧ definition empty : bag A := of_list nil definition singleton (a : A) : bag A := of_list [a] definition insert (a : A) (b : bag A) : bag A := quot.lift_on b (λ l, ⟦a::l⟧) (λ l₁ l₂ h, quot.sound (perm.skip a h)) lemma insert_empty_eq_singleton (a : A) : insert a empty = singleton a := rfl definition insert.comm (a₁ a₂ : A) (b : bag A) : insert a₁ (insert a₂ b) = insert a₂ (insert a₁ b) := quot.induction_on b (λ l, quot.sound !perm.swap) definition append (b₁ b₂ : bag A) : bag A := quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦l₁++l₂⟧) (λ l₁ l₂ l₃ l₄ h₁ h₂, quot.sound (perm_app h₁ h₂)) infix ++ := append lemma append.comm (b₁ b₂ : bag A) : b₁ ++ b₂ = b₂ ++ b₁ := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, quot.sound !perm_app_comm) lemma append.assoc (b₁ b₂ b₃ : bag A) : (b₁ ++ b₂) ++ b₃ = b₁ ++ (b₂ ++ b₃) := quot.induction_on₃ b₁ b₂ b₃ (λ l₁ l₂ l₃, quot.sound (by rewrite list.append.assoc; apply perm.refl)) lemma append_empty_left (b : bag A) : empty ++ b = b := quot.induction_on b (λ l, quot.sound (by rewrite append_nil_left; apply perm.refl)) lemma append_empty_right (b : bag A) : b ++ empty = b := quot.induction_on b (λ l, quot.sound (by rewrite append_nil_right; apply perm.refl)) lemma append_insert_left (a : A) (b₁ b₂ : bag A) : insert a b₁ ++ b₂ = insert a (b₁ ++ b₂) := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, quot.sound (by rewrite append_cons; apply perm.refl)) lemma append_insert_right (a : A) (b₁ b₂ : bag A) : b₁ ++ insert a b₂ = insert a (b₁ ++ b₂) := calc b₁ ++ insert a b₂ = insert a b₂ ++ b₁ : append.comm ... = insert a (b₂ ++ b₁) : append_insert_left ... = insert a (b₁ ++ b₂) : append.comm protected lemma induction_on [recursor 3] {C : bag A → Prop} (b : bag A) (h₁ : C empty) (h₂ : ∀ a b, C b → C (insert a b)) : C b := quot.induction_on b (λ l, list.induction_on l h₁ (λ h t ih, h₂ h ⟦t⟧ ih)) section decidable_eq variable [decA : decidable_eq A] include decA open decidable definition has_decidable_eq [instance] (b₁ b₂ : bag A) : decidable (b₁ = b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match decidable_perm l₁ l₂ with | inl h := inl (quot.sound h) | inr h := inr (λ n, absurd (quot.exact n) h) end) end decidable_eq section count variable [decA : decidable_eq A] include decA definition count (a : A) (b : bag A) : nat := quot.lift_on b (λ l, count a l) (λ l₁ l₂ h, count_eq_of_perm h a) lemma count_empty (a : A) : count a empty = 0 := rfl lemma count_insert (a : A) (b : bag A) : count a (insert a b) = succ (count a b) := quot.induction_on b (λ l, begin unfold [insert, count], rewrite count_cons_eq end) lemma count_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : count a₁ (insert a₂ b) = count a₁ b := quot.induction_on b (λ l, begin unfold [insert, count], rewrite (count_cons_of_ne h) end) lemma count_singleton (a : A) : count a (singleton a) = 1 := begin rewrite [-insert_empty_eq_singleton, count_insert] end lemma count_append (a : A) (b₁ b₂ : bag A) : count a (append b₁ b₂) = count a b₁ + count a b₂ := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, begin unfold [append, count], rewrite list.count_append end) open perm decidable protected lemma ext {b₁ b₂ : bag A} : (∀ a, count a b₁ = count a b₂) → b₁ = b₂ := quot.induction_on₂ b₁ b₂ (λ l₁ l₂ (h : ∀ a, count a ⟦l₁⟧ = count a ⟦l₂⟧), have gen : ∀ (l₁ l₂ : list A), (∀ a, list.count a l₁ = list.count a l₂) → l₁ ~ l₂ | [] [] h₁ := !perm.refl | [] (a₂::s₂) h₁ := assert list.count a₂ [] = list.count a₂ (a₂::s₂), from h₁ a₂, by rewrite [count_nil at this, count_cons_eq at this]; contradiction | (a::s₁) s₂ h₁ := assert g₁ : list.count a (a::s₁) > 0, from count_gt_zero_of_mem !mem_cons, assert list.count a (a::s₁) = list.count a s₂, from h₁ a, assert list.count a s₂ > 0, by rewrite [-this]; exact g₁, have a ∈ s₂, from mem_of_count_gt_zero this, have ∃ l r, s₂ = l++(a::r), from mem_split this, obtain l r (e₁ : s₂ = l++(a::r)), from this, have ∀ a, list.count a s₁ = list.count a (l++r), from take a₁, assert e₂ : list.count a₁ (a::s₁) = list.count a₁ (l++(a::r)), by rewrite -e₁; exact h₁ a₁, by_cases (suppose a₁ = a, begin rewrite [-this at e₂, list.count_append at e₂, *count_cons_eq at e₂, add_succ at e₂], injection e₂ with e₃, rewrite e₃, rewrite list.count_append end) (suppose a₁ ≠ a, by rewrite [list.count_append at e₂, *count_cons_of_ne this at e₂, e₂, list.count_append]), have ih : s₁ ~ l++r, from gen s₁ (l++r) this, calc a::s₁ ~ a::(l++r) : perm.skip a ih ... ~ l++(a::r) : perm_middle ... = s₂ : e₁, quot.sound (gen l₁ l₂ h)) definition insert.inj {a : A} {b₁ b₂ : bag A} : insert a b₁ = insert a b₂ → b₁ = b₂ := assume h, bag.ext (take x, assert e : count x (insert a b₁) = count x (insert a b₂), by rewrite h, by_cases (suppose x = a, begin subst x, rewrite [*count_insert at e], injection e, assumption end) (suppose x ≠ a, begin rewrite [*count_insert_of_ne this at e], assumption end)) end count section extract open decidable variable [decA : decidable_eq A] include decA definition extract (a : A) (b : bag A) : bag A := quot.lift_on b (λ l, ⟦filter (λ c, c ≠ a) l⟧) (λ l₁ l₂ h, quot.sound (perm_filter h)) lemma extract_singleton (a : A) : extract a (singleton a) = empty := begin unfold [extract, singleton, of_list, filter], rewrite [if_neg (λ h : a ≠ a, absurd rfl h)] end lemma extract_insert (a : A) (b : bag A) : extract a (insert a b) = extract a b := quot.induction_on b (λ l, begin unfold [insert, extract], rewrite [@filter_cons_of_neg _ (λ c, c ≠ a) _ _ l (not_not_intro (eq.refl a))] end) lemma extract_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : extract a₁ (insert a₂ b) = insert a₂ (extract a₁ b) := quot.induction_on b (λ l, begin unfold [insert, extract], rewrite [@filter_cons_of_pos _ (λ c, c ≠ a₁) _ _ l (ne.symm h)] end) lemma count_extract (a : A) (b : bag A) : count a (extract a b) = 0 := bag.induction_on b rfl (λ c b ih, by_cases (suppose a = c, begin subst c, rewrite [extract_insert, ih] end) (suppose a ≠ c, begin rewrite [extract_insert_of_ne this, count_insert_of_ne this, ih] end)) lemma count_extract_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : count a₁ (extract a₂ b) = count a₁ b := bag.induction_on b rfl (take x b ih, by_cases (suppose x = a₁, begin subst x, rewrite [extract_insert_of_ne (ne.symm h), *count_insert, ih] end) (suppose x ≠ a₁, by_cases (suppose x = a₂, begin subst x, rewrite [extract_insert, ih, count_insert_of_ne h] end) (suppose x ≠ a₂, begin rewrite [count_insert_of_ne (ne.symm `x ≠ a₁`), extract_insert_of_ne (ne.symm this)], rewrite [count_insert_of_ne (ne.symm `x ≠ a₁`), ih] end))) end extract section erase variable [decA : decidable_eq A] include decA definition erase (a : A) (b : bag A) : bag A := quot.lift_on b (λ l, ⟦erase a l⟧) (λ l₁ l₂ h, quot.sound (erase_perm_erase_of_perm _ h)) lemma erase_empty (a : A) : erase a empty = empty := rfl lemma erase_insert (a : A) (b : bag A) : erase a (insert a b) = b := quot.induction_on b (λ l, quot.sound (by rewrite erase_cons_head; apply perm.refl)) lemma erase_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : erase a₁ (insert a₂ b) = insert a₂ (erase a₁ b) := quot.induction_on b (λ l, quot.sound (by rewrite (erase_cons_tail _ h); apply perm.refl)) end erase section member variable [decA : decidable_eq A] include decA definition mem (a : A) (b : bag A) := count a b > 0 infix ∈ := mem lemma mem_def (a : A) (b : bag A) : (a ∈ b) = (count a b > 0) := rfl lemma mem_insert (a : A) (b : bag A) : a ∈ insert a b := begin unfold mem, rewrite count_insert, exact dec_trivial end lemma mem_of_list_iff_mem (a : A) (l : list A) : a ∈ of_list l ↔ a ∈ l := iff.intro !mem_of_count_gt_zero !count_gt_zero_of_mem lemma count_of_list_eq_count (a : A) (l : list A) : count a (of_list l) = list.count a l := rfl end member section union_inter variable [decA : decidable_eq A] include decA open perm decidable private definition union_list (l₁ l₂ : list A) := erase_dup (l₁ ++ l₂) private lemma perm_union_list {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : union_list l₁ l₂ ~ union_list l₃ l₄ := perm_erase_dup_of_perm (perm_app h₁ h₂) private lemma nodup_union_list (l₁ l₂ : list A) : nodup (union_list l₁ l₂) := !nodup_erase_dup private definition not_mem_of_not_mem_union_list_left {a : A} {l₁ l₂ : list A} (h : a ∉ union_list l₁ l₂) : a ∉ l₁ := suppose a ∈ l₁, have a ∈ l₁ ++ l₂, from mem_append_left _ this, have a ∈ erase_dup (l₁ ++ l₂), from mem_erase_dup this, absurd this h private definition not_mem_of_not_mem_union_list_right {a : A} {l₁ l₂ : list A} (h : a ∉ union_list l₁ l₂) : a ∉ l₂ := suppose a ∈ l₂, have a ∈ l₁ ++ l₂, from mem_append_right _ this, have a ∈ erase_dup (l₁ ++ l₂), from mem_erase_dup this, absurd this h private definition gen : nat → A → list A | 0 a := nil | (n+1) a := a :: gen n a private lemma not_mem_gen_of_ne {a b : A} (h : a ≠ b) : ∀ n, a ∉ gen n b | 0 := !not_mem_nil | (n+1) := not_mem_cons_of_ne_of_not_mem h (not_mem_gen_of_ne n) private lemma count_gen : ∀ (a : A) (n : nat), list.count a (gen n a) = n | a 0 := rfl | a (n+1) := begin unfold gen, rewrite [count_cons_eq, count_gen] end private lemma count_gen_eq_zero_of_ne {a b : A} (h : a ≠ b) : ∀ n, list.count a (gen n b) = 0 | 0 := rfl | (n+1) := begin unfold gen, rewrite [count_cons_of_ne h, count_gen_eq_zero_of_ne] end private definition max_count (l₁ l₂ : list A) : list A → list A | [] := [] | (a::l) := if list.count a l₁ ≥ list.count a l₂ then gen (list.count a l₁) a ++ max_count l else gen (list.count a l₂) a ++ max_count l private definition min_count (l₁ l₂ : list A) : list A → list A | [] := [] | (a::l) := if list.count a l₁ ≤ list.count a l₂ then gen (list.count a l₁) a ++ min_count l else gen (list.count a l₂) a ++ min_count l private lemma not_mem_max_count_of_not_mem (l₁ l₂ : list A) : ∀ {a l}, a ∉ l → a ∉ max_count l₁ l₂ l | a [] h := !not_mem_nil | a (b::l) h := assert ih : a ∉ max_count l₁ l₂ l, from not_mem_max_count_of_not_mem (not_mem_of_not_mem_cons h), assert a ≠ b, from ne_of_not_mem_cons h, by_cases (suppose list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_pos this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) (suppose ¬ list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_neg this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) private lemma max_count_eq (l₁ l₂ : list A) : ∀ {a : A} {l : list A}, a ∈ l → nodup l → list.count a (max_count l₁ l₂ l) = max (list.count a l₁) (list.count a l₂) | a [] h₁ h₂ := absurd h₁ !not_mem_nil | a (b::l) h₁ h₂ := assert nodup l, from nodup_of_nodup_cons h₂, assert b ∉ l, from not_mem_of_nodup_cons h₂, or.elim h₁ (suppose a = b, have a ∉ l, by rewrite this; assumption, assert a ∉ max_count l₁ l₂ l, from not_mem_max_count_of_not_mem l₁ l₂ this, by_cases (suppose i : list.count a l₁ ≥ list.count a l₂, begin unfold max_count, subst b, rewrite [if_pos i, list.count_append, count_gen, max_eq_left i, count_eq_zero_of_not_mem `a ∉ max_count l₁ l₂ l`] end) (suppose i : ¬ list.count a l₁ ≥ list.count a l₂, begin unfold max_count, subst b, rewrite [if_neg i, list.count_append, count_gen, max_eq_right_of_lt (lt_of_not_ge i), count_eq_zero_of_not_mem `a ∉ max_count l₁ l₂ l`] end)) (suppose a ∈ l, assert a ≠ b, from suppose a = b, by subst b; contradiction, assert ih : list.count a (max_count l₁ l₂ l) = max (list.count a l₁) (list.count a l₂), from max_count_eq `a ∈ l` `nodup l`, by_cases (suppose i : list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_pos i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end) (suppose i : ¬ list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_neg i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end)) private lemma not_mem_min_count_of_not_mem (l₁ l₂ : list A) : ∀ {a l}, a ∉ l → a ∉ min_count l₁ l₂ l | a [] h := !not_mem_nil | a (b::l) h := assert ih : a ∉ min_count l₁ l₂ l, from not_mem_min_count_of_not_mem (not_mem_of_not_mem_cons h), assert a ≠ b, from ne_of_not_mem_cons h, by_cases (suppose list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_pos this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) (suppose ¬ list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_neg this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) private lemma min_count_eq (l₁ l₂ : list A) : ∀ {a : A} {l : list A}, a ∈ l → nodup l → list.count a (min_count l₁ l₂ l) = min (list.count a l₁) (list.count a l₂) | a [] h₁ h₂ := absurd h₁ !not_mem_nil | a (b::l) h₁ h₂ := assert nodup l, from nodup_of_nodup_cons h₂, assert b ∉ l, from not_mem_of_nodup_cons h₂, or.elim h₁ (suppose a = b, have a ∉ l, by rewrite this; assumption, assert a ∉ min_count l₁ l₂ l, from not_mem_min_count_of_not_mem l₁ l₂ this, by_cases (suppose i : list.count a l₁ ≤ list.count a l₂, begin unfold min_count, subst b, rewrite [if_pos i, list.count_append, count_gen, min_eq_left i, count_eq_zero_of_not_mem `a ∉ min_count l₁ l₂ l`] end) (suppose i : ¬ list.count a l₁ ≤ list.count a l₂, begin unfold min_count, subst b, rewrite [if_neg i, list.count_append, count_gen, min_eq_right (le_of_lt (lt_of_not_ge i)), count_eq_zero_of_not_mem `a ∉ min_count l₁ l₂ l`] end)) (suppose a ∈ l, assert a ≠ b, from suppose a = b, by subst b; contradiction, assert ih : list.count a (min_count l₁ l₂ l) = min (list.count a l₁) (list.count a l₂), from min_count_eq `a ∈ l` `nodup l`, by_cases (suppose i : list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_pos i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end) (suppose i : ¬ list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_neg i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end)) private lemma perm_max_count_left {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : ∀ l, max_count l₁ l₂ l ~ max_count l₃ l₄ l | [] := by esimp | (a::l) := assert e₁ : list.count a l₁ = list.count a l₃, from count_eq_of_perm h₁ a, assert e₂ : list.count a l₂ = list.count a l₄, from count_eq_of_perm h₂ a, by_cases (suppose list.count a l₁ ≥ list.count a l₂, begin unfold max_count, rewrite [-e₁, -e₂, *if_pos this], exact perm_app !perm.refl !perm_max_count_left end) (suppose ¬ list.count a l₁ ≥ list.count a l₂, begin unfold max_count, rewrite [-e₁, -e₂, *if_neg this], exact perm_app !perm.refl !perm_max_count_left end) private lemma perm_app_left_comm (l₁ l₂ l₃ : list A) : l₁ ++ (l₂ ++ l₃) ~ l₂ ++ (l₁ ++ l₃) := calc l₁ ++ (l₂ ++ l₃) = (l₁ ++ l₂) ++ l₃ : list.append.assoc ... ~ (l₂ ++ l₁) ++ l₃ : perm_app !perm_app_comm !perm.refl ... = l₂ ++ (l₁ ++ l₃) : list.append.assoc private lemma perm_max_count_right {l r : list A} (h : l ~ r) : ∀ l₁ l₂, max_count l₁ l₂ l ~ max_count l₁ l₂ r := perm.induction_on h (λ l₁ l₂, !perm.refl) (λ x s₁ s₂ p ih l₁ l₂, by_cases (suppose i : list.count x l₁ ≥ list.count x l₂, begin unfold max_count, rewrite [*if_pos i], exact perm_app !perm.refl !ih end) (suppose i : ¬ list.count x l₁ ≥ list.count x l₂, begin unfold max_count, rewrite [*if_neg i], exact perm_app !perm.refl !ih end)) (λ x y l l₁ l₂, by_cases (suppose i₁ : list.count x l₁ ≥ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_pos i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_pos i₁, *if_neg i₂], apply perm_app_left_comm end)) (suppose i₁ : ¬ list.count x l₁ ≥ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_neg i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_neg i₁, *if_neg i₂], apply perm_app_left_comm end))) (λ s₁ s₂ s₃ p₁ p₂ ih₁ ih₂ l₁ l₂, perm.trans (ih₁ l₁ l₂) (ih₂ l₁ l₂)) private lemma perm_max_count {l₁ l₂ l₃ r₁ r₂ r₃ : list A} (p₁ : l₁ ~ r₁) (p₂ : l₂ ~ r₂) (p₃ : l₃ ~ r₃) : max_count l₁ l₂ l₃ ~ max_count r₁ r₂ r₃ := calc max_count l₁ l₂ l₃ ~ max_count r₁ r₂ l₃ : perm_max_count_left p₁ p₂ ... ~ max_count r₁ r₂ r₃ : perm_max_count_right p₃ private lemma perm_min_count_left {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : ∀ l, min_count l₁ l₂ l ~ min_count l₃ l₄ l | [] := by esimp | (a::l) := assert e₁ : list.count a l₁ = list.count a l₃, from count_eq_of_perm h₁ a, assert e₂ : list.count a l₂ = list.count a l₄, from count_eq_of_perm h₂ a, by_cases (suppose list.count a l₁ ≤ list.count a l₂, begin unfold min_count, rewrite [-e₁, -e₂, *if_pos this], exact perm_app !perm.refl !perm_min_count_left end) (suppose ¬ list.count a l₁ ≤ list.count a l₂, begin unfold min_count, rewrite [-e₁, -e₂, *if_neg this], exact perm_app !perm.refl !perm_min_count_left end) private lemma perm_min_count_right {l r : list A} (h : l ~ r) : ∀ l₁ l₂, min_count l₁ l₂ l ~ min_count l₁ l₂ r := perm.induction_on h (λ l₁ l₂, !perm.refl) (λ x s₁ s₂ p ih l₁ l₂, by_cases (suppose i : list.count x l₁ ≤ list.count x l₂, begin unfold min_count, rewrite [*if_pos i], exact perm_app !perm.refl !ih end) (suppose i : ¬ list.count x l₁ ≤ list.count x l₂, begin unfold min_count, rewrite [*if_neg i], exact perm_app !perm.refl !ih end)) (λ x y l l₁ l₂, by_cases (suppose i₁ : list.count x l₁ ≤ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_pos i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_pos i₁, *if_neg i₂], apply perm_app_left_comm end)) (suppose i₁ : ¬ list.count x l₁ ≤ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_neg i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_neg i₁, *if_neg i₂], apply perm_app_left_comm end))) (λ s₁ s₂ s₃ p₁ p₂ ih₁ ih₂ l₁ l₂, perm.trans (ih₁ l₁ l₂) (ih₂ l₁ l₂)) private lemma perm_min_count {l₁ l₂ l₃ r₁ r₂ r₃ : list A} (p₁ : l₁ ~ r₁) (p₂ : l₂ ~ r₂) (p₃ : l₃ ~ r₃) : min_count l₁ l₂ l₃ ~ min_count r₁ r₂ r₃ := calc min_count l₁ l₂ l₃ ~ min_count r₁ r₂ l₃ : perm_min_count_left p₁ p₂ ... ~ min_count r₁ r₂ r₃ : perm_min_count_right p₃ definition union (b₁ b₂ : bag A) : bag A := quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦max_count l₁ l₂ (union_list l₁ l₂)⟧) (λ l₁ l₂ l₃ l₄ p₁ p₂, quot.sound (perm_max_count p₁ p₂ (perm_union_list p₁ p₂))) infix ∪ := union definition inter (b₁ b₂ : bag A) : bag A := quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦min_count l₁ l₂ (union_list l₁ l₂)⟧) (λ l₁ l₂ l₃ l₄ p₁ p₂, quot.sound (perm_min_count p₁ p₂ (perm_union_list p₁ p₂))) infix ∩ := inter lemma count_union (a : A) (b₁ b₂ : bag A) : count a (b₁ ∪ b₂) = max (count a b₁) (count a b₂) := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, by_cases (suppose a ∈ union_list l₁ l₂, !max_count_eq this !nodup_union_list) (suppose ¬ a ∈ union_list l₁ l₂, assert ¬ a ∈ l₁, from not_mem_of_not_mem_union_list_left `¬ a ∈ union_list l₁ l₂`, assert ¬ a ∈ l₂, from not_mem_of_not_mem_union_list_right `¬ a ∈ union_list l₁ l₂`, assert n : ¬ a ∈ max_count l₁ l₂ (union_list l₁ l₂), from not_mem_max_count_of_not_mem l₁ l₂ `¬ a ∈ union_list l₁ l₂`, begin unfold [union, count], rewrite [count_eq_zero_of_not_mem `¬ a ∈ l₁`, count_eq_zero_of_not_mem `¬ a ∈ l₂`, max_self], rewrite [count_eq_zero_of_not_mem n] end)) lemma count_inter (a : A) (b₁ b₂ : bag A) : count a (b₁ ∩ b₂) = min (count a b₁) (count a b₂) := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, by_cases (suppose a ∈ union_list l₁ l₂, !min_count_eq this !nodup_union_list) (suppose ¬ a ∈ union_list l₁ l₂, assert ¬ a ∈ l₁, from not_mem_of_not_mem_union_list_left `¬ a ∈ union_list l₁ l₂`, assert ¬ a ∈ l₂, from not_mem_of_not_mem_union_list_right `¬ a ∈ union_list l₁ l₂`, assert n : ¬ a ∈ min_count l₁ l₂ (union_list l₁ l₂), from not_mem_min_count_of_not_mem l₁ l₂ `¬ a ∈ union_list l₁ l₂`, begin unfold [inter, count], rewrite [count_eq_zero_of_not_mem `¬ a ∈ l₁`, count_eq_zero_of_not_mem `¬ a ∈ l₂`, min_self], rewrite [count_eq_zero_of_not_mem n] end)) lemma union.comm (b₁ b₂ : bag A) : b₁ ∪ b₂ = b₂ ∪ b₁ := bag.ext (λ a, by rewrite [*count_union, max.comm]) lemma union.assoc (b₁ b₂ b₃ : bag A) : (b₁ ∪ b₂) ∪ b₃ = b₁ ∪ (b₂ ∪ b₃) := bag.ext (λ a, by rewrite [*count_union, max.assoc]) theorem union.left_comm (s₁ s₂ s₃ : bag A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union.comm union.assoc s₁ s₂ s₃ lemma union_self (b : bag A) : b ∪ b = b := bag.ext (λ a, by rewrite [*count_union, max_self]) lemma union_empty (b : bag A) : b ∪ empty = b := bag.ext (λ a, by rewrite [*count_union, count_empty, max_zero]) lemma empty_union (b : bag A) : empty ∪ b = b := calc empty ∪ b = b ∪ empty : union.comm ... = b : union_empty lemma inter.comm (b₁ b₂ : bag A) : b₁ ∩ b₂ = b₂ ∩ b₁ := bag.ext (λ a, by rewrite [*count_inter, min.comm]) lemma inter.assoc (b₁ b₂ b₃ : bag A) : (b₁ ∩ b₂) ∩ b₃ = b₁ ∩ (b₂ ∩ b₃) := bag.ext (λ a, by rewrite [*count_inter, min.assoc]) theorem inter.left_comm (s₁ s₂ s₃ : bag A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter.comm inter.assoc s₁ s₂ s₃ lemma inter_self (b : bag A) : b ∩ b = b := bag.ext (λ a, by rewrite [*count_inter, min_self]) lemma inter_empty (b : bag A) : b ∩ empty = empty := bag.ext (λ a, by rewrite [*count_inter, count_empty, min_zero]) lemma empty_inter (b : bag A) : empty ∩ b = empty := calc empty ∩ b = b ∩ empty : inter.comm ... = empty : inter_empty lemma append_union_inter (b₁ b₂ : bag A) : (b₁ ∪ b₂) ++ (b₁ ∩ b₂) = b₁ ++ b₂ := bag.ext (λ a, begin rewrite [*count_append, count_inter, count_union], apply (or.elim (lt_or_ge (count a b₁) (count a b₂))), { intro H, rewrite [min_eq_left_of_lt H, max_eq_right_of_lt H, add.comm] }, { intro H, rewrite [min_eq_right H, max_eq_left H, add.comm] } end) lemma inter.left_distrib (b₁ b₂ b₃ : bag A) : b₁ ∩ (b₂ ∪ b₃) = (b₁ ∩ b₂) ∪ (b₁ ∩ b₃) := bag.ext (λ a, begin rewrite [*count_inter, *count_union, *count_inter], apply (@by_cases (count a b₁ ≤ count a b₂)), { intro H₁₂, apply (@by_cases (count a b₂ ≤ count a b₃)), { intro H₂₃, have H₁₃ : count a b₁ ≤ count a b₃, from le.trans H₁₂ H₂₃, rewrite [max_eq_right H₂₃, min_eq_left H₁₂, min_eq_left H₁₃, max_self]}, { intro H₂₃, rewrite [min_eq_left H₁₂, max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃) ], apply (@by_cases (count a b₁ ≤ count a b₃)), { intro H₁₃, rewrite [min_eq_left H₁₃, max_self, min_eq_left H₁₂] }, { intro H₁₃, rewrite [min.comm (count a b₁) (count a b₃), min_eq_left_of_lt (lt_of_not_ge H₁₃), min_eq_left H₁₂, max.comm, max_eq_right_of_lt (lt_of_not_ge H₁₃)]}}}, { intro H₁₂, apply (@by_cases (count a b₂ ≤ count a b₃)), { intro H₂₃, rewrite [max_eq_right H₂₃], apply (@by_cases (count a b₁ ≤ count a b₃)), { intro H₁₃, rewrite [min_eq_left H₁₃, min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂), max_eq_right_of_lt (lt_of_not_ge H₁₂)] }, { intro H₁₃, rewrite [min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₃), min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂), max_eq_right H₂₃] } }, { intro H₂₃, have H₁₃ : count a b₁ > count a b₃, from lt.trans (lt_of_not_ge H₂₃) (lt_of_not_ge H₁₂), rewrite [max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃), min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂)], rewrite [min.comm, min_eq_left_of_lt H₁₃, max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃)] } } end) lemma inter.right_distrib (b₁ b₂ b₃ : bag A) : (b₁ ∪ b₂) ∩ b₃ = (b₁ ∩ b₃) ∪ (b₂ ∩ b₃) := calc (b₁ ∪ b₂) ∩ b₃ = b₃ ∩ (b₁ ∪ b₂) : inter.comm ... = (b₃ ∩ b₁) ∪ (b₃ ∩ b₂) : inter.left_distrib ... = (b₁ ∩ b₃) ∪ (b₃ ∩ b₂) : inter.comm ... = (b₁ ∩ b₃) ∪ (b₂ ∩ b₃) : inter.comm end union_inter section subbag variable [decA : decidable_eq A] include decA definition subbag (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix ⊆ := subbag lemma subbag.refl (b : bag A) : b ⊆ b := take a, !le.refl lemma subbag.trans {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₂ → b₂ ⊆ b₃ → b₁ ⊆ b₃ := assume h₁ h₂, take a, le.trans (h₁ a) (h₂ a) lemma subbag.antisymm {b₁ b₂ : bag A} : b₁ ⊆ b₂ → b₂ ⊆ b₁ → b₁ = b₂ := assume h₁ h₂, bag.ext (take a, le.antisymm (h₁ a) (h₂ a)) lemma count_le_of_subbag {b₁ b₂ : bag A} : b₁ ⊆ b₂ → ∀ a, count a b₁ ≤ count a b₂ := assume h, h lemma subbag.intro {b₁ b₂ : bag A} : (∀ a, count a b₁ ≤ count a b₂) → b₁ ⊆ b₂ := assume h, h lemma empty_subbag (b : bag A) : empty ⊆ b := subbag.intro (take a, !zero_le) lemma eq_empty_of_subbag_empty {b : bag A} : b ⊆ empty → b = empty := assume h, subbag.antisymm h (empty_subbag b) lemma union_subbag_of_subbag_of_subbag {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₃ → b₂ ⊆ b₃ → b₁ ∪ b₂ ⊆ b₃ := assume h₁ h₂, subbag.intro (λ a, calc count a (b₁ ∪ b₂) = max (count a b₁) (count a b₂) : by rewrite count_union ... ≤ count a b₃ : max_le (h₁ a) (h₂ a)) lemma subbag_inter_of_subbag_of_subbag {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₂ → b₁ ⊆ b₃ → b₁ ⊆ b₂ ∩ b₃ := assume h₁ h₂, subbag.intro (λ a, calc count a b₁ ≤ min (count a b₂) (count a b₃) : le_min (h₁ a) (h₂ a) ... = count a (b₂ ∩ b₃) : by rewrite count_inter) lemma subbag_union_left (b₁ b₂ : bag A) : b₁ ⊆ b₁ ∪ b₂ := subbag.intro (take a, by rewrite [count_union]; apply le_max_left) lemma subbag_union_right (b₁ b₂ : bag A) : b₂ ⊆ b₁ ∪ b₂ := subbag.intro (take a, by rewrite [count_union]; apply le_max_right) lemma inter_subbag_left (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₁ := subbag.intro (take a, by rewrite [count_inter]; apply min_le_left) lemma inter_subbag_right (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₂ := subbag.intro (take a, by rewrite [count_inter]; apply min_le_right) lemma subbag_append_left (b₁ b₂ : bag A) : b₁ ⊆ b₁ ++ b₂ := subbag.intro (take a, by rewrite [count_append]; apply le_add_right) lemma subbag_append_right (b₁ b₂ : bag A) : b₂ ⊆ b₁ ++ b₂ := subbag.intro (take a, by rewrite [count_append]; apply le_add_left) lemma inter_subbag_union (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₁ ∪ b₂ := subbag.trans (inter_subbag_left b₁ b₂) (subbag_union_left b₁ b₂) open decidable lemma union_subbag_append (b₁ b₂ : bag A) : b₁ ∪ b₂ ⊆ b₁ ++ b₂ := subbag.intro (take a, begin rewrite [count_append, count_union], exact (or.elim !lt_or_ge) (suppose count a b₁ < count a b₂, by rewrite [max_eq_right_of_lt this]; apply le_add_left) (suppose count a b₁ ≥ count a b₂, by rewrite [max_eq_left this]; apply le_add_right) end) lemma subbag_insert (a : A) (b : bag A) : b ⊆ insert a b := subbag.intro (take x, by_cases (suppose x = a, by rewrite [this, count_insert]; apply le_succ) (suppose x ≠ a, by rewrite [count_insert_of_ne this])) lemma mem_of_subbag_of_mem {a : A} {b₁ b₂ : bag A} : b₁ ⊆ b₂ → a ∈ b₁ → a ∈ b₂ := assume h₁ h₂, have count a b₁ ≤ count a b₂, from count_le_of_subbag h₁ a, have count a b₁ > 0, from h₂, show count a b₂ > 0, from lt_of_lt_of_le `0 < count a b₁` `count a b₁ ≤ count a b₂` lemma extract_subbag (a : A) (b : bag A) : extract a b ⊆ b := subbag.intro (take x, by_cases (suppose x = a, by rewrite [this, count_extract]; apply zero_le) (suppose x ≠ a, by rewrite [count_extract_of_ne this])) open bool private definition subcount : list A → list A → bool | [] l₂ := tt | (a::l₁) l₂ := if list.count a (a::l₁) ≤ list.count a l₂ then subcount l₁ l₂ else ff private lemma all_of_subcount_eq_tt : ∀ {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ | [] l₂ h := take x, !zero_le | (a::l₁) l₂ h := take x, have subcount l₁ l₂ = tt, from by_contradiction (suppose subcount l₁ l₂ ≠ tt, assert subcount l₁ l₂ = ff, from eq_ff_of_ne_tt this, begin unfold subcount at h, rewrite [this at h, if_t_t at h], contradiction end), assert ih : ∀ a, list.count a l₁ ≤ list.count a l₂, from all_of_subcount_eq_tt this, assert i : list.count a (a::l₁) ≤ list.count a l₂, from by_contradiction (suppose ¬ list.count a (a::l₁) ≤ list.count a l₂, begin unfold subcount at h, rewrite [if_neg this at h], contradiction end), by_cases (suppose x = a, by rewrite this; apply i) (suppose x ≠ a, by rewrite [list.count_cons_of_ne this]; apply ih) private lemma ex_of_subcount_eq_ff : ∀ {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ | [] l₂ h := by contradiction | (a::l₁) l₂ h := by_cases (suppose i : list.count a (a::l₁) ≤ list.count a l₂, have subcount l₁ l₂ = ff, from by_contradiction (suppose subcount l₁ l₂ ≠ ff, assert subcount l₁ l₂ = tt, from eq_tt_of_ne_ff this, begin unfold subcount at h, rewrite [if_pos i at h, this at h], contradiction end), have ih : ∃ a, ¬ list.count a l₁ ≤ list.count a l₂, from ex_of_subcount_eq_ff this, obtain w hw, from ih, by_cases (suppose w = a, begin subst w, existsi a, rewrite list.count_cons_eq, apply not_lt_of_ge, apply le_of_lt (lt_of_not_ge hw) end) (suppose w ≠ a, exists.intro w (by rewrite (list.count_cons_of_ne `w ≠ a`); exact hw))) (suppose ¬ list.count a (a::l₁) ≤ list.count a l₂, exists.intro a this) definition decidable_subbag [instance] (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂ with | tt := suppose subcount l₁ l₂ = tt, inl (all_of_subcount_eq_tt this) | ff := suppose subcount l₁ l₂ = ff, inr (suppose h : (∀ a, list.count a l₁ ≤ list.count a l₂), obtain w hw, from ex_of_subcount_eq_ff `subcount l₁ l₂ = ff`, absurd (h w) hw) end rfl) end subbag end bag
dffdff5afe732e90006a4bf5224b8f872bf519e6
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/limits/shapes/kernels.lean
ab792de8e1c70d7cdaa2d3775614864d08d40d6b
[ "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
26,100
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.zero /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.) The basic definitions are * `kernel : (X ⟶ Y) → C` * `kernel.ι : kernel f ⟶ X` * `kernel.condition : kernel.ι f ≫ f = 0` and * `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, we prove * `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.eq_zero_of_epi_kernel`: if `kernel.ι f` is an epimorphism, then `f = 0` * `kernel.of_mono`: the kernel of a monomorphism is the zero object * `kernel.lift_mono`: the lift of a monomorphism `k : W ⟶ X` such that `k ≫ f = 0` is still a monomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism * `kernel.ι_of_zero`: `kernel.ι (0 : X ⟶ Y)` is an isomorphism and the corresponding dual statements. ## Future work * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u u' open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables [has_zero_morphisms C] /-- A morphism `f` has a kernel if the functor `parallel_pair f 0` has a limit. -/ abbreviation has_kernel {X Y : C} (f : X ⟶ Y) : Prop := has_limit (parallel_pair f 0) /-- A morphism `f` has a cokernel if the functor `parallel_pair f 0` has a colimit. -/ abbreviation has_cokernel {X Y : C} (f : X ⟶ Y) : Prop := has_colimit (parallel_pair f 0) variables {X Y : C} (f : X ⟶ Y) section /-- A kernel fork is just a fork where the second morphism is a zero morphism. -/ abbreviation kernel_fork := fork f 0 variables {f} @[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 := by erw [fork.condition, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 := by rw [←fork.app_zero_left, kernel_fork.condition] /-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/ abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f := fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.ι_of_ι {X Y P : C} (f : X ⟶ Y) (ι : P ⟶ X) (w : ι ≫ f = 0) : fork.ι (kernel_fork.of_ι ι w) = ι := rfl section local attribute [tidy] tactic.case_bash /-- Every kernel fork `s` is isomorphic (actually, equal) to `fork.of_ι (fork.ι s) _`. -/ def iso_of_ι (s : fork f 0) : s ≅ fork.of_ι (fork.ι s) (fork.condition s) := cones.ext (iso.refl _) $ by tidy /-- If `ι = ι'`, then `fork.of_ι ι _` and `fork.of_ι ι' _` are isomorphic. -/ def of_ι_congr {P : C} {ι ι' : P ⟶ X} {w : ι ≫ f = 0} (h : ι = ι') : kernel_fork.of_ι ι w ≅ kernel_fork.of_ι ι' (by rw [←h, w]) := cones.ext (iso.refl _) $ by tidy /-- If `F` is an equivalence, then applying `F` to a diagram indexing a (co)kernel of `f` yields the diagram indexing the (co)kernel of `F.map f`. -/ def comp_nat_iso {D : Type u'} [category.{v} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] : parallel_pair f 0 ⋙ F ≅ parallel_pair (F.map f) 0 := nat_iso.of_components (λ j, match j with | zero := iso.refl _ | one := iso.refl _ end) $ by tidy end /-- If `s` is a limit kernel fork and `k : W ⟶ X` satisfies ``k ≫ f = 0`, then there is some `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ kernel_fork.of_ι _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a kernel fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : kernel_fork f) (lift : Π (s : kernel_fork f), s.X ⟶ t.X) (fac : ∀ (s : kernel_fork f), lift s ≫ t.ι = s.ι) (uniq : ∀ (s : kernel_fork f) (m : s.X ⟶ t.X) (w : m ≫ t.ι = s.ι), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, by { cases j, { exact fac s, }, { simp, }, }, uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.zero), } /-- This is a more convenient formulation to show that a `kernel_fork` constructed using `kernel_fork.of_ι` is a limit cone. -/ def is_limit.of_ι {W : C} (g : W ⟶ X) (eq : g ≫ f = 0) (lift : Π {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), W' ⟶ W) (fac : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), lift g' eq' ≫ g = g') (uniq : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0) (m : W' ⟶ W) (w : m ≫ g = g'), m = lift g' eq') : is_limit (kernel_fork.of_ι g eq) := is_limit_aux _ (λ s, lift s.ι s.condition) (λ s, fac s.ι s.condition) (λ s, uniq s.ι s.condition) end section variables [has_kernel f] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0 @[simp] lemma equalizer_as_kernel : equalizer.ι f 0 = kernel.ι f := rfl @[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 := kernel_fork.condition _ /-- Given any morphism `k : W ⟶ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ι f` via `kernel.lift : W ⟶ kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f := limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h) @[simp, reassoc] lemma kernel.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ι f = k := limit.lift_π _ _ @[simp] lemma kernel.lift_zero {W : C} {h} : kernel.lift f (0 : W ⟶ X) h = 0 := by { ext, simp, } instance kernel.lift_mono {W : C} (k : W ⟶ X) (h : k ≫ f = 0) [mono k] : mono (kernel.lift f k h) := ⟨λ Z g g' w, begin replace w := w =≫ kernel.ι f, simp only [category.assoc, kernel.lift_ι] at w, exact (cancel_mono k).1 w, end⟩ /-- Any morphism `k : W ⟶ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟶ kernel f` such that `l ≫ kernel.ι f = k`. -/ def kernel.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ kernel f // l ≫ kernel.ι f = k} := ⟨kernel.lift f k h, kernel.lift_ι _ _ _⟩ /-- Every kernel of the zero morphism is an isomorphism -/ instance kernel.ι_zero_is_iso : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ lemma eq_zero_of_epi_kernel [epi (kernel.ι f)] : f = 0 := (cancel_epi (kernel.ι f)).1 (by simp) /-- The kernel of a zero morphism is isomorphic to the source. -/ def kernel_zero_iso_source : kernel (0 : X ⟶ Y) ≅ X := equalizer.iso_source_of_self 0 @[simp] lemma kernel_zero_iso_source_hom : kernel_zero_iso_source.hom = kernel.ι (0 : X ⟶ Y) := rfl @[simp] lemma kernel_zero_iso_source_inv : kernel_zero_iso_source.inv = kernel.lift (0 : X ⟶ Y) (𝟙 X) (by simp) := by { ext, simp [kernel_zero_iso_source], } /-- If two morphisms are known to be equal, then their kernels are isomorphic. -/ def kernel_iso_of_eq {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) : kernel f ≅ kernel g := has_limit.iso_of_nat_iso (by simp[h]) @[simp] lemma kernel_iso_of_eq_refl {h : f = f} : kernel_iso_of_eq h = iso.refl (kernel f) := by { ext, simp [kernel_iso_of_eq], } @[simp] lemma kernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_kernel f] [has_kernel g] [has_kernel h] (w₁ : f = g) (w₂ : g = h) : kernel_iso_of_eq w₁ ≪≫ kernel_iso_of_eq w₂ = kernel_iso_of_eq (w₁.trans w₂) := by { unfreezingI { induction w₁, induction w₂, }, ext, simp [kernel_iso_of_eq], } variables {f} lemma kernel_not_epi_of_nonzero (w : f ≠ 0) : ¬epi (kernel.ι f) := λ I, by exactI w (eq_zero_of_epi_kernel f) lemma kernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (kernel.ι f)) → false := λ I, kernel_not_epi_of_nonzero w $ by { resetI, apply_instance } -- TODO the remainder of this section has obvious generalizations to `has_equalizer f g`. instance has_kernel_comp_mono {X Y Z : C} (f : X ⟶ Y) [has_kernel f] (g : Y ⟶ Z) [mono g] : has_kernel (f ≫ g) := { exists_limit := ⟨{ cone := kernel_fork.of_ι (kernel.ι f) (by simp), is_limit := is_limit_aux _ (λ s, kernel.lift _ s.ι ((cancel_mono g).mp (by simp))) (by tidy) (by tidy) }⟩ } /-- When `g` is a monomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `f`. -/ @[simps] def kernel_comp_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel f] [mono g] : kernel (f ≫ g) ≅ kernel f := { hom := kernel.lift _ (kernel.ι _) (by { rw [←cancel_mono g], simp, }), inv := kernel.lift _ (kernel.ι _) (by simp), } -- TODO provide an instance `[has_kernel (f ≫ g)]` from `[is_iso f] [has_kernel g]` /-- When `f` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `g`. -/ @[simps] def kernel_is_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : kernel (f ≫ g) ≅ kernel g := { hom := kernel.lift _ (kernel.ι _ ≫ f) (by simp), inv := kernel.lift _ (kernel.ι _ ≫ inv f) (by simp), } end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_cone : cone (parallel_pair f 0) := { X := 0, π := { app := λ j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) := fork.is_limit.mk _ (λ s, 0) (λ s, by { erw zero_comp, convert (zero_of_comp_mono f _).symm, exact kernel_fork.condition _ }) (λ _ _ _, zero_of_to_zero _) /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_kernel f] [mono f] : kernel f ≅ 0 := functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ι_of_mono [has_kernel f] [mono f] : kernel.ι f = 0 := zero_of_source_iso_zero _ (kernel.of_mono f) end has_zero_object section transport /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then any kernel of `f` is a kernel of `l`.-/ def is_kernel.of_comp_iso {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) {s : kernel_fork f} (hs : is_limit s) : is_limit (kernel_fork.of_ι (fork.ι s) $ show fork.ι s ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := fork.is_limit.mk _ (λ s, hs.lift $ kernel_fork.of_ι (fork.ι s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply fork.is_limit.hom_ext hs, simpa using h walking_parallel_pair.zero }) /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then the kernel of `f` is a kernel of `l`.-/ def kernel.of_comp_iso [has_kernel f] {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) : is_limit (kernel_fork.of_ι (kernel.ι f) $ show kernel.ι f ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := is_kernel.of_comp_iso f l i h $ limit.is_limit _ /-- If `s` is any limit kernel cone over `f` and if `i` is an isomorphism such that `i.hom ≫ s.ι = l`, then `l` is a kernel of `f`. -/ def is_kernel.iso_kernel {Z : C} (l : Z ⟶ X) {s : kernel_fork f} (hs : is_limit s) (i : Z ≅ s.X) (h : i.hom ≫ fork.ι s = l) : is_limit (kernel_fork.of_ι l $ show l ≫ f = 0, by simp [←h]) := is_limit.of_iso_limit hs $ cones.ext i.symm $ λ j, by { cases j, { exact (iso.eq_inv_comp i).2 h }, { simp } } /-- If `i` is an isomorphism such that `i.hom ≫ kernel.ι f = l`, then `l` is a kernel of `f`. -/ def kernel.iso_kernel [has_kernel f] {Z : C} (l : Z ⟶ X) (i : Z ≅ kernel f) (h : i.hom ≫ kernel.ι f = l) : is_limit (kernel_fork.of_ι l $ by simp [←h]) := is_kernel.iso_kernel f l (limit.is_limit _) i h end transport section variables (X Y) /-- The kernel morphism of a zero morphism is an isomorphism -/ lemma kernel.ι_of_zero : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ end section /-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/ abbreviation cokernel_cofork := cofork f 0 variables {f} @[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.π s = 0 := by rw [cofork.condition, zero_comp] @[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ι.app zero = 0 := by rw [←cofork.left_app_one, cokernel_cofork.condition] /-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/ abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f := cofork.of_π π $ by rw [w, zero_comp] @[simp] lemma cokernel_cofork.π_of_π {X Y P : C} (f : X ⟶ Y) (π : Y ⟶ P) (w : f ≫ π = 0) : cofork.π (cokernel_cofork.of_π π w) = π := rfl /-- Every cokernel cofork `s` is isomorphic (actually, equal) to `cofork.of_π (cofork.π s) _`. -/ def iso_of_π (s : cofork f 0) : s ≅ cofork.of_π (cofork.π s) (cofork.condition s) := cocones.ext (iso.refl _) $ λ j, by cases j; tidy /-- If `π = π'`, then `cokernel_cofork.of_π π _` and `cokernel_cofork.of_π π' _` are isomorphic. -/ def of_π_congr {P : C} {π π' : Y ⟶ P} {w : f ≫ π = 0} (h : π = π') : cokernel_cofork.of_π π w ≅ cokernel_cofork.of_π π' (by rw [←h, w]) := cocones.ext (iso.refl _) $ λ j, by cases j; tidy /-- If `s` is a colimit cokernel cofork, then every `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cokernel_cofork.is_colimit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cokernel_cofork.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a cokernel cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : cokernel_cofork f) (desc : Π (s : cokernel_cofork f), t.X ⟶ s.X) (fac : ∀ (s : cokernel_cofork f), t.π ≫ desc s = s.π) (uniq : ∀ (s : cokernel_cofork f) (m : t.X ⟶ s.X) (w : t.π ≫ m = s.π), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, by { cases j, { simp, }, { exact fac s, }, }, uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.one), } /-- This is a more convenient formulation to show that a `cokernel_cofork` constructed using `cokernel_cofork.of_π` is a limit cone. -/ def is_colimit.of_π {Z : C} (g : Y ⟶ Z) (eq : f ≫ g = 0) (desc : Π {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), Z ⟶ Z') (fac : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), g ≫ desc g' eq' = g') (uniq : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0) (m : Z ⟶ Z') (w : g ≫ m = g'), m = desc g' eq') : is_colimit (cokernel_cofork.of_π g eq) := is_colimit_aux _ (λ s, desc s.π s.condition) (λ s, fac s.π s.condition) (λ s, uniq s.π s.condition) end section variables [has_cokernel f] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0 @[simp] lemma coequalizer_as_cokernel : coequalizer.π f 0 = cokernel.π f := rfl @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 := cokernel_cofork.condition _ /-- Given any morphism `k : Y ⟶ W` such that `f ≫ k = 0`, `k` factors through `cokernel.π f` via `cokernel.desc : cokernel f ⟶ W`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W := colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h) @[simp, reassoc] lemma cokernel.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel.π f ≫ cokernel.desc f k h = k := colimit.ι_desc _ _ @[simp] lemma cokernel.desc_zero {W : C} {h} : cokernel.desc f (0 : Y ⟶ W) h = 0 := by { ext, simp, } instance cokernel.desc_epi {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) [epi k] : epi (cokernel.desc f k h) := ⟨λ Z g g' w, begin replace w := cokernel.π f ≫= w, simp only [cokernel.π_desc_assoc] at w, exact (cancel_epi k).1 w, end⟩ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟶ W` such that `cokernel.π f ≫ l = k`. -/ def cokernel.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : cokernel f ⟶ W // cokernel.π f ≫ l = k} := ⟨cokernel.desc f k h, cokernel.π_desc _ _ _⟩ /-- The cokernel of the zero morphism is an isomorphism -/ instance cokernel.π_zero_is_iso : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ lemma eq_zero_of_mono_cokernel [mono (cokernel.π f)] : f = 0 := (cancel_mono (cokernel.π f)).1 (by simp) /-- The cokernel of a zero morphism is isomorphic to the target. -/ def cokernel_zero_iso_target : cokernel (0 : X ⟶ Y) ≅ Y := coequalizer.iso_target_of_self 0 @[simp] lemma cokernel_zero_iso_target_hom : cokernel_zero_iso_target.hom = cokernel.desc (0 : X ⟶ Y) (𝟙 Y) (by simp) := by { ext, simp [cokernel_zero_iso_target], } @[simp] lemma cokernel_zero_iso_target_inv : cokernel_zero_iso_target.inv = cokernel.π (0 : X ⟶ Y) := rfl /-- If two morphisms are known to be equal, then their cokernels are isomorphic. -/ def cokernel_iso_of_eq {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) : cokernel f ≅ cokernel g := has_colimit.iso_of_nat_iso (by simp[h]) @[simp] lemma cokernel_iso_of_eq_refl {h : f = f} : cokernel_iso_of_eq h = iso.refl (cokernel f) := by { ext, simp [cokernel_iso_of_eq], } @[simp] lemma cokernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_cokernel f] [has_cokernel g] [has_cokernel h] (w₁ : f = g) (w₂ : g = h) : cokernel_iso_of_eq w₁ ≪≫ cokernel_iso_of_eq w₂ = cokernel_iso_of_eq (w₁.trans w₂) := by { unfreezingI { induction w₁, induction w₂, }, ext, simp [cokernel_iso_of_eq], } variables {f} lemma cokernel_not_mono_of_nonzero (w : f ≠ 0) : ¬mono (cokernel.π f) := λ I, by exactI w (eq_zero_of_mono_cokernel f) lemma cokernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (cokernel.π f)) → false := λ I, cokernel_not_mono_of_nonzero w $ by { resetI, apply_instance } -- TODO the remainder of this section has obvious generalizations to `has_coequalizer f g`. -- TODO provide an instance `[has_cokernel (f ≫ g)]` from `[has_cokernel f] [is_iso g]` /-- When `g` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `f`. -/ @[simps] def cokernel_comp_is_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel (f ≫ g) ≅ cokernel f := { hom := cokernel.desc _ (inv g ≫ cokernel.π f) (by simp), inv := cokernel.desc _ (g ≫ cokernel.π (f ≫ g)) (by rw [←category.assoc, cokernel.condition]), } instance has_cokernel_epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [has_cokernel g] : has_cokernel (f ≫ g) := { exists_colimit := ⟨{ cocone := cokernel_cofork.of_π (cokernel.π g) (by simp), is_colimit := is_colimit_aux _ (λ s, cokernel.desc _ s.π ((cancel_epi f).mp (by { rw ← category.assoc, simp }))) (by tidy) (by tidy) }⟩ } /-- When `f` is an epimorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `g`. -/ @[simps] def cokernel_epi_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi f] [has_cokernel g] : cokernel (f ≫ g) ≅ cokernel g := { hom := cokernel.desc _ (cokernel.π g) (by simp), inv := cokernel.desc _ (cokernel.π (f ≫ g)) (by { rw [←cancel_epi f, ←category.assoc], simp, }), } end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cocone : cocone (parallel_pair f 0) := { X := 0, ι := { app := λ j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by { erw zero_comp, convert (zero_of_epi_comp f _).symm, exact cokernel_cofork.condition _ }) (λ _ _ _, zero_of_from_zero _) /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_cokernel f] [epi f] : cokernel f ≅ 0 := functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism of an epimorphism is a zero morphism -/ lemma cokernel.π_of_epi [has_cokernel f] [epi f] : cokernel.π f = 0 := zero_of_target_iso_zero _ (cokernel.of_epi f) end has_zero_object section has_image /-- The cokernel of the image inclusion of a morphism `f` is isomorphic to the cokernel of `f`. (This result requires that the factorisation through the image is an epimorphism. This holds in any category with equalizers.) -/ @[simps] def cokernel_image_ι {X Y : C} (f : X ⟶ Y) [has_image f] [has_cokernel (image.ι f)] [has_cokernel f] [epi (factor_thru_image f)] : cokernel (image.ι f) ≅ cokernel f := { hom := cokernel.desc _ (cokernel.π f) begin have w := cokernel.condition f, conv at w { to_lhs, congr, rw ←image.fac f, }, rw [←has_zero_morphisms.comp_zero (limits.factor_thru_image f), category.assoc, cancel_epi] at w, exact w, end, inv := cokernel.desc _ (cokernel.π _) begin conv { to_lhs, congr, rw ←image.fac f, }, rw [category.assoc, cokernel.condition, has_zero_morphisms.comp_zero], end, } end has_image section variables (X Y) /-- The cokernel of a zero morphism is an isomorphism -/ lemma cokernel.π_of_zero : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ instance kernel.of_cokernel_of_epi [has_cokernel f] [has_kernel (cokernel.π f)] [epi f] : is_iso (kernel.ι (cokernel.π f)) := equalizer.ι_of_eq $ cokernel.π_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ instance cokernel.of_kernel_of_mono [has_kernel f] [has_cokernel (kernel.ι f)] [mono f] : is_iso (cokernel.π (kernel.ι f)) := coequalizer.π_of_eq $ kernel.ι_of_mono f end has_zero_object section transport /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then any cokernel of `f` is a cokernel of `l`. -/ def is_cokernel.of_iso_comp {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) {s : cokernel_cofork f} (hs : is_colimit s) : is_colimit (cokernel_cofork.of_π (cofork.π s) $ show l ≫ cofork.π s = 0, by simp [i.eq_inv_comp.2 h]) := cofork.is_colimit.mk _ (λ s, hs.desc $ cokernel_cofork.of_π (cofork.π s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply cofork.is_colimit.hom_ext hs, simpa using h walking_parallel_pair.one }) /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then the cokernel of `f` is a cokernel of `l`. -/ def cokernel.of_iso_comp [has_cokernel f] {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) : is_colimit (cokernel_cofork.of_π (cokernel.π f) $ show l ≫ cokernel.π f = 0, by simp [i.eq_inv_comp.2 h]) := is_cokernel.of_iso_comp f l i h $ colimit.is_colimit _ /-- If `s` is any colimit cokernel cocone over `f` and `i` is an isomorphism such that `s.π ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def is_cokernel.cokernel_iso {Z : C} (l : Y ⟶ Z) {s : cokernel_cofork f} (hs : is_colimit s) (i : s.X ≅ Z) (h : cofork.π s ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ show f ≫ l = 0, by simp [←h]) := is_colimit.of_iso_colimit hs $ cocones.ext i $ λ j, by { cases j, { simp }, { exact h } } /-- If `i` is an isomorphism such that `cokernel.π f ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def cokernel.cokernel_iso [has_cokernel f] {Z : C} (l : Y ⟶ Z) (i : cokernel f ≅ Z) (h : cokernel.π f ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ by simp [←h]) := is_cokernel.cokernel_iso f l (colimit.is_colimit _) i h end transport end category_theory.limits namespace category_theory.limits variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] /-- `has_kernels` represents the existence of kernels for every morphism. -/ class has_kernels : Prop := (has_limit : Π {X Y : C} (f : X ⟶ Y), has_kernel f . tactic.apply_instance) /-- `has_cokernels` represents the existence of cokernels for every morphism. -/ class has_cokernels : Prop := (has_colimit : Π {X Y : C} (f : X ⟶ Y), has_cokernel f . tactic.apply_instance) attribute [instance, priority 100] has_kernels.has_limit has_cokernels.has_colimit @[priority 100] instance has_kernels_of_has_equalizers [has_equalizers C] : has_kernels C := {} @[priority 100] instance has_cokernels_of_has_coequalizers [has_coequalizers C] : has_cokernels C := {} end category_theory.limits
7a1ccf1aa10685fcebf52a14e80ce5b4c44d99a5
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/zorn.lean
e6e6791cad3e81bfe0a46c2a11df41c8540898e3
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
12,873
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 Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import data.set.lattice noncomputable theory universes u open set classical open_locale classical namespace zorn section chain parameters {α : Type u} (r : α → α → Prop) local infix ` ≺ `:50 := r /-- A chain is a subset `c` satisfying `x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/ def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) parameters {r} theorem chain.total_of_refl [is_refl α r] {c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) : x ≺ y ∨ y ≺ x := if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e theorem chain.mono {c c'} : c' ⊆ c → chain c → chain c' := pairwise_on.mono theorem chain.directed_on [is_refl α r] {c} (H : chain c) : directed_on (≺) c := assume x hx y hy, match H.total_of_refl hx hy with | or.inl h := ⟨y, hy, h, refl _⟩ | or.inr h := ⟨x, hx, refl _, h⟩ end theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) /-- `super_chain c₁ c₂` means that `c₂ is a chain that strictly includes `c₁`. -/ def super_chain (c₁ c₂ : set α) : Prop := chain c₂ ∧ c₁ ⊂ c₂ /-- A chain `c` is a maximal chain if there does not exists a chain strictly including `c`. -/ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') /-- Given a set `c`, if there exists a chain `c'` strictly including `c`, then `succ_chain c` is one of these chains. Otherwise it is `c`. -/ def succ_chain (c : set α) : set α := if h : ∃c', chain c ∧ super_chain c c' then some h else c theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂, cases hc₂.neg_resolve_left hc₁ with c' hc', exact succ_spec ⟨c', hc₁, hc'⟩ end theorem succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] /-- Set of sets reachable from `∅` using `succ_chain` and `⋃₀`. -/ inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) theorem chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case succ : c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case union : s hs ih { refine (or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case succ : c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case union : s hs ih { apply or.imp_left (assume h', subset.antisymm h' h), apply classical.by_contradiction, simp [not_or_distrib, sUnion_subset_iff, not_forall], intros c₃ hc₃ h₁ h₂, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₁ $ h' ▸ subset.refl _) }, { exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₁ $ subset.trans succ_increasing h) } } end theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case succ : c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case union : s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ theorem chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case succ : c hc h { exact chain_succ h }, case union : s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end /-- `max_chain` is the union of all sets in the chain closure. -/ def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ chain_closure), have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, H⟩ := this, ⟨h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := ssubset_iff_subset_ne.1 H in have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ theorem exists_maximal_of_chains_bounded (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀c:set α, chain (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @exists_maximal_of_chains_bounded α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α) (ih : ∀ c ⊆ s, chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) : ∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m := let ⟨⟨m, hms, hxm⟩, h⟩ := @zorn_partial_order {m // m ∈ s ∧ x ≤ m} _ (λ c hc, c.eq_empty_or_nonempty.elim (assume hce, hce.symm ▸ ⟨⟨x, hxs, le_refl _⟩, λ _, false.elim⟩) (assume ⟨m, hmc⟩, let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (image_subset_iff.2 $ λ z hzc, z.2.1) (by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq; exact hc p hpc q hqc (mt (by rintro rfl; refl) hpq)) m.1 (mem_image_of_mem _ hmc) in ⟨⟨ub, hubs, le_trans m.2.2 $ hub m.1 $ mem_image_of_mem _ hmc⟩, λ a hac, hub a.1 ⟨a, hac, rfl⟩⟩)) in ⟨m, hms, hxm, λ z hzs hmz, congr_arg subtype.val $ h ⟨z, hzs, le_trans hxm hmz⟩ hmz⟩ theorem zorn_subset {α : Type u} (S : set (set α)) (h : ∀c ⊆ S, chain (⊆) c → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) : ∃ m ∈ S, ∀a ∈ S, m ⊆ a → a = m := begin letI : partial_order S := partial_order.lift subtype.val (λ _ _, subtype.ext_val), have : ∀c:set S, @chain S (≤) c → ∃ub, ∀a∈c, a ≤ ub, { intros c hc, rcases h (subtype.val '' c) (image_subset_iff.2 _) _ with ⟨s, sS, hs⟩, { exact ⟨⟨s, sS⟩, λ ⟨x, hx⟩ H, hs _ (mem_image_of_mem _ H)⟩ }, { rintro ⟨x, hx⟩ _, exact hx }, { rintro _ ⟨x, cx, rfl⟩ _ ⟨y, cy, rfl⟩ xy, exact hc x cx y cy (mt (congr_arg _) xy) } }, rcases zorn_partial_order this with ⟨⟨m, mS⟩, hm⟩, exact ⟨m, mS, λ a aS ha, congr_arg subtype.val (hm ⟨a, aS⟩ ha)⟩ end theorem zorn_subset₀ {α : Type u} (S : set (set α)) (H : ∀c ⊆ S, chain (⊆) c → c.nonempty → ∃ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) : ∃ m ∈ S, x ⊆ m ∧ ∀a ∈ S, m ⊆ a → a = m := begin let T := {s ∈ S | x ⊆ s}, rcases zorn_subset T _ with ⟨m, ⟨mS, mx⟩, hm⟩, { exact ⟨m, mS, mx, λ a ha ha', hm a ⟨ha, subset.trans mx ha'⟩ ha'⟩ }, { intros c cT hc, cases c.eq_empty_or_nonempty with c0 c0, { rw c0, exact ⟨x, ⟨hx, subset.refl _⟩, λ _, false.elim⟩ }, { rcases H _ (subset.trans cT (sep_subset _ _)) hc c0 with ⟨ub, us, h⟩, refine ⟨ub, ⟨us, _⟩, h⟩, rcases c0 with ⟨s, hs⟩, exact subset.trans (cT hs).2 (h _ hs) } } end theorem chain.total {α : Type u} [preorder α] {c : set α} (H : chain (≤) c) : ∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x := λ x y, H.total_of_refl theorem chain.image {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) (f : α → β) (h : ∀ x y, r x y → s (f x) (f y)) {c : set α} (hrc : chain r c) : chain s (f '' c) := λ x ⟨a, ha₁, ha₂⟩ y ⟨b, hb₁, hb₂⟩, ha₂ ▸ hb₂ ▸ λ hxy, (hrc a ha₁ b hb₁ (mt (congr_arg f) $ hxy)).elim (or.inl ∘ h _ _) (or.inr ∘ h _ _) end zorn theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f x) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))
8732474ad9664d86639e985fa48deb904d8e5036
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/triangulated/basic.lean
94740f2468fd01fa07369510b88645a0c1925e5d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,632
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import data.int.basic import category_theory.shift.basic /-! # Triangles > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definition of triangles in an additive category with an additive shift. It also defines morphisms between these triangles. TODO: generalise this to n-angles in n-angulated categories as in https://arxiv.org/abs/1006.4592 -/ noncomputable theory open category_theory open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.pretriangulated open category_theory.category /- We work in a category `C` equipped with a shift. -/ variables (C : Type u) [category.{v} C] [has_shift C ℤ] /-- A triangle in `C` is a sextuple `(X,Y,Z,f,g,h)` where `X,Y,Z` are objects of `C`, and `f : X ⟶ Y`, `g : Y ⟶ Z`, `h : Z ⟶ X⟦1⟧` are morphisms in `C`. See <https://stacks.math.columbia.edu/tag/0144>. -/ structure triangle := mk' :: (obj₁ : C) (obj₂ : C) (obj₃ : C) (mor₁ : obj₁ ⟶ obj₂) (mor₂ : obj₂ ⟶ obj₃) (mor₃ : obj₃ ⟶ obj₁⟦(1:ℤ)⟧) variable {C} /-- A triangle `(X,Y,Z,f,g,h)` in `C` is defined by the morphisms `f : X ⟶ Y`, `g : Y ⟶ Z` and `h : Z ⟶ X⟦1⟧`. -/ @[simps] def triangle.mk {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ X⟦(1:ℤ)⟧) : triangle C := { obj₁ := X, obj₂ := Y, obj₃ := Z, mor₁ := f, mor₂ := g, mor₃ := h } section variables [has_zero_object C] [has_zero_morphisms C] open_locale zero_object instance : inhabited (triangle C) := ⟨⟨0,0,0,0,0,0⟩⟩ /-- For each object in `C`, there is a triangle of the form `(X,X,0,𝟙 X,0,0)` -/ @[simps] def contractible_triangle (X : C) : triangle C := triangle.mk (𝟙 X) (0 : X ⟶ 0) 0 end /-- A morphism of triangles `(X,Y,Z,f,g,h) ⟶ (X',Y',Z',f',g',h')` in `C` is a triple of morphisms `a : X ⟶ X'`, `b : Y ⟶ Y'`, `c : Z ⟶ Z'` such that `a ≫ f' = f ≫ b`, `b ≫ g' = g ≫ c`, and `a⟦1⟧' ≫ h = h' ≫ c`. In other words, we have a commutative diagram: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧' V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` See <https://stacks.math.columbia.edu/tag/0144>. -/ @[ext] structure triangle_morphism (T₁ : triangle C) (T₂ : triangle C) := (hom₁ : T₁.obj₁ ⟶ T₂.obj₁) (hom₂ : T₁.obj₂ ⟶ T₂.obj₂) (hom₃ : T₁.obj₃ ⟶ T₂.obj₃) (comm₁' : T₁.mor₁ ≫ hom₂ = hom₁ ≫ T₂.mor₁ . obviously) (comm₂' : T₁.mor₂ ≫ hom₃ = hom₂ ≫ T₂.mor₂ . obviously) (comm₃' : T₁.mor₃ ≫ hom₁⟦1⟧' = hom₃ ≫ T₂.mor₃ . obviously) restate_axiom triangle_morphism.comm₁' restate_axiom triangle_morphism.comm₂' restate_axiom triangle_morphism.comm₃' attribute [simp, reassoc] triangle_morphism.comm₁ triangle_morphism.comm₂ triangle_morphism.comm₃ /-- The identity triangle morphism. -/ @[simps] def triangle_morphism_id (T : triangle C) : triangle_morphism T T := { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃ } instance (T : triangle C) : inhabited (triangle_morphism T T) := ⟨triangle_morphism_id T⟩ variables {T₁ T₂ T₃ : triangle C} /-- Composition of triangle morphisms gives a triangle morphism. -/ @[simps] def triangle_morphism.comp (f : triangle_morphism T₁ T₂) (g : triangle_morphism T₂ T₃) : triangle_morphism T₁ T₃ := { hom₁ := f.hom₁ ≫ g.hom₁, hom₂ := f.hom₂ ≫ g.hom₂, hom₃ := f.hom₃ ≫ g.hom₃ } /-- Triangles with triangle morphisms form a category. -/ @[simps] instance triangle_category : category (triangle C) := { hom := λ A B, triangle_morphism A B, id := λ A, triangle_morphism_id A, comp := λ A B C f g, f.comp g } /-- a constructor for morphisms of triangles -/ @[simps] def triangle.hom_mk (A B : triangle C) (hom₁ : A.obj₁ ⟶ B.obj₁) (hom₂ : A.obj₂ ⟶ B.obj₂) (hom₃ : A.obj₃ ⟶ B.obj₃) (comm₁ : A.mor₁ ≫ hom₂ = hom₁ ≫ B.mor₁) (comm₂ : A.mor₂ ≫ hom₃ = hom₂ ≫ B.mor₂) (comm₃ : A.mor₃ ≫ hom₁⟦1⟧' = hom₃ ≫ B.mor₃) : A ⟶ B := { hom₁ := hom₁, hom₂ := hom₂, hom₃ := hom₃, comm₁' := comm₁, comm₂' := comm₂, comm₃' := comm₃, } /-- a constructor for isomorphisms of triangles -/ @[simps] def triangle.iso_mk (A B : triangle C) (iso₁ : A.obj₁ ≅ B.obj₁) (iso₂ : A.obj₂ ≅ B.obj₂) (iso₃ : A.obj₃ ≅ B.obj₃) (comm₁ : A.mor₁ ≫ iso₂.hom = iso₁.hom ≫ B.mor₁) (comm₂ : A.mor₂ ≫ iso₃.hom = iso₂.hom ≫ B.mor₂) (comm₃ : A.mor₃ ≫ iso₁.hom⟦1⟧' = iso₃.hom ≫ B.mor₃) : A ≅ B := { hom := triangle.hom_mk _ _ iso₁.hom iso₂.hom iso₃.hom comm₁ comm₂ comm₃, inv := triangle.hom_mk _ _ iso₁.inv iso₂.inv iso₃.inv (by simp only [← cancel_mono iso₂.hom, assoc, iso.inv_hom_id, comp_id, comm₁, iso.inv_hom_id_assoc]) (by simp only [← cancel_mono iso₃.hom, assoc, iso.inv_hom_id, comp_id, comm₂, iso.inv_hom_id_assoc]) (by simp only [← cancel_mono (iso₁.hom⟦(1 : ℤ)⟧'), assoc, ← functor.map_comp, iso.inv_hom_id, category_theory.functor.map_id, comp_id, comm₃, iso.inv_hom_id_assoc]), } end category_theory.pretriangulated
d5d1ed4642affd1f25c33fd7cf6f9438df5701fd
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/base_case.lean
8b750d9e98676bb02332039796e8669757cdbe1e
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
8,188
lean
import .functor import .for_mathlib.coprod.free_group_subgroup import neat.initial import data.nat.digits /-! # The base case of the `group_thingy` tactic ## Main definitions The only definition used outside of this file is `base_case_solver`. `base_case_solver T r₁ r₂` solves the word problem for the relation `of' r₁ r₂`, returning a normalized word in `T` when possible, and `none` otherwise -/ variables {ι : Type} [decidable_eq ι] open multiplicative free_group P semidirect_product @[simp] lemma gpowers_hom_apply {G : Type*} [group G] (x : G) (y : C∞) : gpowers_hom G x y = x ^ y.to_add := rfl def base_case'_cons (r₁ : ι) (r₂ : C∞) (i : ι) (n : C∞) : P (free_group ι) → P (free_group ι) | ⟨w, ⟨[], _⟩⟩ := if i = r₁ ∧ to_add r₂ ∣ to_add n then ⟨of' (1 : free_group ι) (of_add (to_add n / to_add r₂)) * w, 1⟩ else ⟨mul_free (of' i n) w, ⟨[⟨i, n⟩], sorry⟩⟩ | ⟨w, ⟨(j::l), h⟩⟩ := if i = r₁ then let x := to_add n + to_add j.2 in if j.1 = r₁ ∧ to_add r₂ ∣ x then ⟨mul_free (of' i n) w * of' (1 : free_group ι) (of_add (x / (to_add r₂))), ⟨l, sorry⟩⟩ else if (to_add r₂ : ℤ) ∣ to_add n then ⟨mul_free (of' i n) w * of' (1 : free_group ι) (of_add (to_add n / to_add r₂)), ⟨(j :: l), h⟩⟩ else ⟨mul_free (of' i n) w, of' i n * ⟨j :: l, h⟩⟩ else ⟨mul_free (of' i n) w, of' i n * ⟨j :: l, h⟩⟩ def base_case' (r₁ : ι) (r₂ : C∞) : free_group ι → P (free_group ι) | ⟨[], h⟩ := ⟨1, ⟨[], h⟩⟩ | ⟨(i::l), h⟩ := base_case'_cons r₁ r₂ i.1 i.2 $ base_case' ⟨l, coprod.pre.reduced_of_reduced_cons h⟩ using_well_founded { rel_tac := λ _ _, `[exact ⟨λ _ _, true, sorry⟩], dec_tac := `[trivial] } def base_case'_solver (T : set ι) [decidable_pred T] (r₁ : ι) (r₂ : C∞) : solver (of' r₁ r₂) T := λ w, let p := base_case' r₁ r₂ w in if p.right ∈ closure_var T then some p else none /-- `base_case_core` takes a word `l₁` in the free_group as a `list (Σ i : ι, C∞)` and a normalized word with proof `p` as a `P (free_group ι)`. It returns a normalized version `reverse l₁ * p`, reduced modulo `of' r₁ r₂` -/ @[inline] def base_case_core (r₁ : ι) (r₂ : C∞) : list (Σ i : ι, C∞) → P (free_group ι) → P (free_group ι) | [] p := p | (i::l₁) ⟨p, ⟨[], _⟩⟩ := if i.1 = r₁ then if to_add r₂ ∣ i.2 then let q := to_add i.2 / to_add r₂ in base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, 1⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, 1⟩) else base_case_core l₁ (inr (of' i.1 i.2) * inl p) | (i::l₁) ⟨p, ⟨j::l₂, _⟩⟩ := if i.1 = r₁ then if j.1 = r₁ then let x := to_add i.2 + to_add j.2 in if to_add r₂ ∣ x then base_case_core l₁ (inl (of' (1 : free_group ι) (of_add (to_add x / to_add r₂))) * inr (of' j.1 j.2⁻¹) * ⟨p, ⟨j::l₂, sorry⟩⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩) else if to_add r₂ ∣ i.2 then let q := to_add i.2 / to_add r₂ in base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, ⟨j::l₂, sorry⟩⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩) else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩) -- def normalize_single (r₁ : ι) (r₂ : C∞) (i : ι) (n : C∞) : P (free_group ι) := -- if i = r₁ ∧ to_add r₂ ∣ to_add n -- then ⟨of' 1 (of_add (to_add n / to_add r₂)), 1⟩ -- else ⟨1, of' i n⟩ -- def mul_left (r₁ : ι) (r₂ : C∞) (i : ι) (n : C∞) : -- P (free_group ι) → P (free_group ι) -- | ⟨p, ⟨[], _⟩⟩ := normalize_single r₁ r₂ i n * inl p -- | ⟨p, ⟨(j::l), _⟩⟩ := -- if i = j.1 -- then _ -- else _ -- -- @[inline] def base_case_core₂ (r₁ : ι) (r₂ : C∞) : list (Σ i : ι, C∞) → -- -- P (free_group ι) → P (free_group ι) -- -- | [] p := p -- -- | (i::l₁) ⟨p, ⟨[], _⟩⟩ := -- -- if i.1 = r₁ -- -- then if to_add r₂ ∣ i.2 -- -- then let q := to_add i.2 / to_add r₂ in -- -- base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, 1⟩) -- -- else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, 1⟩) -- -- else base_case_core l₁ (inr (of' i.1 i.2) * inl p) -- -- | (i::l₁) ⟨p, ⟨j::l₂, _⟩⟩ := -- -- if i.1 = r₁ -- -- then if j.1 = r₁ -- -- then -- -- let x := to_add i.2 + to_add j.2 in -- -- if to_add r₂ ∣ x -- -- then base_case_core l₁ (inl (of' (1 : free_group ι) (of_add (to_add x / to_add r₂))) * -- -- inr (of' j.1 j.2⁻¹) * ⟨p, ⟨j::l₂, sorry⟩⟩) -- -- else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩) -- -- else if to_add r₂ ∣ i.2 -- -- then let q := to_add i.2 / to_add r₂ in -- -- base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, ⟨j::l₂, sorry⟩⟩) -- -- else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩) -- -- else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩) /-- `base_case` reduces a word `w` in the `free_group ι` modulo `of' r₁ r₂` -/ @[inline] def base_case (r₁ : ι) (r₂ : C∞) (w : free_group ι) : P (free_group ι) := base_case_core r₁ r₂ w.to_list.reverse 1 /-- `base_case_solver T r₁ r₂` solves the word problem for the relation `of' r₁ r₂`, returning a normalized word in `T` when possible, and `none` otherwise -/ @[inline] def base_case_solver (T : set ι) [decidable_pred T] (r₁ : ι) (r₂ : C∞) : solver (of' r₁ r₂) T := λ w, let p := base_case r₁ r₂ w in if p.right ∈ closure_var T then some p else none #eval --(of' 0 (of_add 2)) P.lhs (of' 0 (of_add 2)) ((base_case 0 (of_add 2) ((of 1)⁻¹ *of 0^(-2 : ℤ) * (of 1)⁻¹ * of 0 ^2* (of 1)^(-2 : ℤ) * (of 0)^2))) #eval ((base_case 1 (of_add 1) ((of 0)⁻¹ * of 1 * of 0 ^ 2 * (of 1) * (of 0)⁻¹)).left) #eval ((base_case' 0 (of_add 2) (of 1 *of 0^2 * (of 1) * of 0 ^2* (of 1)^(-2 : ℤ) * (of 0)^2)).left) #eval ((base_case' 1 (of_add 1) ((of 0)⁻¹ * of 1 * of 0 ^ 2 * (of 1) * (of 0)⁻¹)).left) @[simp] lemma lhs_base_case'_cons (r₁ : ι) (r₂ : C∞) (hr₂ : to_add r₂ ≠ 0) (i : ι) (n : C∞) : Π (x : P (free_group ι)), lhs (of' r₁ r₂) (base_case'_cons r₁ r₂ i n x) = of' i n * lhs (of' r₁ r₂) x | ⟨w, ⟨[], _⟩⟩ := begin rw [base_case'_cons], split_ifs, { clear_aux_decl, rcases h with ⟨rfl, m, hm⟩, simp [lhs_inl, free_group.lift, gpowers_hom_apply], simp only [of'_eq_of_pow, ← gpow_add, ← gpow_neg, ← gpow_mul, int.div_eq_of_eq_mul_right hr₂ hm], rw hm }, { simp [inl_aut] } end | ⟨w, ⟨(j::l), _⟩⟩ := begin clear_aux_decl, rw [base_case'_cons], dsimp only, split_ifs, { subst r₁, rcases h_1 with ⟨rfl, m, hm⟩, rw [int.div_eq_of_eq_mul_right hr₂ hm], rw [← eq_sub_iff_add_eq] at hm, simp [lhs_inl, free_group.lift, mul_assoc, gpowers_hom_apply, inl_aut, hm], simp only [of'_eq_of_pow, ← gpow_add, ← gpow_neg, ← gpow_mul, ← mul_assoc, hm], simp }, { subst r₁, rcases h_2 with ⟨m, hm⟩, rw [int.div_eq_of_eq_mul_right hr₂ hm], simp [lhs_inl, free_group.lift, mul_assoc, gpowers_hom_apply, inl_aut, hm], simp only [of'_eq_of_pow, ← gpow_add, ← gpow_neg, ← gpow_mul, ← mul_assoc, hm], simp }, { simp [inl_aut_inv, inl_aut, mul_assoc] }, { simp [inl_aut_inv, inl_aut, mul_assoc] } end lemma lhs_base_case' (r₁ : ι) (r₂ : C∞) (hr₂ : to_add r₂ ≠ 0) : ∀ x : free_group ι, lhs (of' r₁ r₂) (base_case' r₁ r₂ x) = x | ⟨[], h⟩ := by rw [base_case']; simp | ⟨(i::l), _⟩ := by rw [base_case', lhs_base_case'_cons, lhs_base_case']; simp [inl_aut, inl_aut_inv, mul_assoc, hr₂] using_well_founded { rel_tac := λ _ _, `[exact ⟨λ _ _, true, sorry⟩], dec_tac := `[trivial] }
3c1da5d1b604122d02c5f6d84dc3ce8bb32f7b4a
7b02c598aa57070b4cf4fbfe2416d0479220187f
/heq.hlean
8c070f86e374ab66352c91c23fc1e1dfe8ce31f7
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,773
hlean
open eq is_trunc variables {I : Set} {P : I → Type} {i j k : I} {x x₁ x₂ : P i} {y y₁ y₂ : P j} {z : P k} {Q : Π⦃i⦄, P i → Type} structure heq (x : P i) (y : P j) : Type := (p : i = j) (q : x =[p] y) namespace eq notation x ` ==[`:50 P:0 `] `:0 y:50 := @heq _ P _ _ x y infix ` == `:50 := heq -- mostly for printing, since it will be almost always ambiguous what P is definition pathover_of_heq {p : i = j} (q : x ==[P] y) : x =[p] y := change_path !is_set.elim (heq.q q) definition eq_of_heq (p : x₁ ==[P] x₂) : x₁ = x₂ := eq_of_pathover_idp (pathover_of_heq p) definition heq.elim (p : x ==[P] y) (q : Q x) : Q y := begin induction p with p r, induction r, exact q end definition heq.refl [refl] (x : P i) : x ==[P] x := heq.mk idp idpo definition heq.rfl : x ==[P] x := heq.refl x definition heq.symm [symm] (p : x ==[P] y) : y ==[P] x := begin induction p with p q, constructor, exact q⁻¹ᵒ end definition heq_of_eq (p : x₁ = x₂) : x₁ ==[P] x₂ := heq.mk idp (pathover_idp_of_eq p) definition heq.trans [trans] (p : x ==[P] y) (p₂ : y ==[P] z) : x ==[P] z := begin induction p with p q, induction p₂ with p₂ q₂, constructor, exact q ⬝o q₂ end infix ` ⬝he `:72 := heq.trans postfix `⁻¹ʰᵉ`:(max+10) := heq.symm definition heq_of_heq_of_eq (p : x ==[P] y) (p₂ : y = y₂) : x ==[P] y₂ := p ⬝he heq_of_eq p₂ definition heq_of_eq_of_heq (p : x = x₂) (p₂ : x₂ ==[P] y) : x ==[P] y := heq_of_eq p ⬝he p₂ infix ` ⬝hep `:73 := concato_eq infix ` ⬝phe `:74 := eq_concato definition heq_tr (p : i = j) (x : P i) : x ==[P] transport P p x := heq.mk p !pathover_tr definition tr_heq (p : i = j) (x : P i) : transport P p x ==[P] x := (heq_tr p x)⁻¹ʰᵉ end eq
f26b6fe352fc4182b502b0ebe0ad675fe181b4ca
be5348f86d661459153802318209304b793c0e2a
/src/definitions.lean
ddfc0260ac932586d008c1e803473e70091a4049
[]
no_license
reglayass/lean-avl
6b758c7708bdb3316b1b97ada3e3f259b49da58a
c7bffa75d7548e5ff8cdd7d69f5a58499f883df1
refs/heads/master
1,692,297,536,477
1,633,946,864,000
1,633,946,864,000
340,881,572
4
0
null
null
null
null
UTF-8
Lean
false
false
7,337
lean
universe u /-- Inductive type for a binary tree A tree can either be empty, or have two children (which may also be empty) A tree node contains a key and a node value -/ inductive btree (α : Type u) | empty {} : btree | node (l : btree) (k : nat) (a : α) (r : btree) : btree namespace btree variables {α : Type u} /-- Definition for an empty tree -/ def empty_tree : btree α := btree.empty /-- Lookup a value in a tree A recursive function that traverses the left or right subtree depending on the key -/ def lookup (x : nat) : btree α → option α | empty := none | (node l k a r) := if x < k then lookup l else if x > k then lookup r else a /- Checking if a key exists in a tree. For this case, there is no need to know in which subtree it is in, it matters that it exists in the first place -/ def bound (x : nat) : btree α → bool | empty := ff | (node l k a r) := x = k ∨ bound l ∨ bound r /-- For all keys in some tree, the key needs to exist in the tree and have either a > or < relation -/ def forall_keys (p : nat → nat → Prop) (k : nat) (t : btree α) : Prop := ∀ k', bound k' t → p k k' /-- Binary search property For any node in a tree, all of the keys to the left must be smaller and all of the keys to the right must be larger, and both of the right and left children must be ordered themselves -/ def ordered : btree α → Prop | empty := tt | (node l k a r) := ordered l ∧ ordered r ∧ (forall_keys (>) k l) ∧ (forall_keys (<) k r) /-- Definition for the height of a tree The height is the longest path from the root node To some leaf node -/ def height : btree α → nat | empty := 0 | (node l k a r) := 1 + (max (height l) (height r)) /-- Definition for a tree to be balanced -/ def balanced : btree α → bool | empty := tt | (node l k a r) := if height l ≥ height r then height l ≤ height r + 1 else height r ≤ height l + 1 /-- Definition of a tree being left-heavy -/ def left_heavy : btree α → bool | empty := ff | (node empty k a r) := ff | (node (node ll lk la lr) k a r) := (height ll ≥ height lr) ∧ (height ll ≤ height lr + 1) ∧ (height lr ≥ height r) ∧ (height r + 1 = height ll) /-- Definition of a tree being right-heavy -/ def right_heavy : btree α → bool | empty := ff | (node l k a empty) := ff | (node l k a (node rl rk ra rr)) := (height rr ≥ height rl) ∧ (height rr ≤ height rl + 1) ∧ (height rl ≤ height l) ∧ (height l + 1 = height rr) /-- Simple right rotation -/ def simple_right : btree α → btree α | empty := empty | (node (node ll lk la lr) k a r) := node ll lk la (node lr k a r) | (node l k a r) := node l k a r /-- Simple left rotation -/ def simple_left : btree α → btree α | empty := empty | (node l k a (node rl rk ra rr)) := node (node l k a rl) rk ra rr | (node l k a r) := node l k a r /-- Definition of a right rotation If the left child tree is empty, no rotation is done If the left child subtree is taller than the right child subtree, a compound rotation is done by first a left rotation on the left tree then a right rotation on the whole tree. Otherwise, a simple right rotation is done. -/ def rotate_right : btree α → btree α | empty := empty | (node l k a r) := match l with | empty := (node l k a r) | (node ll lk la lr) := if height ll < height lr then simple_right (node (simple_left l) k a r) else simple_right (node l k a r) end /-- Definition of a left rotation A mirror definition to rotate_right -/ def rotate_left : btree α → btree α | empty := empty | (node l k a r) := match r with | empty := (node l k a r) | (node rl rk ra rr) := if height rr < height rl then simple_left (node l k a (simple_right r)) else simple_left (node l k a r) end /- Definition of a balanced insertion Traverses the tree by comparing keys similar to lookup. If the tree is left- or right-heavy after insertion, a rotation is done. -/ def insert (x : nat) (v : α) : btree α → btree α | empty := node empty x v empty | (node l k a r) := if x < k then let inl := insert l in let t := (node inl k a r) in if height inl > height r + 1 then rotate_right t else t else if x > k then let inr := insert r in let t := (node l k a inr) in if height inr > height l + 1 then rotate_left t else t else node l x v r /- "Shrinking" the right subtree of a three Returns x, which the key of the node in r with an empty right subtree Return a, which is the node value the node with key x Returns sh, the "shrunken" tree -/ def shrink : btree α → option (nat × α × btree α) | empty := none | (node l k v r) := some $ match shrink r with | none := (k, v, l) | some (x, a, sh) := if height l > height sh + 1 then (x, a, rotate_right (node l k v sh)) else (x, a, node l k v sh) end /-- Deleting the root of a tree If the left subtree is empty, the node is replaced with the right subtree Otherwise, the left subtree is shrunk until an empty subtree is found. -/ def del_root : btree α → btree α | empty := empty | (node l k v r) := match shrink l with | none := r | some (x, a, sh) := if height r > height sh + 1 then rotate_left (node sh x a r) else node sh x a r end /-- Deleting a key from a tree If the input key is the same as the current node key, the node is deleted Otherwise deletion is recursively called on either the right or left subtree, rotations completed as necessary. -/ def delete (x : nat) : btree α → btree α | empty := empty | (node l k a r) := if x = k then del_root (node l k a r) else if x < k then let dl := delete l in if height r > height dl + 1 then rotate_left (node dl k a r) else node dl k a r else let dr := delete r in if height l > height dr + 1 then rotate_right (node l k a dr) else (node l k a dr) /-- View inductive definition for shrink -/ inductive shrink_view {α} : btree α → option (nat × α × btree α) → Sort* | empty : shrink_view empty none | nonempty_empty : ∀ {l k v r}, shrink r = none → shrink_view (node l k v r) (some (k, v, l)) | nonempty_nonempty₁ : ∀ {l k v r x a sh out}, shrink r = some (x, a, sh) → height l > height sh + 1 → out = some (x, a, rotate_right (node l k v sh)) → shrink_view (node l k v r) out | nonempty_nonempty₂ : ∀ {l k v r x a sh}, shrink r = some (x, a, sh) → height l ≤ height sh + 1 → shrink_view (node l k v r) (some (x, a, node l k v sh)) /-- View inductive definition for del_node -/ inductive del_root_view {α} : btree α → btree α → Sort* | empty : del_root_view empty empty | nonempty_empty : ∀ {l k v r}, shrink l = none → del_root_view (node l k v r) r | nonempty_nonempty₁ : ∀ {l k v r x a sh}, shrink l = some (x, a, sh) → height r > height sh + 1 → del_root_view (node l k v r) (rotate_left (node sh x a r)) | nonempty_nonempty₂ : ∀ {l k v r x a sh}, shrink l = some (x, a, sh) → height r ≤ height sh + 1 → del_root_view (node l k v r) (node sh x a r) end btree
4dc06f20380fee85386f134de5e6abf8be2d029a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/list_monad1.lean
96d961dccbdeb6281839a7807edb0f72de160676
[ "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
168
lean
#eval (do { a : nat ← [1, 2, 3, 4], b : nat ← [4, 5, 6], (guard $ 2 * a ≥ b : list unit), (guard $ b < 6 : list unit), return (a, b) } : list (nat × nat) )
024710cacd0524383eccdf1253e7e5367688e547
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/PreDefinition/Basic.lean
07ff973442a21b71c0692f2af8ebaf3fcd09d423
[ "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
8,532
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.Compiler.NoncomputableAttr import Lean.Util.CollectLevelParams import Lean.Meta.AbstractNestedProofs import Lean.Elab.RecAppSyntax import Lean.Elab.DefView namespace Lean.Elab open Meta open Term /-- A (potentially recursive) definition. The elaborator converts it into Kernel definitions using many different strategies. -/ structure PreDefinition where ref : Syntax kind : DefKind levelParams : List Name modifiers : Modifiers declName : Name type : Expr value : Expr deriving Inhabited def instantiateMVarsAtPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← instantiateMVars preDef.type), value := (← instantiateMVars preDef.value) } def levelMVarToParamPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← levelMVarToParam preDef.type), value := (← levelMVarToParam preDef.value) } private def getLevelParamsPreDecls (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (List Name) := do let mut s : CollectLevelParams.State := {} for preDef in preDefs do s := collectLevelParams s preDef.type s := collectLevelParams s preDef.value match sortDeclLevelParams scopeLevelNames allUserLevelNames s.params with | Except.error msg => throwError msg | Except.ok levelParams => pure levelParams def fixLevelParams (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (Array PreDefinition) := do -- We used to use `shareCommon` here, but is was a bottleneck let levelParams ← getLevelParamsPreDecls preDefs scopeLevelNames allUserLevelNames let us := levelParams.map mkLevelParam let fixExpr (e : Expr) : Expr := e.replace fun c => match c with | Expr.const declName _ => if preDefs.any fun preDef => preDef.declName == declName then some $ Lean.mkConst declName us else none | _ => none return preDefs.map fun preDef => { preDef with type := fixExpr preDef.type, value := fixExpr preDef.value, levelParams := levelParams } def applyAttributesOf (preDefs : Array PreDefinition) (applicationTime : AttributeApplicationTime) : TermElabM Unit := do for preDef in preDefs do applyAttributesAt preDef.declName preDef.modifiers.attrs applicationTime def abstractNestedProofs (preDef : PreDefinition) : MetaM PreDefinition := if preDef.kind.isTheorem || preDef.kind.isExample then pure preDef else do let value ← Meta.abstractNestedProofs preDef.declName preDef.value pure { preDef with value := value } /-- Auxiliary method for (temporarily) adding pre definition as an axiom -/ def addAsAxiom (preDef : PreDefinition) : MetaM Unit := do withRef preDef.ref do addDecl <| Declaration.axiomDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, isUnsafe := preDef.modifiers.isUnsafe } private def shouldGenCodeFor (preDef : PreDefinition) : Bool := !preDef.kind.isTheorem && !preDef.modifiers.isNoncomputable private def compileDecl (decl : Declaration) : TermElabM Bool := do try Lean.compileDecl decl catch ex => if (← read).isNoncomputableSection then return false else throw ex return true private def addNonRecAux (preDef : PreDefinition) (compile : Bool) (all : List Name) (applyAttrAfterCompilation := true) : TermElabM Unit := withRef preDef.ref do let preDef ← abstractNestedProofs preDef let decl ← match preDef.kind with | DefKind.«theorem» => pure <| Declaration.thmDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value, all } | DefKind.«opaque» => pure <| Declaration.opaqueDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value isUnsafe := preDef.modifiers.isUnsafe, all } | DefKind.«abbrev» => pure <| Declaration.defnDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value hints := ReducibilityHints.«abbrev» safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe, all } | _ => -- definitions and examples pure <| Declaration.defnDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value hints := ReducibilityHints.regular (getMaxHeight (← getEnv) preDef.value + 1) safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe, all } addDecl decl withSaveInfoContext do -- save new env addTermInfo' preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true) applyAttributesOf #[preDef] AttributeApplicationTime.afterTypeChecking if preDef.modifiers.isNoncomputable then modifyEnv fun env => addNoncomputable env preDef.declName if compile && shouldGenCodeFor preDef then discard <| compileDecl decl if applyAttrAfterCompilation then applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation def addAndCompileNonRec (preDef : PreDefinition) (all : List Name := [preDef.declName]) : TermElabM Unit := do addNonRecAux preDef (compile := true) (all := all) def addNonRec (preDef : PreDefinition) (applyAttrAfterCompilation := true) (all : List Name := [preDef.declName]) : TermElabM Unit := do addNonRecAux preDef (compile := false) (applyAttrAfterCompilation := applyAttrAfterCompilation) (all := all) /-- Eliminate recursive application annotations containing syntax. These annotations are used by the well-founded recursion module to produce better error messages. -/ def eraseRecAppSyntaxExpr (e : Expr) : CoreM Expr := Core.transform e (post := fun e => pure <| TransformStep.done <| if (getRecAppSyntax? e).isSome then e.mdataExpr! else e) def eraseRecAppSyntax (preDef : PreDefinition) : CoreM PreDefinition := return { preDef with value := (← eraseRecAppSyntaxExpr preDef.value) } def addAndCompileUnsafe (preDefs : Array PreDefinition) (safety := DefinitionSafety.unsafe) : TermElabM Unit := do let preDefs ← preDefs.mapM fun d => eraseRecAppSyntax d withRef preDefs[0]!.ref do let all := preDefs.toList.map (·.declName) let decl := Declaration.mutualDefnDecl <| ← preDefs.toList.mapM fun preDef => return { name := preDef.declName levelParams := preDef.levelParams type := preDef.type value := preDef.value hints := ReducibilityHints.opaque safety, all } addDecl decl withSaveInfoContext do -- save new env for preDef in preDefs do addTermInfo' preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true) applyAttributesOf preDefs AttributeApplicationTime.afterTypeChecking discard <| compileDecl decl applyAttributesOf preDefs AttributeApplicationTime.afterCompilation return () def addAndCompilePartialRec (preDefs : Array PreDefinition) : TermElabM Unit := do if preDefs.all shouldGenCodeFor then withEnableInfoTree false do addAndCompileUnsafe (safety := DefinitionSafety.partial) <| preDefs.map fun preDef => { preDef with declName := Compiler.mkUnsafeRecName preDef.declName value := preDef.value.replace fun e => match e with | Expr.const declName us => if preDefs.any fun preDef => preDef.declName == declName then some <| mkConst (Compiler.mkUnsafeRecName declName) us else none | _ => none modifiers := {} } private def containsRecFn (recFnName : Name) (e : Expr) : Bool := (e.find? fun e => e.isConstOf recFnName).isSome def ensureNoRecFn (recFnName : Name) (e : Expr) : MetaM Expr := do if containsRecFn recFnName e then Meta.forEachExpr e fun e => do if e.isAppOf recFnName then throwError "unexpected occurrence of recursive application{indentExpr e}" pure e else pure e end Lean.Elab
151a71fa44090879e97d9ca82e27e2950e1e31b5
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/SemiRngWithUnit.lean
ba7a6c411f783afcebe667c147b97666150765f7
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
12,910
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section SemiRngWithUnit structure SemiRngWithUnit (A : Type) : Type := (times : (A → (A → A))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (one : A) (lunit_one : (∀ {x : A} , (times one x) = x)) (runit_one : (∀ {x : A} , (times x one) = x)) (plus : (A → (A → A))) (zero : A) (lunit_zero : (∀ {x : A} , (plus zero x) = x)) (runit_zero : (∀ {x : A} , (plus x zero) = x)) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) (commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x))) (leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z)))) (rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x)))) open SemiRngWithUnit structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (oneS : AS) (plusS : (AS → (AS → AS))) (zeroS : AS) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (oneP : (Prod A A)) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (zeroP : (Prod A A)) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (lunit_1P : (∀ {xP : (Prod A A)} , (timesP oneP xP) = xP)) (runit_1P : (∀ {xP : (Prod A A)} , (timesP xP oneP) = xP)) (lunit_0P : (∀ {xP : (Prod A A)} , (plusP zeroP xP) = xP)) (runit_0P : (∀ {xP : (Prod A A)} , (plusP xP zeroP) = xP)) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) (commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP))) (leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP)))) (rightDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP (plusP yP zP) xP) = (plusP (timesP yP xP) (timesP zP xP)))) structure Hom {A1 : Type} {A2 : Type} (Se1 : (SemiRngWithUnit A1)) (Se2 : (SemiRngWithUnit A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Se1) x1 x2)) = ((times Se2) (hom x1) (hom x2)))) (pres_one : (hom (one Se1)) = (one Se2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Se1) x1 x2)) = ((plus Se2) (hom x1) (hom x2)))) (pres_zero : (hom (zero Se1)) = (zero Se2)) structure RelInterp {A1 : Type} {A2 : Type} (Se1 : (SemiRngWithUnit A1)) (Se2 : (SemiRngWithUnit A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Se1) x1 x2) ((times Se2) y1 y2)))))) (interp_one : (interp (one Se1) (one Se2))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Se1) x1 x2) ((plus Se2) y1 y2)))))) (interp_zero : (interp (zero Se1) (zero Se2))) inductive SemiRngWithUnitTerm : Type | timesL : (SemiRngWithUnitTerm → (SemiRngWithUnitTerm → SemiRngWithUnitTerm)) | oneL : SemiRngWithUnitTerm | plusL : (SemiRngWithUnitTerm → (SemiRngWithUnitTerm → SemiRngWithUnitTerm)) | zeroL : SemiRngWithUnitTerm open SemiRngWithUnitTerm inductive ClSemiRngWithUnitTerm (A : Type) : Type | sing : (A → ClSemiRngWithUnitTerm) | timesCl : (ClSemiRngWithUnitTerm → (ClSemiRngWithUnitTerm → ClSemiRngWithUnitTerm)) | oneCl : ClSemiRngWithUnitTerm | plusCl : (ClSemiRngWithUnitTerm → (ClSemiRngWithUnitTerm → ClSemiRngWithUnitTerm)) | zeroCl : ClSemiRngWithUnitTerm open ClSemiRngWithUnitTerm inductive OpSemiRngWithUnitTerm (n : ℕ) : Type | v : ((fin n) → OpSemiRngWithUnitTerm) | timesOL : (OpSemiRngWithUnitTerm → (OpSemiRngWithUnitTerm → OpSemiRngWithUnitTerm)) | oneOL : OpSemiRngWithUnitTerm | plusOL : (OpSemiRngWithUnitTerm → (OpSemiRngWithUnitTerm → OpSemiRngWithUnitTerm)) | zeroOL : OpSemiRngWithUnitTerm open OpSemiRngWithUnitTerm inductive OpSemiRngWithUnitTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpSemiRngWithUnitTerm2) | sing2 : (A → OpSemiRngWithUnitTerm2) | timesOL2 : (OpSemiRngWithUnitTerm2 → (OpSemiRngWithUnitTerm2 → OpSemiRngWithUnitTerm2)) | oneOL2 : OpSemiRngWithUnitTerm2 | plusOL2 : (OpSemiRngWithUnitTerm2 → (OpSemiRngWithUnitTerm2 → OpSemiRngWithUnitTerm2)) | zeroOL2 : OpSemiRngWithUnitTerm2 open OpSemiRngWithUnitTerm2 def simplifyCl {A : Type} : ((ClSemiRngWithUnitTerm A) → (ClSemiRngWithUnitTerm A)) | (timesCl oneCl x) := x | (timesCl x oneCl) := x | (plusCl zeroCl x) := x | (plusCl x zeroCl) := x | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | oneCl := oneCl | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | zeroCl := zeroCl | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpSemiRngWithUnitTerm n) → (OpSemiRngWithUnitTerm n)) | (timesOL oneOL x) := x | (timesOL x oneOL) := x | (plusOL zeroOL x) := x | (plusOL x zeroOL) := x | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | oneOL := oneOL | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | zeroOL := zeroOL | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpSemiRngWithUnitTerm2 n A) → (OpSemiRngWithUnitTerm2 n A)) | (timesOL2 oneOL2 x) := x | (timesOL2 x oneOL2) := x | (plusOL2 zeroOL2 x) := x | (plusOL2 x zeroOL2) := x | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | oneOL2 := oneOL2 | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | zeroOL2 := zeroOL2 | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((SemiRngWithUnit A) → (SemiRngWithUnitTerm → A)) | Se (timesL x1 x2) := ((times Se) (evalB Se x1) (evalB Se x2)) | Se oneL := (one Se) | Se (plusL x1 x2) := ((plus Se) (evalB Se x1) (evalB Se x2)) | Se zeroL := (zero Se) def evalCl {A : Type} : ((SemiRngWithUnit A) → ((ClSemiRngWithUnitTerm A) → A)) | Se (sing x1) := x1 | Se (timesCl x1 x2) := ((times Se) (evalCl Se x1) (evalCl Se x2)) | Se oneCl := (one Se) | Se (plusCl x1 x2) := ((plus Se) (evalCl Se x1) (evalCl Se x2)) | Se zeroCl := (zero Se) def evalOpB {A : Type} {n : ℕ} : ((SemiRngWithUnit A) → ((vector A n) → ((OpSemiRngWithUnitTerm n) → A))) | Se vars (v x1) := (nth vars x1) | Se vars (timesOL x1 x2) := ((times Se) (evalOpB Se vars x1) (evalOpB Se vars x2)) | Se vars oneOL := (one Se) | Se vars (plusOL x1 x2) := ((plus Se) (evalOpB Se vars x1) (evalOpB Se vars x2)) | Se vars zeroOL := (zero Se) def evalOp {A : Type} {n : ℕ} : ((SemiRngWithUnit A) → ((vector A n) → ((OpSemiRngWithUnitTerm2 n A) → A))) | Se vars (v2 x1) := (nth vars x1) | Se vars (sing2 x1) := x1 | Se vars (timesOL2 x1 x2) := ((times Se) (evalOp Se vars x1) (evalOp Se vars x2)) | Se vars oneOL2 := (one Se) | Se vars (plusOL2 x1 x2) := ((plus Se) (evalOp Se vars x1) (evalOp Se vars x2)) | Se vars zeroOL2 := (zero Se) def inductionB {P : (SemiRngWithUnitTerm → Type)} : ((∀ (x1 x2 : SemiRngWithUnitTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((P oneL) → ((∀ (x1 x2 : SemiRngWithUnitTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P zeroL) → (∀ (x : SemiRngWithUnitTerm) , (P x)))))) | ptimesl p1l pplusl p0l (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl p1l pplusl p0l x1) (inductionB ptimesl p1l pplusl p0l x2)) | ptimesl p1l pplusl p0l oneL := p1l | ptimesl p1l pplusl p0l (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl p1l pplusl p0l x1) (inductionB ptimesl p1l pplusl p0l x2)) | ptimesl p1l pplusl p0l zeroL := p0l def inductionCl {A : Type} {P : ((ClSemiRngWithUnitTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClSemiRngWithUnitTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((P oneCl) → ((∀ (x1 x2 : (ClSemiRngWithUnitTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P zeroCl) → (∀ (x : (ClSemiRngWithUnitTerm A)) , (P x))))))) | psing ptimescl p1cl ppluscl p0cl (sing x1) := (psing x1) | psing ptimescl p1cl ppluscl p0cl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl p1cl ppluscl p0cl x1) (inductionCl psing ptimescl p1cl ppluscl p0cl x2)) | psing ptimescl p1cl ppluscl p0cl oneCl := p1cl | psing ptimescl p1cl ppluscl p0cl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl p1cl ppluscl p0cl x1) (inductionCl psing ptimescl p1cl ppluscl p0cl x2)) | psing ptimescl p1cl ppluscl p0cl zeroCl := p0cl def inductionOpB {n : ℕ} {P : ((OpSemiRngWithUnitTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpSemiRngWithUnitTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((P oneOL) → ((∀ (x1 x2 : (OpSemiRngWithUnitTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P zeroOL) → (∀ (x : (OpSemiRngWithUnitTerm n)) , (P x))))))) | pv ptimesol p1ol pplusol p0ol (v x1) := (pv x1) | pv ptimesol p1ol pplusol p0ol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol p1ol pplusol p0ol x1) (inductionOpB pv ptimesol p1ol pplusol p0ol x2)) | pv ptimesol p1ol pplusol p0ol oneOL := p1ol | pv ptimesol p1ol pplusol p0ol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol p1ol pplusol p0ol x1) (inductionOpB pv ptimesol p1ol pplusol p0ol x2)) | pv ptimesol p1ol pplusol p0ol zeroOL := p0ol def inductionOp {n : ℕ} {A : Type} {P : ((OpSemiRngWithUnitTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpSemiRngWithUnitTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((P oneOL2) → ((∀ (x1 x2 : (OpSemiRngWithUnitTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P zeroOL2) → (∀ (x : (OpSemiRngWithUnitTerm2 n A)) , (P x)))))))) | pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 x1) (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 x2)) | pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 oneOL2 := p1ol2 | pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 x1) (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 x2)) | pv2 psing2 ptimesol2 p1ol2 pplusol2 p0ol2 zeroOL2 := p0ol2 def stageB : (SemiRngWithUnitTerm → (Staged SemiRngWithUnitTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | oneL := (Now oneL) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | zeroL := (Now zeroL) def stageCl {A : Type} : ((ClSemiRngWithUnitTerm A) → (Staged (ClSemiRngWithUnitTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | oneCl := (Now oneCl) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | zeroCl := (Now zeroCl) def stageOpB {n : ℕ} : ((OpSemiRngWithUnitTerm n) → (Staged (OpSemiRngWithUnitTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | oneOL := (Now oneOL) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | zeroOL := (Now zeroOL) def stageOp {n : ℕ} {A : Type} : ((OpSemiRngWithUnitTerm2 n A) → (Staged (OpSemiRngWithUnitTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | oneOL2 := (Now oneOL2) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | zeroOL2 := (Now zeroOL2) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (oneT : (Repr A)) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (zeroT : (Repr A)) end SemiRngWithUnit
14c8ec63e4f55a9febf77f50bd87cb3098e72abc
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/test/ext.lean
fc7b0bbfb06959156160ab1816222bcb7b393d8f
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
178
lean
import tactic.interactive universes u₁ u₂ lemma Q : 1 = 1 := begin success_if_fail { ext }, refl end lemma P (X Y : ℕ × ℕ) : X = X := begin ext, refl, refl, end
835be32237034922032983ef3fe12efa1f6e8d55
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/category_theory/limits/shapes/pullbacks.lean
fbe364229ae56a9d253a821e0b30b6ff073826c3
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
26,502
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fintype.basic import category_theory.limits.limits import category_theory.limits.shapes.finite_limits import category_theory.sparse /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. Typeclasses `has_pullbacks` and `has_pushouts` assert the existence of (co)limits shaped as walking (co)spans. -/ open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback. -/ @[derive decidable_eq, derive inhabited] inductive walking_cospan : Type v | left | right | one /-- The type of objects for the diagram indexing a pushout. -/ @[derive decidable_eq, derive inhabited] inductive walking_span : Type v | zero | left | right instance fintype_walking_cospan : fintype walking_cospan := { elems := [walking_cospan.left, walking_cospan.right, walking_cospan.one].to_finset, complete := λ x, by { cases x; simp } } instance fintype_walking_span : fintype walking_span := { elems := [walking_span.zero, walking_span.left, walking_span.right].to_finset, complete := λ x, by { cases x; simp } } namespace walking_cospan /-- The arrows in a pullback diagram. -/ @[derive decidable_eq] inductive hom : walking_cospan → walking_cospan → Type v | inl : hom left one | inr : hom right one | id : Π X : walking_cospan.{v}, hom X X /-- Satisfying the inhabited linter -/ instance hom.inhabited : inhabited (hom left one) := { default := hom.inl } open hom instance fintype_walking_cospan_hom (j j' : walking_cospan) : fintype (hom j j') := { elems := walking_cospan.rec_on j (walking_cospan.rec_on j' [hom.id left].to_finset ∅ [inl].to_finset) (walking_cospan.rec_on j' ∅ [hom.id right].to_finset [inr].to_finset) (walking_cospan.rec_on j' ∅ ∅ [hom.id one].to_finset), complete := by tidy } /-- Composition of morphisms in the category indexing a pullback. -/ def hom.comp : Π (X Y Z : walking_cospan) (f : hom X Y) (g : hom Y Z), hom X Z | _ _ _ (id _) h := h | _ _ _ inl (id one) := inl | _ _ _ inr (id one) := inr . instance category_struct : category_struct walking_cospan := { hom := hom, id := hom.id, comp := hom.comp, } instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy -- We make this a @[simp] lemma later; if we do it now there's a mysterious -- failure in `cospan`, below. lemma hom_id (X : walking_cospan.{v}) : hom.id X = 𝟙 X := rfl /-- The walking_cospan is the index diagram for a pullback. -/ instance : small_category.{v} walking_cospan.{v} := sparse_category instance : fin_category.{v} walking_cospan.{v} := { fintype_hom := walking_cospan.fintype_walking_cospan_hom } end walking_cospan namespace walking_span /-- The arrows in a pushout diagram. -/ @[derive decidable_eq] inductive hom : walking_span → walking_span → Type v | fst : hom zero left | snd : hom zero right | id : Π X : walking_span.{v}, hom X X instance hom.inhabited : inhabited (hom zero left) := { default := hom.fst } open hom instance fintype_walking_span_hom (j j' : walking_span) : fintype (hom j j') := { elems := walking_span.rec_on j (walking_span.rec_on j' [hom.id zero].to_finset [fst].to_finset [snd].to_finset) (walking_span.rec_on j' ∅ [hom.id left].to_finset ∅) (walking_span.rec_on j' ∅ ∅ [hom.id right].to_finset), complete := by tidy } /-- Composition of morphisms in the category indexing a pushout. -/ def hom.comp : Π (X Y Z : walking_span) (f : hom X Y) (g : hom Y Z), hom X Z | _ _ _ (id _) h := h | _ _ _ fst (id left) := fst | _ _ _ snd (id right) := snd . instance category_struct : category_struct walking_span := { hom := hom, id := hom.id, comp := hom.comp } instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy -- We make this a @[simp] lemma later; if we do it now there's a mysterious -- failure in `span`, below. lemma hom_id (X : walking_span.{v}) : hom.id X = 𝟙 X := rfl /-- The walking_span is the index diagram for a pushout. -/ instance : small_category.{v} walking_span.{v} := sparse_category instance : fin_category.{v} walking_span.{v} := { fintype_hom := walking_span.fintype_walking_span_hom } end walking_span open walking_span walking_cospan walking_span.hom walking_cospan.hom variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C := { obj := λ x, match x with | left := X | right := Y | one := Z end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, inl := f | _, _, inr := g end } /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C := { obj := λ x, match x with | zero := X | left := Y | right := Z end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, fst := f | _, _, snd := g end } @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an equalizer is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- Every diagram indexing a coequalizer naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy variables {X Y Z : C} attribute [simp] walking_cospan.hom_id walking_span.hom_id /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app right /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, walking_cospan.cases_on j fst snd (fst ≫ f), naturality' := λ j j' f, by cases f; obviously } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app one = fst ≫ f := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := begin erw [t.w inl, ← t.w inr], refl end /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | left := h₀ | right := h₁ | one := calc k ≫ t.π.app one = k ≫ t.π.app left ≫ (cospan f g).map inl : by rw ←t.w ... = l ≫ t.π.app left ≫ (cospan f g).map inl : by rw [←category.assoc, h₀, category.assoc] ... = l ≫ t.π.app one : by rw t.w lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit.mk (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app left = s.π.app left) (fac_right : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app right = s.π.app right) (uniq : ∀ (s : cone (cospan f g)) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_cospan.cases_on j (fac_left s) (fac_right s) $ by rw [←t.w inl, ←s.w inl, ←fac_left s, category.assoc], uniq' := uniq } end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app right /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, walking_span.cases_on j (f ≫ inl) inl inr, naturality' := λ j j' f, by cases f; obviously } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app zero = f ≫ inl := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := begin erw [t.w fst, ← t.w snd], refl end /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | left := h₀ | right := h₁ | zero := calc t.ι.app zero ≫ k = ((span f g).map fst ≫ t.ι.app left) ≫ k : by rw ←t.w ... = ((span f g).map fst ≫ t.ι.app left) ≫ l : by rw [category.assoc, h₀, ←category.assoc] ... = t.ι.app zero ≫ l : by rw t.w lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit.mk (t : pushout_cocone f g) (desc : Π (s : cocone (span f g)), t.X ⟶ s.X) (fac_left : ∀ (s : cocone (span f g)), t.ι.app left ≫ desc s = s.ι.app left) (fac_right : ∀ (s : cocone (span f g)), t.ι.app right ≫ desc s = s.ι.app right) (uniq : ∀ (s : cocone (span f g)) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_span.cases_on j (by rw [←s.w fst, ←t.w fst, category.assoc, fac_left s]) (fac_left s) (fac_right s), uniq' := uniq } end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ def cone.of_pullback_cone {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, exact (t.w inl).symm, exact (t.w inr).symm end } }. @[simp] lemma cone.of_pullback_cone_π {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) (j) : (cone.of_pullback_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ def cocone.of_pushout_cocone {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, exact t.w fst, exact t.w snd end } }. @[simp] lemma cocone.of_pushout_cocone_ι {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) (j) : (cocone.of_pushout_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ def pullback_cone.of_cone {F : walking_cospan.{v} ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := { app := λ j, t.π.app j ≫ eq_to_hom (by tidy) } } @[simp] lemma pullback_cone.of_cone_π {F : walking_cospan.{v} ⥤ C} (t : cone F) (j) : (pullback_cone.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ def pushout_cocone.of_cocone {F : walking_span.{v} ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := { app := λ j, eq_to_hom (by tidy) ≫ t.ι.app j } } @[simp] lemma pushout_cocone.of_cocone_ι {F : walking_span.{v} ⥤ C} (t : cocone F) (j) : (pushout_cocone.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (span f g)] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ calc (u ≫ pullback.snd) ≫ g = u ≫ pullback.fst ≫ f : by rw [category.assoc, pullback.condition] ... = v ≫ pullback.fst ≫ f : by rw [←category.assoc, h, category.assoc] ... = (v ≫ pullback.snd) ≫ g : by rw [pullback.condition, ←category.assoc]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ calc (u ≫ pullback.fst) ≫ f = u ≫ pullback.snd ≫ g : by rw [category.assoc, pullback.condition] ... = v ≫ pullback.snd ≫ g : by rw [←category.assoc, h, category.assoc] ... = (v ≫ pullback.fst) ≫ f : by rw [←pullback.condition, ←category.assoc]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ calc g ≫ pushout.inr ≫ u = (f ≫ pushout.inl) ≫ u : by rw [←category.assoc, ←pushout.condition] ... = f ≫ pushout.inl ≫ v : by rw [category.assoc, h] ... = g ≫ pushout.inr ≫ v : by rw [←category.assoc, pushout.condition, category.assoc]⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ calc f ≫ pushout.inl ≫ u = (g ≫ pushout.inr) ≫ u : by rw [←category.assoc, pushout.condition] ... = g ≫ pushout.inr ≫ v : by rw [category.assoc, h] ... = f ≫ pushout.inl ≫ v : by rw [←category.assoc, ←pushout.condition, category.assoc]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ class has_pullbacks := (has_limits_of_shape : has_limits_of_shape.{v} walking_cospan C) /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ class has_pushouts := (has_colimits_of_shape : has_colimits_of_shape.{v} walking_span C) attribute [instance] has_pullbacks.has_limits_of_shape has_pushouts.has_colimits_of_shape /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ def has_pullbacks_of_has_finite_limits [has_finite_limits.{v} C] : has_pullbacks.{v} C := { has_limits_of_shape := infer_instance } /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ def has_pushouts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_pushouts.{v} C := { has_colimits_of_shape := infer_instance } /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ def has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } } end category_theory.limits
eb41ae5d304526f8b0809ad3616381cf75dfd89b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/BindersUtil.lean
dbf97fe1db72e075ab1f579a6dcc9b2c7da1a601
[ "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
2,250
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term namespace Lean.Elab.Term /-- Recall that ``` def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec ``` -/ def expandOptType (ref : Syntax) (optType : Syntax) : Syntax := if optType.isNone then mkHole ref else optType[0][1] open Lean.Parser.Term /-- Helper function for `expandEqnsIntoMatch` -/ def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat := let alt0 := matchAlts[0][0] let pats := alt0[1][0].getSepArgs pats.size /-- Expand a match alternative such as `| 0 | 1 => rhs` to an array containing `| 0 => rhs` and `| 1 => rhs`. -/ def expandMatchAlt (stx : TSyntax ``matchAlt) : MacroM (Array (TSyntax ``matchAlt)) := match stx with | `(matchAltExpr| | $[$patss,*]|* => $rhs) => if patss.size ≤ 1 then return #[stx] else patss.mapM fun pats => `(matchAltExpr| | $pats,* => $rhs) | _ => return #[stx] def shouldExpandMatchAlt : TSyntax ``matchAlt → Bool | `(matchAltExpr| | $[$patss,*]|* => $_) => patss.size > 1 | _ => false def expandMatchAlts? (stx : Syntax) : MacroM (Option Syntax) := do match stx with | `(match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*) => if alts.any shouldExpandMatchAlt then let alts ← alts.foldlM (init := #[]) fun alts alt => return alts ++ (← expandMatchAlt alt) `(match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*) else return none | _ => return none open TSyntax.Compat in def clearInMatchAlt (stx : TSyntax ``matchAlt) (vars : Array Ident) : TSyntax ``matchAlt := stx.1.modifyArg 3 fun rhs => Unhygienic.run do let mut rhs := rhs for v in vars do rhs ← `(clear% $v; $rhs) return rhs def clearInMatch (stx : Syntax) (vars : Array Ident) : MacroM Syntax := do if vars.isEmpty then return stx match stx with | `(match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*) => let alts := alts.map (clearInMatchAlt · vars) `(match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*) | _ => return stx end Lean.Elab.Term
77d64c7ee98f4d790e18482d88e11ebd17edd222
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/data/encodable.lean
89096aae6ce52b44e8ffec50b70bfbc6ae06479e
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,458
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 Type class for encodable types. Note that every encodable type is countable. -/ import data.fintype data.list data.list.sort data.sum data.nat.div data.countable data.equiv data.finset open option list nat function structure encodable [class] (A : Type) := (encode : A → nat) (decode : nat → option A) (encodek : ∀ a, decode (encode a) = some a) open encodable definition countable_of_encodable {A : Type} : encodable A → countable A := assume e : encodable A, have injective encode, from λ (a₁ a₂ : A) (h : encode a₁ = encode a₂), assert decode A (encode a₁) = decode A (encode a₂), by rewrite h, by rewrite [*encodek at this]; injection this; assumption, exists.intro encode this definition encodable_fintype [instance] {A : Type} [h₁ : fintype A] [h₂ : decidable_eq A] : encodable A := encodable.mk (λ a, find a (elements_of A)) (λ n, nth (elements_of A) n) (λ a, find_nth (fintype.complete a)) definition encodable_nat [instance] : encodable nat := encodable.mk (λ a, a) (λ n, some n) (λ a, rfl) definition encodable_option [instance] {A : Type} [h : encodable A] : encodable (option A) := encodable.mk (λ o, match o with | some a := succ (encode a) | none := 0 end) (λ n, if n = 0 then some none else some (decode A (pred n))) (λ o, begin cases o with a, begin esimp end, begin esimp, rewrite [if_neg !succ_ne_zero, encodable.encodek] end end) section sum variables {A B : Type} variables [h₁ : encodable A] [h₂ : encodable B] include h₁ h₂ definition encode_sum : sum A B → nat | (sum.inl a) := 2 * encode a | (sum.inr b) := 2 * encode b + 1 definition decode_sum (n : nat) : option (sum A B) := if n mod 2 = 0 then match decode A (n div 2) with | some a := some (sum.inl a) | none := none end else match decode B ((n - 1) div 2) with | some b := some (sum.inr b) | none := none end open decidable theorem decode_encode_sum : ∀ s : sum A B, decode_sum (encode_sum s) = some s | (sum.inl a) := assert aux : 2 > 0, from dec_trivial, begin esimp [encode_sum, decode_sum], rewrite [mul_mod_right, if_pos (eq.refl (0 : nat)), mul_div_cancel_left _ aux, encodable.encodek] end | (sum.inr b) := assert aux₁ : 2 > 0, from dec_trivial, assert aux₂ : 1 mod 2 = 1, by rewrite [nat.modulo_def], assert aux₃ : 1 ≠ 0, from dec_trivial, begin esimp [encode_sum, decode_sum], rewrite [add.comm, add_mul_mod_self_left, aux₂, if_neg aux₃, add_sub_cancel_left, mul_div_cancel_left _ aux₁, encodable.encodek] end definition encodable_sum [instance] : encodable (sum A B) := encodable.mk (λ s, encode_sum s) (λ n, decode_sum n) (λ s, decode_encode_sum s) end sum section prod variables {A B : Type} variables [h₁ : encodable A] [h₂ : encodable B] include h₁ h₂ definition encode_prod : A × B → nat | (a, b) := mkpair (encode a) (encode b) definition decode_prod (n : nat) : option (A × B) := match unpair n with | (n₁, n₂) := match decode A n₁ with | some a := match decode B n₂ with | some b := some (a, b) | none := none end | none := none end end theorem decode_encode_prod : ∀ p : A × B, decode_prod (encode_prod p) = some p | (a, b) := begin esimp [encode_prod, decode_prod, prod.cases_on], rewrite [unpair_mkpair], esimp, rewrite [*encodable.encodek] end definition encodable_product [instance] : encodable (A × B) := encodable.mk encode_prod decode_prod decode_encode_prod end prod section list variables {A : Type} variables [h : encodable A] include h definition encode_list_core : list A → nat | [] := 0 | (a::l) := mkpair (encode a) (encode_list_core l) theorem encode_list_core_cons (a : A) (l : list A) : encode_list_core (a::l) = mkpair (encode a) (encode_list_core l) := rfl definition encode_list (l : list A) : nat := mkpair (length l) (encode_list_core l) definition decode_list_core : nat → nat → option (list A) | 0 v := some [] | (succ n) v := match unpair v with | (v₁, v₂) := match decode A v₁ with | some a := match decode_list_core n v₂ with | some l := some (a::l) | none := none end | none := none end end theorem decode_list_core_succ (n v : nat) : decode_list_core (succ n) v = match unpair v with | (v₁, v₂) := match decode A v₁ with | some a := match decode_list_core n v₂ with | some l := some (a::l) | none := none end | none := none end end := rfl definition decode_list (n : nat) : option (list A) := match unpair n with | (l, v) := decode_list_core l v end theorem decode_encode_list_core : ∀ l : list A, decode_list_core (length l) (encode_list_core l) = some l | [] := rfl | (a::l) := begin rewrite [encode_list_core_cons, length_cons, add_one (length l), decode_list_core_succ], rewrite [unpair_mkpair], esimp [prod.cases_on], rewrite [decode_encode_list_core l], rewrite [encodable.encodek], end theorem decode_encode_list (l : list A) : decode_list (encode_list l) = some l := begin esimp [encode_list, decode_list], rewrite [unpair_mkpair], esimp [prod.cases_on], apply decode_encode_list_core end definition encodable_list [instance] : encodable (list A) := encodable.mk encode_list decode_list decode_encode_list end list section finset variable {A : Type} variable [encA : encodable A] include encA private definition enle (a b : A) : Prop := encode a ≤ encode b private lemma enle.refl (a : A) : enle a a := !le.refl private lemma enle.trans (a b c : A) : enle a b → enle b c → enle a c := assume h₁ h₂, le.trans h₁ h₂ private lemma enle.total (a b : A) : enle a b ∨ enle b a := le.total private lemma enle.antisymm (a b : A) : enle a b → enle b a → a = b := assume h₁ h₂, assert encode a = encode b, from le.antisymm h₁ h₂, assert decode A (encode a) = decode A (encode b), by rewrite this, assert some a = some b, by rewrite [*encodek at this]; exact this, option.no_confusion this (λ e, e) private definition decidable_enle [instance] (a b : A) : decidable (enle a b) := decidable_le (encode a) (encode b) variables [decA : decidable_eq A] include decA private definition ensort (l : list A) : list A := sort enle l open subtype perm private lemma sorted_eq_of_perm {l₁ l₂ : list A} (h : l₁ ~ l₂) : ensort l₁ = ensort l₂ := list.sort_eq_of_perm_core enle.total enle.trans enle.refl enle.antisymm h definition encode_finset (s : finset A) : nat := quot.lift_on s (λ l, encode (ensort (elt_of l))) (λ l₁ l₂ p, have elt_of l₁ ~ elt_of l₂, from p, assert ensort (elt_of l₁) = ensort (elt_of l₂), from sorted_eq_of_perm this, by rewrite this) definition decode_finset (n : nat) : option (finset A) := match decode (list A) n with | some l₁ := some (finset.to_finset l₁) | none := none end theorem decode_encode_finset (s : finset A) : decode_finset (encode_finset s) = some s := quot.induction_on s (λ l, begin unfold encode_finset, unfold decode_finset, rewrite encodek, esimp, congruence, apply quot.sound, cases l with l nd, show erase_dup (ensort l) ~ l, from have nodup (ensort l), from nodup_of_perm_of_nodup (perm.symm !sort_perm) nd, calc erase_dup (ensort l) = ensort l : erase_dup_eq_of_nodup this ... ~ l : sort_perm end) definition encodable_finset [instance] : encodable (finset A) := encodable.mk encode_finset decode_finset decode_encode_finset end finset section subtype open subtype decidable variable {A : Type} variable {P : A → Prop} variable [encA : encodable A] variable [decP : decidable_pred P] include encA definition encode_subtype : {a : A | P a} → nat | (tag v h) := encode v include decP definition decode_subtype (v : nat) : option {a : A | P a} := match decode A v with | some a := if h : P a then some (tag a h) else none | none := none end lemma decode_encode_subtype : ∀ s : {a : A | P a}, decode_subtype (encode_subtype s) = some s | (tag v h) := begin unfold [encode_subtype, decode_subtype], rewrite encodek, esimp, rewrite [dif_pos h] end definition encodable_subtype [instance] : encodable {a : A | P a} := encodable.mk encode_subtype decode_subtype decode_encode_subtype end subtype definition encodable_of_left_injection {A B : Type} [h₁ : encodable A] (f : B → A) (finv : A → option B) (linv : ∀ b, finv (f b) = some b) : encodable B := encodable.mk (λ b, encode (f b)) (λ n, match decode A n with | some a := finv a | none := none end) (λ b, begin esimp, rewrite [encodable.encodek], esimp [option.cases_on], rewrite [linv] end) section open equiv definition encodable_of_equiv {A B : Type} [h : encodable A] : A ≃ B → encodable B | (mk f g l r) := encodable_of_left_injection g (λ a, some (f a)) (λ b, by rewrite r; reflexivity) end /- Choice function for encodable types and decidable predicates. We provide the following API choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A := choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ section find_a parameters {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] include c include d private definition pn (n : nat) : Prop := match decode A n with | some a := p a | none := false end private definition decidable_pn : decidable_pred pn := λ n, match decode A n with | some a := λ e : decode A n = some a, match d a with | decidable.inl t := begin unfold pn, rewrite e, esimp [option.cases_on], exact (decidable.inl t) end | decidable.inr f := begin unfold pn, rewrite e, esimp [option.cases_on], exact (decidable.inr f) end end | none := λ e : decode A n = none, begin unfold pn, rewrite e, esimp [option.cases_on], exact decidable_false end end (eq.refl (decode A n)) private definition ex_pn_of_ex : (∃ x, p x) → (∃ x, pn x) := assume ex, obtain (w : A) (pw : p w), from ex, exists.intro (encode w) begin unfold pn, rewrite [encodek], esimp, exact pw end private lemma decode_ne_none_of_pn {n : nat} : pn n → decode A n ≠ none := assume pnn e, begin rewrite [▸ (match decode A n with | some a := p a | none := false end) at pnn], rewrite [e at pnn], esimp [option.cases_on] at pnn, exact (false.elim pnn) end open subtype private definition of_nat (n : nat) : pn n → { a : A | p a } := match decode A n with | some a := λ (e : decode A n = some a), begin unfold pn, rewrite e, esimp [option.cases_on], intro pa, exact (tag a pa) end | none := λ (e : decode A n = none) h, absurd e (decode_ne_none_of_pn h) end (eq.refl (decode A n)) private definition find_a : (∃ x, p x) → {a : A | p a} := suppose ∃ x, p x, have ∃ x, pn x, from ex_pn_of_ex this, let r := @nat.find _ decidable_pn this in have pn r, from @nat.find_spec pn decidable_pn this, of_nat r this end find_a namespace encodable open subtype definition choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A := assume ex, elt_of (find_a ex) theorem choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := has_property (find_a ex) theorem axiom_of_choice {A : Type} {B : A → Type} {R : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (R x y)] : (∀x, ∃y, R x y) → ∃f, ∀x, R x (f x) := assume H, have ∀x, R x (choose (H x)), from take x, choose_spec (H x), exists.intro _ this theorem skolem {A : Type} {B : A → Type} {P : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (P x y)] : (∀x, ∃y, P x y) ↔ ∃f, (∀x, P x (f x)) := iff.intro (suppose (∀ x, ∃y, P x y), axiom_of_choice this) (suppose (∃ f, (∀x, P x (f x))), take x, obtain (fw : ∀x, B x) (Hw : ∀x, P x (fw x)), from this, exists.intro (fw x) (Hw x)) end encodable namespace quot section open setoid encodable parameter {A : Type} parameter {s : setoid A} parameter [decR : ∀ a b : A, decidable (a ≈ b)] parameter [encA : encodable A] include decR include encA -- Choose equivalence class representative definition rep (q : quot s) : A := choose (exists_rep q) theorem rep_spec (q : quot s) : ⟦rep q⟧ = q := choose_spec (exists_rep q) definition encode_quot (q : quot s) : nat := encode (rep q) definition decode_quot (n : nat) : option (quot s) := match decode A n with | some a := some ⟦ a ⟧ | none := none end lemma decode_encode_quot (q : quot s) : decode_quot (encode_quot q) = some q := quot.induction_on q (λ l, begin unfold [encode_quot, decode_quot], rewrite encodek, esimp, rewrite rep_spec end) definition encodable_quot : encodable (quot s) := encodable.mk encode_quot decode_quot decode_encode_quot end end quot attribute quot.encodable_quot [instance]
f09945155af608f258412a498c432639a410f15d
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/category_theory/functor.lean
245f1146f9e4d9b1fab05f447c96ae05fcb3f7ef
[ "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
3,403
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison Defines a functor between categories. (As it is a 'bundled' object rather than the `is_functorial` typeclass parametrised by the underlying function on objects, the name is capitalised.) Introduces notations `C ⥤ D` for the type of all functors from `C` to `D`. (I would like a better arrow here, unfortunately ⇒ (`\functor`) is taken by core.) -/ import tactic.reassoc_axiom import tactic.monotonicity namespace category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`. The axiom `map_id` expresses preservation of identities, and `map_comp` expresses functoriality. See https://stacks.math.columbia.edu/tag/001B. -/ structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] : Type (max v₁ v₂ u₁ u₂) := (obj [] : C → D) (map : Π {X Y : C}, (X ⟶ Y) → ((obj X) ⟶ (obj Y))) (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) -- A functor is basically a function, so give ⥤ a similar precedence to → (25). -- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`. infixr ` ⥤ `:26 := functor -- type as \func -- restate_axiom functor.map_id' attribute [simp] functor.map_id restate_axiom functor.map_comp' attribute [reassoc, simp] functor.map_comp namespace functor section variables (C : Type u₁) [category.{v₁} C] /-- `𝟭 C` is the identity functor on a category `C`. -/ protected def id : C ⥤ C := { obj := λ X, X, map := λ _ _ f, f } notation `𝟭` := functor.id -- Type this as `\sb1` instance : inhabited (C ⥤ C) := ⟨functor.id C⟩ variable {C} @[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl end section variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G.obj (F.obj X), map := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_obj (F : C ⥤ D) (G : D ⥤ E) (X : C) : (F ⋙ G).obj X = G.obj (F.obj X) := rfl @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) {X Y : C} (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl -- These are not simp lemmas because rewriting along equalities between functors -- is not necessarily a good idea. -- Natural isomorphisms are also provided in `whiskering.lean`. protected lemma comp_id (F : C ⥤ D) : F ⋙ (𝟭 D) = F := by cases F; refl protected lemma id_comp (F : C ⥤ D) : (𝟭 C) ⋙ F = F := by cases F; refl end @[mono] lemma monotone {α β : Type*} [preorder α] [preorder β] (F : α ⥤ β) : monotone F.obj := λ a b h, le_of_hom (F.map (hom_of_le h)) end functor end category_theory
4c4e504a4d0c979709670dcef08d54fadd7b3e04
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/support.lean
708e55ebc648f96a4fc5e2c2a4035153309d28cb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
11,126
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Patrick Massot -/ import topology.separation /-! # The topological support of a function In this file we define the topological support of a function `f`, `tsupport f`, as the closure of the support of `f`. Furthermore, we say that `f` has compact support if the topological support of `f` is compact. ## Main definitions * `function.mul_tsupport` & `function.tsupport` * `function.has_compact_mul_support` & `function.has_compact_support` ## Implementation Notes * We write all lemmas for multiplicative functions, and use `@[to_additive]` to get the more common additive versions. * We do not put the definitions in the `function` namespace, following many other topological definitions that are in the root namespace (compare `embedding` vs `function.embedding`). -/ open function set filter open_locale topological_space variables {X α α' β γ δ M E R : Type*} section one variables [has_one α] variables [topological_space X] /-- The topological support of a function is the closure of its support, i.e. the closure of the set of all elements where the function is not equal to 1. -/ @[to_additive /-" The topological support of a function is the closure of its support. i.e. the closure of the set of all elements where the function is nonzero. "-/] def mul_tsupport (f : X → α) : set X := closure (mul_support f) @[to_additive] lemma subset_mul_tsupport (f : X → α) : mul_support f ⊆ mul_tsupport f := subset_closure @[to_additive] lemma is_closed_mul_tsupport (f : X → α) : is_closed (mul_tsupport f) := is_closed_closure @[to_additive] lemma mul_tsupport_eq_empty_iff {f : X → α} : mul_tsupport f = ∅ ↔ f = 1 := by rw [mul_tsupport, closure_empty_iff, mul_support_eq_empty_iff] @[to_additive] lemma image_eq_zero_of_nmem_mul_tsupport {f : X → α} {x : X} (hx : x ∉ mul_tsupport f) : f x = 1 := mul_support_subset_iff'.mp (subset_mul_tsupport f) x hx @[to_additive] lemma range_subset_insert_image_mul_tsupport (f : X → α) : range f ⊆ insert 1 (f '' mul_tsupport f) := (range_subset_insert_image_mul_support f).trans $ insert_subset_insert $ image_subset _ subset_closure @[to_additive] lemma range_eq_image_mul_tsupport_or (f : X → α) : range f = f '' mul_tsupport f ∨ range f = insert 1 (f '' mul_tsupport f) := (wcovby_insert _ _).eq_or_eq (image_subset_range _ _) (range_subset_insert_image_mul_tsupport f) end one section variables [topological_space α] [topological_space α'] variables [has_one β] [has_one γ] [has_one δ] variables {g : β → γ} {f : α → β} {f₂ : α → γ} {m : β → γ → δ} {x : α} @[to_additive] lemma not_mem_closure_mul_support_iff_eventually_eq : x ∉ mul_tsupport f ↔ f =ᶠ[𝓝 x] 1 := by simp_rw [mul_tsupport, mem_closure_iff_nhds, not_forall, not_nonempty_iff_eq_empty, ← disjoint_iff_inter_eq_empty, disjoint_mul_support_iff, eventually_eq_iff_exists_mem] /-- A function `f` *has compact multiplicative support* or is *compactly supported* if the closure of the multiplicative support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `1` outside a compact set. -/ @[to_additive /-" A function `f` *has compact support* or is *compactly supported* if the closure of the support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `0` outside a compact set. "-/] def has_compact_mul_support (f : α → β) : Prop := is_compact (mul_tsupport f) @[to_additive] lemma has_compact_mul_support_def : has_compact_mul_support f ↔ is_compact (closure (mul_support f)) := by refl @[to_additive] lemma exists_compact_iff_has_compact_mul_support [t2_space α] : (∃ K : set α, is_compact K ∧ ∀ x ∉ K, f x = 1) ↔ has_compact_mul_support f := by simp_rw [← nmem_mul_support, ← mem_compl_iff, ← subset_def, compl_subset_compl, has_compact_mul_support_def, exists_compact_superset_iff] @[to_additive] lemma has_compact_mul_support.intro [t2_space α] {K : set α} (hK : is_compact K) (hfK : ∀ x ∉ K, f x = 1) : has_compact_mul_support f := exists_compact_iff_has_compact_mul_support.mp ⟨K, hK, hfK⟩ @[to_additive] lemma has_compact_mul_support.is_compact (hf : has_compact_mul_support f) : is_compact (mul_tsupport f) := hf @[to_additive] lemma has_compact_mul_support_iff_eventually_eq : has_compact_mul_support f ↔ f =ᶠ[coclosed_compact α] 1 := ⟨ λ h, mem_coclosed_compact.mpr ⟨mul_tsupport f, is_closed_mul_tsupport _, h, λ x, not_imp_comm.mpr $ λ hx, subset_mul_tsupport f hx⟩, λ h, let ⟨C, hC⟩ := mem_coclosed_compact'.mp h in compact_of_is_closed_subset hC.2.1 (is_closed_mul_tsupport _) (closure_minimal hC.2.2 hC.1)⟩ @[to_additive] lemma has_compact_mul_support.is_compact_range [topological_space β] (h : has_compact_mul_support f) (hf : continuous f) : is_compact (range f) := begin cases range_eq_image_mul_tsupport_or f with h2 h2; rw [h2], exacts [h.image hf, (h.image hf).insert 1] end @[to_additive] lemma has_compact_mul_support.mono' {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_tsupport f) : has_compact_mul_support f' := compact_of_is_closed_subset hf is_closed_closure $ closure_minimal hff' is_closed_closure @[to_additive] lemma has_compact_mul_support.mono {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_support f) : has_compact_mul_support f' := hf.mono' $ hff'.trans subset_closure @[to_additive] lemma has_compact_mul_support.comp_left (hf : has_compact_mul_support f) (hg : g 1 = 1) : has_compact_mul_support (g ∘ f) := hf.mono $ mul_support_comp_subset hg f @[to_additive] lemma has_compact_mul_support_comp_left (hg : ∀ {x}, g x = 1 ↔ x = 1) : has_compact_mul_support (g ∘ f) ↔ has_compact_mul_support f := by simp_rw [has_compact_mul_support_def, mul_support_comp_eq g @hg f] @[to_additive] lemma has_compact_mul_support.comp_closed_embedding (hf : has_compact_mul_support f) {g : α' → α} (hg : closed_embedding g) : has_compact_mul_support (f ∘ g) := begin rw [has_compact_mul_support_def, function.mul_support_comp_eq_preimage], refine compact_of_is_closed_subset (hg.is_compact_preimage hf) is_closed_closure _, rw [hg.to_embedding.closure_eq_preimage_closure_image], exact preimage_mono (closure_mono $ image_preimage_subset _ _) end @[to_additive] lemma has_compact_mul_support.comp₂_left (hf : has_compact_mul_support f) (hf₂ : has_compact_mul_support f₂) (hm : m 1 1 = 1) : has_compact_mul_support (λ x, m (f x) (f₂ x)) := begin rw [has_compact_mul_support_iff_eventually_eq] at hf hf₂ ⊢, filter_upwards [hf, hf₂] using λ x hx hx₂, by simp_rw [hx, hx₂, pi.one_apply, hm] end end section monoid variables [topological_space α] [monoid β] variables {f f' : α → β} {x : α} @[to_additive] lemma has_compact_mul_support.mul (hf : has_compact_mul_support f) (hf' : has_compact_mul_support f') : has_compact_mul_support (f * f') := by apply hf.comp₂_left hf' (mul_one 1) -- `by apply` speeds up elaboration end monoid section distrib_mul_action variables [topological_space α] [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_left (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero]) end end distrib_mul_action section smul_with_zero variables [topological_space α] [has_zero R] [has_zero M] [smul_with_zero R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_right (hf : has_compact_support f) : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, zero_smul]) end lemma has_compact_support.smul_left' (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero']) end end smul_with_zero section mul_zero_class variables [topological_space α] [mul_zero_class β] variables {f f' : α → β} {x : α} lemma has_compact_support.mul_right (hf : has_compact_support f) : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, zero_mul]) end lemma has_compact_support.mul_left (hf : has_compact_support f') : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, mul_zero]) end end mul_zero_class namespace locally_finite variables {ι : Type*} {U : ι → set X} [topological_space X] [has_one R] /-- If a family of functions `f` has locally-finite multiplicative support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are not equal to 1. -/ @[to_additive /-" If a family of functions `f` has locally-finite support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are non-zero. "-/] lemma exists_finset_nhd_mul_support_subset {f : ι → X → R} (hlf : locally_finite (λ i, mul_support (f i))) (hso : ∀ i, mul_tsupport (f i) ⊆ U i) (ho : ∀ i, is_open (U i)) (x : X) : ∃ (is : finset ι) {n : set X} (hn₁ : n ∈ 𝓝 x) (hn₂ : n ⊆ ⋂ i ∈ is, U i), ∀ (z ∈ n), mul_support (λ i, f i z) ⊆ is := begin obtain ⟨n, hn, hnf⟩ := hlf x, classical, let is := hnf.to_finset.filter (λ i, x ∈ U i), let js := hnf.to_finset.filter (λ j, x ∉ U j), refine ⟨is, n ∩ (⋂ j ∈ js, (mul_tsupport (f j))ᶜ) ∩ (⋂ i ∈ is, U i), inter_mem (inter_mem hn _) _, inter_subset_right _ _, λ z hz, _⟩, { exact (bInter_finset_mem js).mpr (λ j hj, is_closed.compl_mem_nhds (is_closed_mul_tsupport _) (set.not_mem_subset (hso j) (finset.mem_filter.mp hj).2)), }, { exact (bInter_finset_mem is).mpr (λ i hi, (ho i).mem_nhds (finset.mem_filter.mp hi).2) }, { have hzn : z ∈ n, { rw inter_assoc at hz, exact mem_of_mem_inter_left hz, }, replace hz := mem_of_mem_inter_right (mem_of_mem_inter_left hz), simp only [finset.mem_filter, finite.mem_to_finset, mem_set_of_eq, mem_Inter, and_imp] at hz, suffices : mul_support (λ i, f i z) ⊆ hnf.to_finset, { refine hnf.to_finset.subset_coe_filter_of_subset_forall _ this (λ i hi, _), specialize hz i ⟨z, ⟨hi, hzn⟩⟩, contrapose hz, simp [hz, subset_mul_tsupport (f i) hi], }, intros i hi, simp only [finite.coe_to_finset, mem_set_of_eq], exact ⟨z, ⟨hi, hzn⟩⟩, }, end end locally_finite
5bea4fa66718c4c29e82596246e23e9a4fb08759
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Modifiers.lean
741c69af097212bca4517ac6aaa83d2906cdd437
[ "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
2,433
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.Environment namespace Lean builtin_initialize protectedExt : TagDeclarationExtension ← mkTagDeclarationExtension @[export lean_add_protected] def addProtected (env : Environment) (n : Name) : Environment := protectedExt.tag env n @[export lean_is_protected] def isProtected (env : Environment) (n : Name) : Bool := protectedExt.isTagged env n /-! # Private name support. Suppose the user marks as declaration `n` as private. Then, we create the name: `_private.<module_name>.0 ++ n`. We say `_private.<module_name>.0` is the "private prefix" We assume that `n` is a valid user name and does not contain `Name.num` constructors. Thus, we can easily convert from private internal name to the user given name. -/ def privateHeader : Name := `_private def mkPrivateName (env : Environment) (n : Name) : Name := Name.mkNum (privateHeader ++ env.mainModule) 0 ++ n def isPrivateName : Name → Bool | n@(.str p _) => n == privateHeader || isPrivateName p | .num p _ => isPrivateName p | _ => false @[export lean_is_private_name] def isPrivateNameExport (n : Name) : Bool := isPrivateName n /-- Return `true` if `n` is of the form `_private.<module_name>.0` See comment above. -/ private def isPrivatePrefix (n : Name) : Bool := match n with | .num p 0 => go p | _ => false where go (n : Name) : Bool := n == privateHeader || match n with | .str p _ => go p | _ => false private def privateToUserNameAux (n : Name) : Name := match n with | .str p s => .str (privateToUserNameAux p) s | .num p i => if isPrivatePrefix n then .anonymous else .num (privateToUserNameAux p) i | _ => .anonymous @[export lean_private_to_user_name] def privateToUserName? (n : Name) : Option Name := if isPrivateName n then privateToUserNameAux n else none def isPrivateNameFromImportedModule (env : Environment) (n : Name) : Bool := match privateToUserName? n with | some userName => mkPrivateName env userName != n | _ => false private def privatePrefixAux : Name → Name | .str p _ => privatePrefixAux p | n => n @[export lean_private_prefix] def privatePrefix? (n : Name) : Option Name := if isPrivateName n then privatePrefixAux n else none end Lean
4aa70e7bf72b6fcaf291926f04297f3fa1986b63
f7c63613a4933f66368ef2802a50c417a46cddfc
/library/init/meta/attribute.lean
8de7f2439a7ffcdbfe0056796dcae5322c4eb425
[ "Apache-2.0" ]
permissive
avigad/lean
28cef71cd8c4eae53f342c87f81ca78d7cc75874
5410178203ab5ae854b5804586ace074ffd63aae
refs/heads/master
1,608,801,379,340
1,504,894,459,000
1,505,174,163,000
22,361,408
0
0
null
null
null
null
UTF-8
Lean
false
false
3,883
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.tactic init.meta.rb_map init.meta.has_reflect init.meta.lean.parser meta constant attribute.get_instances : name → tactic (list name) meta constant attribute.fingerprint : name → tactic nat meta structure user_attribute_cache_cfg (cache_ty : Type) := (mk_cache : list name → tactic cache_ty) (dependencies : list name) meta def user_attribute.dflt_cache_cfg : tactic unit := tactic.exact `(⟨λ _, pure (), []⟩ : user_attribute_cache_cfg unit) meta def user_attribute.dflt_parser : tactic unit := tactic.exact `(pure () : lean.parser unit) meta structure user_attribute (cache_ty : Type := unit) (param_ty : Type := unit) := (name : name) (descr : string) /- Optional handler that will be called after the attribute has been applied to a declaration. Failing the tactic will fail the entire `attribute/def/...` command, i.e. the attribute will not be applied after all. Declaring an `after_set` handler without a `before_unset` handler will make the attribute non-removable. -/ (after_set : option (Π (decl : _root_.name) (prio : nat) (persistent : bool), command) := none) /- Optional handler that will be called before the attribute is removed from a declaration. -/ (before_unset : option (Π (decl : _root_.name) (persistent : bool), command) := none) (cache_cfg : user_attribute_cache_cfg cache_ty . user_attribute.dflt_cache_cfg) [reflect_param : has_reflect param_ty] /- Parser that will be invoked after parsing the attribute's name. The parse result will be reflected and stored and can be retrieved with `user_attribute.get_param`. -/ (parser : lean.parser param_ty . user_attribute.dflt_parser) /- Registers a new user-defined attribute. The argument must be the name of a definition of type `user_attribute`. -/ meta def attribute.register (decl : name) : command := tactic.set_basic_attribute ``user_attribute decl tt meta constant user_attribute.get_cache {α β : Type} (attr : user_attribute α β) : tactic α meta def user_attribute.parse_reflect {α β : Type} (attr : user_attribute α β) : lean.parser expr := (λ a, attr.reflect_param a) <$> attr.parser meta constant user_attribute.get_param_untyped {α β : Type} (attr : user_attribute α β) (decl : name) : tactic expr meta constant user_attribute.set_param_untyped {α β : Type} [reflected β] (attr : user_attribute α β) (decl : name) (val : expr) (persistent : bool) (prio : option nat := none) : tactic unit meta def user_attribute.get_param {α β : Type} [reflected β] (attr : user_attribute α β) (n : name) : tactic β := attr.get_param_untyped n >>= tactic.eval_expr β meta def user_attribute.set_param {α β : Type} [reflected β] (attr : user_attribute α β) (n : name) (val : β) (persistent : bool) (prio : option nat := none) : tactic unit := attr.set_param_untyped n (attr.reflect_param val) persistent prio open tactic meta def register_attribute := attribute.register meta def get_attribute_cache_dyn {α : Type} [reflected α] (name : name) : tactic α := let attr : pexpr := expr.const name [] in do e ← to_expr ``(user_attribute.get_cache %%attr), t ← eval_expr (tactic α) e, t meta def mk_name_set_attr (attr_name : name) : command := do let t := `(user_attribute name_set), let v := `({name := attr_name, descr := "name_set attribute", cache_cfg := { mk_cache := λ ns, return (name_set.of_list ns), dependencies := []}} : user_attribute name_set), add_meta_definition attr_name [] t v, register_attribute attr_name meta def get_name_set_for_attr (name : name) : tactic name_set := get_attribute_cache_dyn name
e8976ad77f733072fc67410185d25cfd86a3502c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/homology/homotopy.lean
fcee23aeb5ea68722f1c2837a6f4593cfd0f459f
[ "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
18,287
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.homology.additive /-! # Chain homotopies We define chain homotopies, and prove that homotopic chain maps induce the same map on homology. -/ universes v u open_locale classical noncomputable theory open category_theory category_theory.limits homological_complex variables {ι : Type*} variables {V : Type u} [category.{v} V] [preadditive V] variables {c : complex_shape ι} {C D E : homological_complex V c} variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι) section /-- The composition of `C.d i i' ≫ f i' i` if there is some `i'` coming after `i`, and `0` otherwise. -/ def d_next (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X i ⟶ D.X i) := add_monoid_hom.mk' (λ f, match c.next i with | none := 0 | some ⟨i',w⟩ := C.d i i' ≫ f i' i end) begin intros f g, rcases c.next i with _|⟨i',w⟩, exact (zero_add _).symm, exact preadditive.comp_add _ _ _ _ _ _, end /-- `f i' i` if `i'` comes after `i`, and 0 if there's no such `i'`. Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next` to see that `d_next` factors through `C.d_from i`. -/ def from_next [has_zero_object V] (i : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X_next i ⟶ D.X i) := add_monoid_hom.mk' (λ f, match c.next i with | none := 0 | some ⟨i',w⟩ := (C.X_next_iso w).hom ≫ f i' i end) begin intros f g, rcases c.next i with _|⟨i',w⟩, exact (zero_add _).symm, exact preadditive.comp_add _ _ _ _ _ _, end lemma d_next_eq_d_from_from_next [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (i : ι) : d_next i f = C.d_from i ≫ from_next i f := begin dsimp [d_next, from_next], rcases c.next i with ⟨⟩|⟨⟨i', w⟩⟩; { dsimp [d_next, from_next], simp }, end lemma d_next_eq (f : Π i j, C.X i ⟶ D.X j) {i i' : ι} (w : c.rel i i') : d_next i f = C.d i i' ≫ f i' i := begin dsimp [d_next], rw c.next_eq_some w, refl, end @[simp] lemma d_next_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (i : ι) : d_next i (λ i j, f.f i ≫ g i j) = f.f i ≫ d_next i g := begin dsimp [d_next], rcases c.next i with _|⟨i',w⟩, { exact comp_zero.symm, }, { dsimp [d_next], simp, }, end @[simp] lemma d_next_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (i : ι) : d_next i (λ i j, f i j ≫ g.f j) = d_next i f ≫ g.f i := begin dsimp [d_next], rcases c.next i with _|⟨i',w⟩, { exact zero_comp.symm, }, { dsimp [d_next], simp, }, end /-- The composition of `f j j' ≫ D.d j' j` if there is some `j'` coming before `j`, and `0` otherwise. -/ def prev_d (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X j) := add_monoid_hom.mk' (λ f, match c.prev j with | none := 0 | some ⟨j',w⟩ := f j j' ≫ D.d j' j end) begin intros f g, rcases c.prev j with _|⟨j',w⟩, exact (zero_add _).symm, exact preadditive.add_comp _ _ _ _ _ _, end /-- `f j j'` if `j'` comes after `j`, and 0 if there's no such `j'`. Hopefully there won't be much need for this, except in `d_next_eq_d_from_from_next` to see that `d_next` factors through `C.d_from i`. -/ def to_prev [has_zero_object V] (j : ι) : (Π i j, C.X i ⟶ D.X j) →+ (C.X j ⟶ D.X_prev j) := add_monoid_hom.mk' (λ f, match c.prev j with | none := 0 | some ⟨j',w⟩ := f j j' ≫ (D.X_prev_iso w).inv end) begin intros f g, rcases c.prev j with _|⟨j',w⟩, exact (zero_add _).symm, exact preadditive.add_comp _ _ _ _ _ _, end lemma prev_d_eq_to_prev_d_to [has_zero_object V] (f : Π i j, C.X i ⟶ D.X j) (j : ι) : prev_d j f = to_prev j f ≫ D.d_to j := begin dsimp [prev_d, to_prev], rcases c.prev j with ⟨⟩|⟨⟨j', w⟩⟩; { dsimp [prev_d, to_prev], simp }, end lemma prev_d_eq (f : Π i j, C.X i ⟶ D.X j) {j j' : ι} (w : c.rel j' j) : prev_d j f = f j j' ≫ D.d j' j := begin dsimp [prev_d], rw c.prev_eq_some w, refl, end @[simp] lemma prev_d_comp_left (f : C ⟶ D) (g : Π i j, D.X i ⟶ E.X j) (j : ι) : prev_d j (λ i j, f.f i ≫ g i j) = f.f j ≫ prev_d j g := begin dsimp [prev_d], rcases c.prev j with _|⟨j',w⟩, { exact comp_zero.symm, }, { dsimp [prev_d, hom.prev], simp, }, end @[simp] lemma to_prev'_comp_right (f : Π i j, C.X i ⟶ D.X j) (g : D ⟶ E) (j : ι) : prev_d j (λ i j, f i j ≫ g.f j) = prev_d j f ≫ g.f j := begin dsimp [prev_d], rcases c.prev j with _|⟨j',w⟩, { exact zero_comp.symm, }, { dsimp [prev_d], simp, }, end lemma d_next_nat (C D : chain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) : d_next i f = C.d i (i-1) ≫ f (i-1) i := begin cases i, { dsimp [d_next], rcases (complex_shape.down ℕ).next 0 with _|⟨j,hj⟩; dsimp [d_next], { rw [C.shape, zero_comp], dsimp, dec_trivial }, { dsimp at hj, exact (nat.succ_ne_zero _ hj).elim } }, rw d_next_eq, dsimp, refl end lemma prev_d_nat (C D : cochain_complex V ℕ) (i : ℕ) (f : Π i j, C.X i ⟶ D.X j) : prev_d i f = f i (i-1) ≫ D.d (i-1) i := begin cases i, { dsimp [prev_d], rcases (complex_shape.up ℕ).prev 0 with _|⟨j,hj⟩; dsimp [prev_d], { rw [D.shape, comp_zero], dsimp, dec_trivial }, { dsimp at hj, exact (nat.succ_ne_zero _ hj).elim } }, rw prev_d_eq, dsimp, refl end /-- A homotopy `h` between chain maps `f` and `g` consists of components `h i j : C.X i ⟶ D.X j` which are zero unless `c.rel j i`, satisfying the homotopy condition. -/ @[ext, nolint has_inhabited_instance] structure homotopy (f g : C ⟶ D) := (hom : Π i j, C.X i ⟶ D.X j) (zero' : ∀ i j, ¬ c.rel j i → hom i j = 0 . obviously) (comm : ∀ i, f.f i = d_next i hom + prev_d i hom + g.f i . obviously') variables {f g} namespace homotopy restate_axiom homotopy.zero' /-- `f` is homotopic to `g` iff `f - g` is homotopic to `0`. -/ def equiv_sub_zero : homotopy f g ≃ homotopy (f - g) 0 := { to_fun := λ h, { hom := λ i j, h.hom i j, zero' := λ i j w, h.zero _ _ w, comm := λ i, by simp [h.comm] }, inv_fun := λ h, { hom := λ i j, h.hom i j, zero' := λ i j w, h.zero _ _ w, comm := λ i, by simpa [sub_eq_iff_eq_add] using h.comm i }, left_inv := by tidy, right_inv := by tidy, } /-- Equal chain maps are homotopic. -/ @[simps] def of_eq (h : f = g) : homotopy f g := { hom := 0, zero' := λ _ _ _, rfl, comm := λ _, by simp only [add_monoid_hom.map_zero, zero_add, h] } /-- Every chain map is homotopic to itself. -/ @[simps, refl] def refl (f : C ⟶ D) : homotopy f f := of_eq (rfl : f = f) /-- `f` is homotopic to `g` iff `g` is homotopic to `f`. -/ @[simps, symm] def symm {f g : C ⟶ D} (h : homotopy f g) : homotopy g f := { hom := -h.hom, zero' := λ i j w, by rw [pi.neg_apply, pi.neg_apply, h.zero i j w, neg_zero], comm := λ i, by rw [add_monoid_hom.map_neg, add_monoid_hom.map_neg, h.comm, ← neg_add, ← add_assoc, neg_add_self, zero_add] } /-- homotopy is a transitive relation. -/ @[simps, trans] def trans {e f g : C ⟶ D} (h : homotopy e f) (k : homotopy f g) : homotopy e g := { hom := h.hom + k.hom, zero' := λ i j w, by rw [pi.add_apply, pi.add_apply, h.zero i j w, k.zero i j w, zero_add], comm := λ i, by { rw [add_monoid_hom.map_add, add_monoid_hom.map_add, h.comm, k.comm], abel }, } /-- homotopy is closed under composition (on the right) -/ @[simps] def comp_right {e f : C ⟶ D} (h : homotopy e f) (g : D ⟶ E) : homotopy (e ≫ g) (f ≫ g) := { hom := λ i j, h.hom i j ≫ g.f j, zero' := λ i j w, by rw [h.zero i j w, zero_comp], comm := λ i, by simp only [h.comm i, d_next_comp_right, preadditive.add_comp, to_prev'_comp_right, comp_f], } /-- homotopy is closed under composition (on the left) -/ @[simps] def comp_left {f g : D ⟶ E} (h : homotopy f g) (e : C ⟶ D) : homotopy (e ≫ f) (e ≫ g) := { hom := λ i j, e.f i ≫ h.hom i j, zero' := λ i j w, by rw [h.zero i j w, comp_zero], comm := λ i, by simp only [h.comm i, d_next_comp_left, preadditive.comp_add, prev_d_comp_left, comp_f], } /-- homotopy is closed under composition -/ @[simps] def comp {C₁ C₂ C₃ : homological_complex V c} {f₁ g₁ : C₁ ⟶ C₂} {f₂ g₂ : C₂ ⟶ C₃} (h₁ : homotopy f₁ g₁) (h₂ : homotopy f₂ g₂) : homotopy (f₁ ≫ f₂) (g₁ ≫ g₂) := (h₁.comp_right _).trans (h₂.comp_left _) /-- a variant of `homotopy.comp_right` useful for dealing with homotopy equivalences. -/ @[simps] def comp_right_id {f : C ⟶ C} (h : homotopy f (𝟙 C)) (g : C ⟶ D) : homotopy (f ≫ g) g := (h.comp_right g).trans (of_eq $ category.id_comp _) /-- a variant of `homotopy.comp_left` useful for dealing with homotopy equivalences. -/ @[simps] def comp_left_id {f : D ⟶ D} (h : homotopy f (𝟙 D)) (g : C ⟶ D) : homotopy (g ≫ f) g := (h.comp_left g).trans (of_eq $ category.comp_id _) /-! `homotopy.mk_inductive` allows us to build a homotopy inductively, so that as we construct each component, we have available the previous two components, and the fact that they satisfy the homotopy condition. To simplify the situation, we only construct homotopies of the form `homotopy e 0`. `homotopy.equiv_sub_zero` can provide the general case. Notice however, that this construction does not have particularly good definitional properties: we have to insert `eq_to_hom` in several places. Hopefully this is okay in most applications, where we only need to have the existence of some homotopy. -/ section mk_inductive variables {P Q : chain_complex V ℕ} @[simp] lemma prev_d_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (j : ℕ) : prev_d j f = f j (j+1) ≫ Q.d _ _ := begin dsimp [prev_d], simp only [chain_complex.prev], refl, end @[simp] lemma d_next_succ_chain_complex (f : Π i j, P.X i ⟶ Q.X j) (i : ℕ) : d_next (i+1) f = P.d _ _ ≫ f i (i+1) := begin dsimp [d_next], simp only [chain_complex.next_nat_succ], refl, end @[simp] lemma d_next_zero_chain_complex (f : Π i j, P.X i ⟶ Q.X j) : d_next 0 f = 0 := begin dsimp [d_next], simp only [chain_complex.next_nat_zero], refl, end variables (e : P ⟶ Q) (zero : P.X 0 ⟶ Q.X 1) (comm_zero : e.f 0 = zero ≫ Q.d 1 0) (one : P.X 1 ⟶ Q.X 2) (comm_one : e.f 1 = P.d 1 0 ≫ zero + one ≫ Q.d 2 1) (succ : ∀ (n : ℕ) (p : Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)), e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1)), Σ' f'' : P.X (n+2) ⟶ Q.X (n+3), e.f (n+2) = P.d (n+2) (n+1) ≫ p.2.1 + f'' ≫ Q.d (n+3) (n+2)) include comm_one comm_zero /-- An auxiliary construction for `mk_inductive`. Here we build by induction a family of diagrams, but don't require at the type level that these successive diagrams actually agree. They do in fact agree, and we then capture that at the type level (i.e. by constructing a homotopy) in `mk_inductive`. At this stage, we don't check the homotopy condition in degree 0, because it "falls off the end", and is easier to treat using `X_next` and `X_prev`, which we do in `mk_inductive_aux₂`. -/ @[simp, nolint unused_arguments] def mk_inductive_aux₁ : Π n, Σ' (f : P.X n ⟶ Q.X (n+1)) (f' : P.X (n+1) ⟶ Q.X (n+2)), e.f (n+1) = P.d (n+1) n ≫ f + f' ≫ Q.d (n+2) (n+1) | 0 := ⟨zero, one, comm_one⟩ | 1 := ⟨one, (succ 0 ⟨zero, one, comm_one⟩).1, (succ 0 ⟨zero, one, comm_one⟩).2⟩ | (n+2) := ⟨(mk_inductive_aux₁ (n+1)).2.1, (succ (n+1) (mk_inductive_aux₁ (n+1))).1, (succ (n+1) (mk_inductive_aux₁ (n+1))).2⟩ section variable [has_zero_object V] /-- An auxiliary construction for `mk_inductive`. -/ @[simp] def mk_inductive_aux₂ : Π n, Σ' (f : P.X_next n ⟶ Q.X n) (f' : P.X n ⟶ Q.X_prev n), e.f n = P.d_from n ≫ f + f' ≫ Q.d_to n | 0 := ⟨0, zero ≫ (Q.X_prev_iso rfl).inv, by simpa using comm_zero⟩ | (n+1) := let I := mk_inductive_aux₁ e zero comm_zero one comm_one succ n in ⟨(P.X_next_iso rfl).hom ≫ I.1, I.2.1 ≫ (Q.X_prev_iso rfl).inv, by simpa using I.2.2⟩ lemma mk_inductive_aux₃ (i : ℕ) : (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso rfl).hom = (P.X_next_iso rfl).inv ≫ (mk_inductive_aux₂ e zero comm_zero one comm_one succ (i+1)).1 := by rcases i with (_|_|i); { dsimp, simp, } /-- A constructor for a `homotopy e 0`, for `e` a chain map between `ℕ`-indexed chain complexes, working by induction. You need to provide the components of the homotopy in degrees 0 and 1, show that these satisfy the homotopy condition, and then give a construction of each component, and the fact that it satisfies the homotopy condition, using as an inductive hypothesis the data and homotopy condition for the previous two components. -/ def mk_inductive : homotopy e 0 := { hom := λ i j, if h : i + 1 = j then (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.1 ≫ (Q.X_prev_iso h).hom else 0, zero' := λ i j w, by rwa dif_neg, comm := λ i, begin dsimp, simp only [add_zero], convert (mk_inductive_aux₂ e zero comm_zero one comm_one succ i).2.2, { rcases i with (_|_|_|i), { dsimp, simp only [d_next_zero_chain_complex, d_from_eq_zero, limits.comp_zero], }, all_goals { simp only [d_next_succ_chain_complex], dsimp, simp only [category.comp_id, category.assoc, iso.inv_hom_id, d_from_comp_X_next_iso_assoc, dite_eq_ite, if_true, eq_self_iff_true]}, }, { cases i, all_goals { simp only [prev_d_chain_complex], dsimp, simp only [category.comp_id, category.assoc, iso.inv_hom_id, X_prev_iso_comp_d_to, dite_eq_ite, if_true, eq_self_iff_true], }, }, end, } end end mk_inductive end homotopy /-- A homotopy equivalence between two chain complexes consists of a chain map each way, and homotopies from the compositions to the identity chain maps. Note that this contains data; arguably it might be more useful for many applications if we truncated it to a Prop. -/ structure homotopy_equiv (C D : homological_complex V c) := (hom : C ⟶ D) (inv : D ⟶ C) (homotopy_hom_inv_id : homotopy (hom ≫ inv) (𝟙 C)) (homotopy_inv_hom_id : homotopy (inv ≫ hom) (𝟙 D)) namespace homotopy_equiv /-- Any complex is homotopy equivalent to itself. -/ @[refl] def refl (C : homological_complex V c) : homotopy_equiv C C := { hom := 𝟙 C, inv := 𝟙 C, homotopy_hom_inv_id := by simp, homotopy_inv_hom_id := by simp, } instance : inhabited (homotopy_equiv C C) := ⟨refl C⟩ /-- Being homotopy equivalent is a symmetric relation. -/ @[symm] def symm {C D : homological_complex V c} (f : homotopy_equiv C D) : homotopy_equiv D C := { hom := f.inv, inv := f.hom, homotopy_hom_inv_id := f.homotopy_inv_hom_id, homotopy_inv_hom_id := f.homotopy_hom_inv_id, } /-- Homotopy equivalence is a transitive relation. -/ @[trans] def trans {C D E : homological_complex V c} (f : homotopy_equiv C D) (g : homotopy_equiv D E) : homotopy_equiv C E := { hom := f.hom ≫ g.hom, inv := g.inv ≫ f.inv, homotopy_hom_inv_id := by simpa using ((g.homotopy_hom_inv_id.comp_right_id f.inv).comp_left f.hom).trans f.homotopy_hom_inv_id, homotopy_inv_hom_id := by simpa using ((f.homotopy_inv_hom_id.comp_right_id g.hom).comp_left g.inv).trans g.homotopy_inv_hom_id, } end homotopy_equiv variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V] variable [has_zero_object V] /-- Homotopic maps induce the same map on homology. -/ theorem homology_map_eq_of_homotopy (h : homotopy f g) (i : ι) : (homology_functor V c i).map f = (homology_functor V c i).map g := begin dsimp [homology_functor], apply eq_of_sub_eq_zero, ext, simp only [homology.π_map, comp_zero, preadditive.comp_sub], dsimp [kernel_subobject_map], simp_rw [h.comm i], simp only [zero_add, zero_comp, d_next_eq_d_from_from_next, kernel_subobject_arrow_comp_assoc, preadditive.comp_add], rw [←preadditive.sub_comp], simp only [category_theory.subobject.factor_thru_add_sub_factor_thru_right], erw [subobject.factor_thru_of_le (D.boundaries_le_cycles i)], { simp, }, { rw [prev_d_eq_to_prev_d_to, ←category.assoc], apply image_subobject_factors_comp_self, }, end /-- Homotopy equivalent complexes have isomorphic homologies. -/ def homology_obj_iso_of_homotopy_equiv (f : homotopy_equiv C D) (i : ι) : (homology_functor V c i).obj C ≅ (homology_functor V c i).obj D := { hom := (homology_functor V c i).map f.hom, inv := (homology_functor V c i).map f.inv, hom_inv_id' := begin rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_hom_inv_id, category_theory.functor.map_id], end, inv_hom_id' := begin rw [←functor.map_comp, homology_map_eq_of_homotopy f.homotopy_inv_hom_id, category_theory.functor.map_id], end, } end namespace category_theory variables {W : Type*} [category W] [preadditive W] /-- An additive functor takes homotopies to homotopies. -/ @[simps] def functor.map_homotopy (F : V ⥤ W) [F.additive] {f g : C ⟶ D} (h : homotopy f g) : homotopy ((F.map_homological_complex c).map f) ((F.map_homological_complex c).map g) := { hom := λ i j, F.map (h.hom i j), zero' := λ i j w, by { rw [h.zero i j w, F.map_zero], }, comm := λ i, begin have := h.comm i, dsimp [d_next, prev_d] at *, rcases c.next i with _|⟨inext,wn⟩; rcases c.prev i with _|⟨iprev,wp⟩; dsimp [d_next, prev_d] at *; { intro h, simp [h] }, end, } /-- An additive functor preserves homotopy equivalences. -/ @[simps] def functor.map_homotopy_equiv (F : V ⥤ W) [F.additive] (h : homotopy_equiv C D) : homotopy_equiv ((F.map_homological_complex c).obj C) ((F.map_homological_complex c).obj D) := { hom := (F.map_homological_complex c).map h.hom, inv := (F.map_homological_complex c).map h.inv, homotopy_hom_inv_id := begin rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id], exact F.map_homotopy h.homotopy_hom_inv_id, end, homotopy_inv_hom_id := begin rw [←(F.map_homological_complex c).map_comp, ←(F.map_homological_complex c).map_id], exact F.map_homotopy h.homotopy_inv_hom_id, end } end category_theory
23836c896974618db8258dd599e366e7531a3cf7
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/bases.lean
f05c427528293f376d55cfe9257f84594220097e
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,114
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.continuous_on import topology.constructions /-! # 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. * `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 classical 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 α) | finite f ∧ 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, bUnion_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 binfi_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 only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { 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.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 } 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 set.prod 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.prod 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 α, countable s ∧ dense s) lemma exists_countable_dense [separable_space α] : ∃ s : set α, countable s ∧ 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 countable_iff_exists_surjective.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 {α} /-- In a separable space, a family of nonempty disjoint open sets is countable. -/ lemma countable_of_is_open_of_disjoint [separable_space α] {β : Type*} (s : β → set α) {a : set β} (ha : ∀ i ∈ a, is_open (s i)) (h'a : ∀ i ∈ a, (s i).nonempty) (h : a.pairwise_on (disjoint on s)) : countable a := begin rcases eq_empty_or_nonempty a with rfl|H, { exact countable_empty }, haveI : inhabited α, { choose i ia using H, choose y hy using h'a i ia, exact ⟨y⟩ }, rcases exists_countable_dense α with ⟨u, u_count, u_dense⟩, have : ∀ i, i ∈ a → ∃ y, y ∈ s i ∩ u := λ i hi, dense_iff_inter_open.1 u_dense (s i) (ha i hi) (h'a i hi), choose! f hf using this, have f_inj : inj_on f a, { assume i hi j hj hij, have : ¬disjoint (s i) (s j), { rw not_disjoint_iff_nonempty_inter, refine ⟨f i, (hf i hi).1, _⟩, rw hij, exact (hf j hj).1 }, contrapose! this, exact h i hi j hj this }, apply countable_of_injective_of_countable_image f_inj, apply u_count.mono _, exact image_subset_iff.2 (λ i hi, (hf i hi).2) end /-- In a separable space, a family of disjoint sets with nonempty interiors is countable. -/ lemma countable_of_nonempty_interior_of_disjoint [separable_space α] {β : Type*} (s : β → set α) {a : set β} (ha : ∀ i ∈ a, (interior (s i)).nonempty) (h : a.pairwise_on (disjoint on s)) : countable a := begin have : a.pairwise_on (disjoint on (λ i, interior (s i))) := pairwise_on_disjoint_on_mono h (λ i hi, interior_subset), exact countable_of_is_open_of_disjoint (λ i, interior (s i)) (λ i hi, is_open_interior) ha this 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 classical, 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 is_topological_basis.is_open (cond i) (h1 i hi) }, { intros a U ha hU, have : U ∈ nhds a := is_open.mem_nhds hU ha, rw [nhds_pi, filter.mem_infi] at this, obtain ⟨F, hF, V, hV1, rfl⟩ := this, choose U' hU' using hV1, obtain ⟨hU1, hU2⟩ := ⟨λ i, (hU' i).1, λ i, (hU' i).2⟩, have : ∀ j : F, ∃ (T' : set (X j)) (hT : T' ∈ T j), a j ∈ T' ∧ T' ⊆ U' j, { intros i, specialize hU1 i, rwa (cond i).mem_nhds_iff at hU1 }, choose U'' hU'' using this, let U : Π (i : ι), set (X i) := λ i, if hi : i ∈ F then U'' ⟨i, hi⟩ else set.univ, refine ⟨F.pi U, ⟨U, hF.to_finset, λ i hi, _, by simp⟩, _, _⟩, { dsimp only [U], rw [dif_pos], swap, { simpa using hi }, exact (hU'' _).1 }, { rw set.mem_pi, intros i hi, dsimp only [U], rw dif_pos hi, exact (hU'' _).2.1 }, { intros x hx, rintros - ⟨i, rfl⟩, refine hU2 i ((hU'' i).2.2 _), convert hx i i.2, rcases i with ⟨i, p⟩, dsimp [U], rw dif_pos p, } }, 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 /-- 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, countable t ∧ 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⟩ 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 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 α), countable b ∧ t = topological_space.generate_from b) variable {α} protected lemma is_topological_basis.second_countable_topology {b : set (set α)} (hb : is_topological_basis b) (hc : countable b) : second_countable_topology α := ⟨⟨b, hc, hb.eq_generate_from⟩⟩ variable (α) lemma exists_countable_basis [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ 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 (countable_basis α) := (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 second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := begin have : t = (λa, generate_from (countable_basis (π a))), from funext (assume a, (is_basis_countable_basis (π a)).eq_generate_from), rw this, constructor, refine ⟨pi univ '' pi univ (λ a, countable_basis (π a)), countable.image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ countable_basis (π a)}, { simpa [pi] }, exact countable_pi (assume i, (countable_countable_basis _)), }, rw [pi_generate_from_eq_fintype], { congr' 1 with f, simp [pi, eq_comm] }, exact assume a, (is_basis_countable_basis (π a)).sUnion_eq 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 ι, countable T ∧ (⋃ 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, subset.antisymm (bUnion_subset_Union _ _) (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 α), countable T ∧ 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 α, countable s ∧ (⋃ 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 (bUnion_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, countable t ∧ 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 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
3caeee75870ab19676748359e4b555e6d5346b61
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/testre.lean
b807cd1b4cb11ef83819c16cc5e1d801e22f5667
[]
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
723
lean
example {a : Type u} {s t : list α} : length (s ++ t) = length s + length t := list.rec_on s ( -- length t = length [] + length t -- length [] = 0 by definition -- 0 + x = x by definition show length ([] ++ t) = length [] + length t, from begin have z : [] ++ t = t, from rfl, rw z, have g : length [] = 0, from rfl, assumption, rw g, rw zero_add, end ) ( λ x y z, -- z : length (y ++ t) = length y + length t show length (x :: y ++ t) = length (x :: y) + length t, from begin show length (x :: y ++ t) = ((length y) + 1) + length t, have r : length (x :: y) = ((length y) + 1), refl, -- unfinished end )
3c595cc65b9bd40c1101cce66f465e6a6173397c
a6f55abce20abcd06e718cb3e5fba7bf8a230fa1
/topic/vehicle.lean
2717b9d76c70013bbfd223f8408c5b179feec1c1
[]
no_license
sonna0909/abc
b8a53e906d4d000d1f2347173a1cd4221757fabf
ff7b4c621cdf6d53937f2d1b6def28de2085a2aa
refs/heads/master
1,599,114,664,248
1,573,634,309,000
1,573,634,309,000
219,406,484
0
0
null
null
null
null
UTF-8
Lean
false
false
5,556
lean
[ { "key": "car", "title": "Car", "spelling": "/kɑːr/", "subs": [ { "key": "car1", "title": "This is a car", "spelling": "" } ] }, { "key": "truck", "title": "Truck", "spelling": "/trʌk/", "subs": [ { "key": "truck1", "title": "This is a truck", "spelling": "" } ] }, { "key": "bus", "title": "Bus", "spelling": "/bʌs/", "subs": [ { "key": "bus1", "title": "That is a bus", "spelling": "" } ] }, { "key": "bicycle", "title": "Bicycle", "spelling": "/ˈbaɪsɪkl/", "subs": [ { "key": "bicycle1", "title": "I have a bicycle", "spelling": "" } ] }, { "key": "scooter", "title": "Scooter", "spelling": "/ˈskuːtər/", "subs": [ { "key": "scooter1", "title": "I have a scooter", "spelling": "" } ] }, { "key": "motorbike", "title": "Motorbike", "spelling": "/ˈməʊtəbaɪk/", "subs": [ { "key": "motorbike1", "title": "She has a motorbike", "spelling": "" } ] }, { "key": "train", "title": "Train", "spelling": "/treɪn/", "subs": [ { "key": "train1", "title": "This is a train", "spelling": "" } ] }, { "key": "subway", "title": "Subway", "spelling": "/ˈsʌbweɪ/", "subs": [ { "key": "subway1", "title": "That is subway", "spelling": "" } ] }, { "key": "jet", "title": "Jet", "spelling": "/dʒet/", "subs": [ { "key": "jet1", "title": "That is the jet", "spelling": "" } ] }, { "key": "cart", "title": "Cart", "spelling": "/kɑ:t/", "subs": [ { "key": "cart1", "title": "That is the cart", "spelling": "" } ] }, { "key": "ship", "title": "Ship", "spelling": "/ʃip/", "subs": [ { "key": "ship1", "title": "That is the ship", "spelling": "" } ] }, { "key": "fire_truck", "title": "Fire truck", "spelling": "/'faie trʌk/", "subs": [ { "key": "fire_truck1", "title": "That is the fire truck", "spelling": "" } ] }, { "key": "boat", "title": "Boat", "spelling": "/bout/", "subs": [ { "key": "boat1", "title": "This is a boat", "spelling": "" } ] }, { "key": "van", "title": "Van", "spelling": "/væn/", "subs": [ { "key": "van1", "title": "This is a van", "spelling": "" } ] }, { "key": "police_car", "title": "Police car", "spelling": "/pə'li:s kɑ:/", "subs": [ { "key": "police_car1", "title": "That is a police car", "spelling": "" } ] }, { "key": "airplane", "title": "Airplane", "spelling": "/'eəplein/", "subs": [ { "key": "airplane1", "title": "The airplane is fying in the sky", "spelling": "" } ] }, { "key": "ambulance", "title": "Ambulance", "spelling": "/'æmbjuləns/", "subs": [ { "key": "ambulance1", "title": "This is the ambulance", "spelling": "" } ] }, { "key": "cruise_ship", "title": "Cruise ship", "spelling": "/kru:z ʃip/", "subs": [ { "key": "cruise_ship1", "title": "This is the cruise ship", "spelling": "" } ] }, { "key": "submarine", "title": "Submarine", "spelling": "/ˌsʌbmərˈiːn/", "subs": [ { "key": "submarine1", "title": "This is the submarine", "spelling": "" } ] }, { "key": "helicopter", "title": "Helicopter", "spelling": "/ˈhelɪkɒptər/", "subs": [ { "key": "helicopter1", "title": "The helicopter is flying in the sky", "spelling": "" } ] }, { "key": "rocket", "title": "Rocket", "spelling": "/ˈrɒkɪt/", "subs": [ { "key": "rocket1", "title": "That is the rocket", "spelling": "" } ] }, { "key": "hot-air_balloon", "title": "Hot-air balloon", "spelling": "/hɔt eə bə'lu:n/", "subs": [ { "key": "hot-air_balloon1", "title": "That is the hot-air balloon", "spelling": "" } ] }, { "key": "tricycle", "title": "Tricycle", "spelling": "/'traisikl/", "subs": [ { "key": "tricycle1", "title": "This is the tricycle", "spelling": "" } ] }, { "key": "motorized_bicycle", "title": "Motorized bicycle", "spelling": "/ˈməʊtəzaɪk 'baisikl/", "subs": [ { "key": "motorized_bicycle1", "title": "I have a motorized bicycle", "spelling": "" } ] }, { "key": "cable_car", "title": "Cable car", "spelling": "/'keibl kɑ:/", "subs": [ { "key": "cable_car1", "title": "This is the cable car", "spelling": "" } ] }, { "key": "tram", "title": "Tram", "spelling": "/træm/", "subs": [ { "key": "tram1", "title": "This is the tram", "spelling": "" } ] } ]
771315ab18be45c574d1d48746449d92dc0fc0c0
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/euclidean_domain.lean
1a0bf914b04d76d73f7ab646de9d425bf64498f1
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,801
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import ring_theory.ideals noncomputable theory open_locale classical open euclidean_domain set ideal theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin apply le_antisymm, { refine span_le.2 (λ x, _), simp only [set.mem_singleton_iff, submodule.mem_coe, mem_span_pair], rintro rfl, exact ⟨gcd_a x y, gcd_b x y, by simp [gcd_eq_gcd_ab, mul_comm]⟩ }, { assume z , simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair, @eq_comm _ _ z] {contextual := tt}, assume a b h, exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _) (dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) } end theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := by rw [← span_singleton_eq_top, span_gcd, is_coprime] theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, euclidean_domain.gcd_eq_zero_iff] end theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), unfreezeI, apply is_coprime_of_dvd, { rintro ⟨rfl, rfl⟩, simpa using h }, { rintro z nu nz ⟨w, rfl⟩ dy, refine h' (dvd.trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end
66b9aa7d577e7f0fb9cc309a0c81a122626052e4
618003631150032a5676f229d13a079ac875ff77
/src/tactic/simps.lean
46831659a9bdb75fe38d3b7382054d843d388800
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,647
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.core /-! # simps attribute This file defines the `@[simps]` attribute, to automatically generate simp-lemmas reducing a definition when projections are applied to it. ## Tags structures, projections, simp, simplifier, generates declarations -/ open tactic expr /-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`, `args` is the list of local constants occurring, and `univs` is the list of universe variables. If `add_simp` then we make the resulting lemma a simp-lemma. -/ meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr) (univs : list name) (add_simp : bool) : tactic unit := do eq_ap ← mk_mapp `eq $ [type, lhs, rhs].map some, refl_ap ← mk_app `eq.refl [type, lhs], decl_name ← get_unused_decl_name nm, let decl_type := eq_ap.pis args, let decl_value := refl_ap.lambdas args, let decl := declaration.thm decl_name univs decl_type (pure decl_value), add_decl decl <|> fail format!"failed to add projection lemma {decl_name}.", when add_simp $ do set_basic_attribute `_refl_lemma decl_name tt, set_basic_attribute `simp decl_name tt /-- Derive lemmas specifying the projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. -/ meta def simps_add_projections : ∀(e : environment) (nm : name) (suffix : string) (type lhs rhs : expr) (args : list expr) (univs : list name) (add_simp must_be_str short_nm : bool) (todo : list string), tactic unit | e nm suffix type lhs rhs args univs add_simp must_be_str short_nm todo := do (type_args, tgt) ← mk_local_pis_whnf type, tgt ← whnf tgt, let new_args := args ++ type_args, let lhs_ap := lhs.mk_app type_args, let rhs_ap := rhs.instantiate_lambdas_or_apps type_args, let str := tgt.get_app_fn.const_name, if e.is_structure str then do projs ← e.structure_fields_full str, [intro] ← return $ e.constructors_of str | fail "unreachable code (3)", let params := get_app_args tgt, -- the parameters of the structure if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application guard ((get_app_args rhs_ap).take params.length = params) <|> fail "unreachable code (1)", let rhs_args := (get_app_args rhs_ap).drop params.length, -- the fields of the structure guard (rhs_args.length = projs.length) <|> fail "unreachable code (2)", let pairs := projs.zip rhs_args, eta ← expr.is_eta_expansion_aux rhs_ap pairs, -- check whether `rhs_ap` is an eta-expansion let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap` /- we want to generate the current projection if it is in `todo` or when `rhs_ap` was an eta-expansion -/ when ("" ∈ todo ∨ (todo = [] ∧ eta.is_some)) $ simps_add_projection (nm.append_suffix suffix) tgt lhs_ap rhs_ap new_args univs add_simp, -- if `rhs_ap` was an eta-expansion and `todo` is empty, we stop when ¬(todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do /- remove "" from todo. This allows a to generate lemmas + nested version of them. This is not very useful, but this does improve error messages. -/ let todo := todo.filter $ (≠ ""), -- check whether all elements in `todo` have a projection as prefix guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|> let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget, simp_lemma := nm.append_suffix $ suffix ++ x, needed_proj := (x.split_on '_').tail.head in fail format!"Invalid simp-lemma {simp_lemma}. Projection {needed_proj} doesn't exist.", pairs.mmap' $ λ ⟨proj, new_rhs⟩, do new_type ← infer_type new_rhs, let new_todo := todo.filter_map $ λ x, string.get_rest x $ "_" ++ proj.last, b ← is_prop new_type, -- we only continue with this field if it is non-propositional or mentioned in todo when ((¬ b ∧ todo = []) ∨ (todo ≠ [] ∧ new_todo ≠ [])) $ do -- cannot use `mk_app` here, since the resulting application might still be a function. new_lhs ← mk_mapp proj $ (params ++ [lhs_ap]).map some, let new_suffix := if short_nm then "_" ++ proj.last else suffix ++ "_" ++ proj.last, simps_add_projections e nm new_suffix new_type new_lhs new_rhs new_args univs add_simp ff short_nm new_todo else do when must_be_str $ fail "Invalid `simps` attribute. Body is not a constructor application", when (todo ≠ [] ∧ todo ≠ [""]) $ fail format!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo.head}. Too many projections given.", simps_add_projection (nm.append_suffix suffix) tgt lhs_ap rhs_ap new_args univs add_simp else do when must_be_str $ fail "Invalid `simps` attribute. Target is not a structure", when (todo ≠ [] ∧ todo ≠ [""]) $ fail format!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo.head}. Too many projections given.", simps_add_projection (nm.append_suffix suffix) tgt lhs_ap rhs_ap new_args univs add_simp /-- `simps_tac` derives simp-lemmas for all (nested) non-Prop projections of the declaration. If `todo` is non-empty, it will generate exactly the names in `todo`. If `short_nm` is true, the generated names will only use the last projection name. -/ meta def simps_tac (nm : name) (add_simp : bool) (short_nm : bool := ff) (todo : list string := []) : tactic unit := do e ← get_env, d ← e.get nm, let lhs : expr := const d.to_name (d.univ_params.map level.param), let todo := todo.erase_dup.map $ λ proj, "_" ++ proj, simps_add_projections e nm "" d.type lhs d.value [] d.univ_params add_simp tt short_nm todo reserve notation `lemmas_only` reserve notation `short_name` setup_tactic_parser /-- The parser for simps. Pattern: `'lemmas_only'? ident*` -/ meta def simps_parser : parser (bool × bool × list string) := /- note: we currently don't check whether the user has written a nonsense namespace as arguments. -/ prod.mk <$> (option.is_none <$> (tk "lemmas_only")?) <*> (prod.mk <$> (option.is_some <$> (tk "short_name")?) <*> many (name.last <$> ident)) /-- The `@[simps]` attribute automatically derives lemmas specifying the projections of this declaration. Example: (note that the forward and reverse functions are specified differently!) ```lean @[simps] def refl (α) : α ≃ α := ⟨id, λ x, x, λ x, rfl, λ x, rfl⟩ ``` derives two simp-lemmas: ```lean @[simp] lemma refl_to_fun (α) (x : α) : (refl α).to_fun x = id x @[simp] lemma refl_inv_fun (α) (x : α) : (refl α).inv_fun x = x ``` * It does not derive simp-lemmas for the prop-valued projections. * It will automatically reduce newly created beta-redexes, but not unfold any definitions. * If one of the fields itself is a structure, this command will recursively create simp-lemmas for all fields in that structure. * You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified projections. For example: ```lean attribute [simps to_fun] refl ``` * If one of the values is an eta-expanded structure, we will eta-reduce this structure. * You can use `@[simps lemmas_only]` to derive the lemmas, but not mark them as simp-lemmas. * You can use `@[simps short_name]` to only use the name of the last projection for the name of the generated lemmas. * The precise syntax is `('simps' 'lemmas_only'? 'short_name'? ident*)`. * If one of the projections is marked as a coercion, the generated lemmas do *not* use this coercion. * `@[simps]` reduces let-expressions where necessary. * If one of the fields is a partially applied constructor, we will eta-expand it (this likely never happens). -/ @[user_attribute] meta def simps_attr : user_attribute unit (bool × bool × list string) := { name := `simps, descr := "Automatically derive lemmas specifying the projections of this declaration.", parser := simps_parser, after_set := some $ λ n _ _, do (add_simp, short_nm, todo) ← simps_attr.get_param n, simps_tac n add_simp short_nm todo } add_tactic_doc { name := "simps", category := doc_category.attr, decl_names := [`simps_attr], tags := ["simplification"] }
888629bf6c68e29d8b5e14d0ecaf73e8da140080
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/explode.lean
3a881e261bae3c0d5cb0a759127025c05ba2d1ed
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
6,053
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import tactic.core /-! # `#explode` command Displays a proof term in a line by line format somewhat akin to a Fitch style proof or the Metamath proof style. -/ open expr tactic namespace tactic namespace explode -- TODO(Mario): move back to list.basic @[simp] def head' {α} : list α → option α | [] := none | (a :: l) := some a @[derive inhabited] inductive status | reg | intro | lam | sintro meta structure entry := (expr : expr) (line : nat) (depth : nat) (status : status) (thm : string) (deps : list nat) meta def pad_right (l : list string) : list string := let n := l.foldl (λ r (s:string), max r s.length) 0 in l.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s @[derive inhabited] meta structure entries := mk' :: (s : expr_map entry) (l : list entry) meta def entries.find (es : entries) (e : expr) := es.s.find e meta def entries.size (es : entries) := es.s.size meta def entries.add : entries → entry → entries | es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩ meta def entries.head (es : entries) : option entry := head' es.l meta def format_aux : list string → list string → list string → list entry → tactic format | (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do fmt ← do { let margin := string.join (list.repeat " │" en.depth), let margin := match en.status with | status.sintro := " ├" ++ margin | status.intro := " │" ++ margin ++ " ┌" | status.reg := " │" ++ margin ++ "" | status.lam := " │" ++ margin ++ "" end, p ← infer_type en.expr >>= pp, let lhs := line ++ "│" ++ dep ++ "│ " ++ thm ++ margin ++ " ", return $ format.of_string lhs ++ to_string p ++ format.line }, (++ fmt) <$> format_aux lines deps thms es | _ _ _ _ := return format.nil meta instance : has_to_tactic_format entries := ⟨λ es : entries, let lines := pad_right $ es.l.map (λ en, to_string en.line), deps := pad_right $ es.l.map (λ en, string.intercalate "," (en.deps.map to_string)), thms := pad_right $ es.l.map entry.thm in format_aux lines deps thms es.l⟩ meta def append_dep (filter : expr → tactic unit) (es : entries) (e : expr) (deps : list nat) : tactic (list nat) := do { ei ← es.find e, filter ei.expr, return (ei.line :: deps) } <|> return deps meta def may_be_proof (e : expr) : tactic bool := do expr.sort u ← infer_type e >>= infer_type, return $ bnot u.nonzero end explode open explode meta mutual def explode.core, explode.args (filter : expr → tactic unit) with explode.core : expr → bool → nat → entries → tactic entries | e@(lam n bi d b) si depth es := do m ← mk_fresh_name, let l := local_const m n bi d, let b' := instantiate_var b l, if si then let en : entry := ⟨l, es.size, depth, status.sintro, to_string n, []⟩ in do es' ← explode.core b' si depth (es.add en), return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", [es.size, es'.size - 1]⟩ else do let en : entry := ⟨l, es.size, depth, status.intro, to_string n, []⟩, es' ← explode.core b' si (depth + 1) (es.add en), deps' ← explode.append_dep filter es' b' [], deps' ← explode.append_dep filter es' l deps', return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", deps'⟩ | e@(macro _ l) si depth es := explode.core l.head si depth es | e si depth es := filter e >> match get_app_fn_args e with | (const n _, args) := explode.args e args depth es (to_string n) [] | (fn, []) := do p ← pp fn, let en : entry := ⟨fn, es.size, depth, status.reg, to_string p, []⟩, return (es.add en) | (fn, args) := do es' ← explode.core fn ff depth es, deps ← explode.append_dep filter es' fn [], explode.args e args depth es' "∀E" deps end with explode.args : expr → list expr → nat → entries → string → list nat → tactic entries | e (arg :: args) depth es thm deps := do es' ← explode.core arg ff depth es <|> return es, deps' ← explode.append_dep filter es' arg deps, explode.args e args depth es' thm deps' | e [] depth es thm deps := return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩) meta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries := let filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in tactic.explode.core filter e tt 0 (default _) meta def explode (n : name) : tactic unit := do const n _ ← resolve_name n | fail "cannot resolve name", d ← get_decl n, v ← match d with | (declaration.defn _ _ _ v _ _) := return v | (declaration.thm _ _ _ v) := return v.get | _ := fail "not a definition" end, t ← pp d.type, explode_expr v <* trace (to_fmt n ++ " : " ++ t) >>= trace open interactive lean lean.parser interaction_monad.result /-- `#explode decl_name` displays a proof term in a line by line format somewhat akin to a Fitch style proof or the Metamath proof style. `#explode iff_true_intro` produces ```lean iff_true_intro : ∀ {a : Prop}, a → (a ↔ true) 0│ │ a ├ Prop 1│ │ h ├ a 2│ │ hl │ ┌ a 3│ │ trivial │ │ true 4│2,3│ ∀I │ a → true 5│ │ hr │ ┌ true 6│5,1│ ∀I │ true → a 7│4,6│ iff.intro │ a ↔ true 8│1,7│ ∀I │ a → (a ↔ true) 9│0,8│ ∀I │ ∀ {a : Prop}, a → (a ↔ true) ``` -/ @[user_command] meta def explode_cmd (_ : parse $ tk "#explode") : parser unit := do n ← ident, explode n . add_tactic_doc { name := "#explode", category := doc_category.cmd, decl_names := [`tactic.explode_cmd], tags := ["proof display"] } -- #explode iff_true_intro -- #explode nat.strong_rec_on end tactic
39f50634bd8f3c28426ae85c240fde2b51039072
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/topology/instances/nnreal.lean
b15be55e4ea07f008a05b5e1474930b2fb1032b4
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,333
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.algebra.infinite_sum import topology.algebra.group_with_zero /-! # Topology on `ℝ≥0` The natural topology on `ℝ≥0` (the one induced from `ℝ`), and a basic API. ## Main definitions Instances for the following typeclasses are defined: * `topological_space ℝ≥0` * `topological_semiring ℝ≥0` * `second_countable_topology ℝ≥0` * `order_topology ℝ≥0` * `has_continuous_sub ℝ≥0` * `has_continuous_inv' ℝ≥0` (continuity of `x⁻¹` away from `0`) * `has_continuous_smul ℝ≥0 ℝ` Everything is inherited from the corresponding structures on the reals. ## Main statements Various mathematically trivial lemmas are proved about the compatibility of limits and sums in `ℝ≥0` and `ℝ`. For example * `tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x)` says that the limit of a filter along a map to `ℝ≥0` is the same in `ℝ` and `ℝ≥0`, and * `coe_tsum {f : α → ℝ≥0} : ((∑'a, f a) : ℝ) = (∑'a, (f a : ℝ))` says that says that a sum of elements in `ℝ≥0` is the same in `ℝ` and `ℝ≥0`. Similarly, some mathematically trivial lemmas about infinite sums are proved, a few of which rely on the fact that subtraction is continuous. -/ noncomputable theory open set topological_space metric filter open_locale topological_space namespace nnreal open_locale nnreal big_operators filter instance : topological_space ℝ≥0 := infer_instance -- short-circuit type class inference instance : topological_semiring ℝ≥0 := { continuous_mul := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).mul (continuous_subtype_val.comp continuous_snd), continuous_add := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).add (continuous_subtype_val.comp continuous_snd) } instance : second_countable_topology ℝ≥0 := topological_space.subtype.second_countable_topology _ _ instance : order_topology ℝ≥0 := @order_topology_of_ord_connected _ _ _ _ (Ici 0) _ section coe variable {α : Type*} open filter finset lemma continuous_of_real : continuous real.to_nnreal := continuous_subtype_mk _ $ continuous_id.max continuous_const lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ) := continuous_subtype_val @[simp, norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x) := tendsto_subtype_rng.symm lemma tendsto_coe' {f : filter α} [ne_bot f] {m : α → ℝ≥0} {x : ℝ} : tendsto (λ a, m a : α → ℝ) f (𝓝 x) ↔ ∃ hx : 0 ≤ x, tendsto m f (𝓝 ⟨x, hx⟩) := ⟨λ h, ⟨ge_of_tendsto' h (λ c, (m c).2), tendsto_coe.1 h⟩, λ ⟨hx, hm⟩, tendsto_coe.2 hm⟩ @[simp] lemma map_coe_at_top : map (coe : ℝ≥0 → ℝ) at_top = at_top := map_coe_Ici_at_top 0 lemma comap_coe_at_top : comap (coe : ℝ≥0 → ℝ) at_top = at_top := (at_top_Ici_eq 0).symm @[simp, norm_cast] lemma tendsto_coe_at_top {f : filter α} {m : α → ℝ≥0} : tendsto (λ a, (m a : ℝ)) f at_top ↔ tendsto m f at_top := tendsto_Ici_at_top.symm lemma tendsto_of_real {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (𝓝 x)) : tendsto (λa, real.to_nnreal (m a)) f (𝓝 (real.to_nnreal x)) := (continuous_of_real.tendsto _).comp h lemma nhds_zero : 𝓝 (0 : ℝ≥0) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0)).has_basis (λ a : ℝ≥0, 0 < a) (λ a, Iio a) := nhds_bot_basis instance : has_continuous_sub ℝ≥0 := ⟨continuous_subtype_mk _ $ ((continuous_coe.comp continuous_fst).sub (continuous_coe.comp continuous_snd)).max continuous_const⟩ instance : has_continuous_inv' ℝ≥0 := ⟨λ x hx, tendsto_coe.1 $ (real.tendsto_inv $ nnreal.coe_ne_zero.2 hx).comp continuous_coe.continuous_at⟩ instance : has_continuous_smul ℝ≥0 ℝ := { continuous_smul := continuous.comp real.continuous_mul $ continuous.prod_mk (continuous.comp continuous_subtype_val continuous_fst) continuous_snd } @[norm_cast] lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ)) (r : ℝ) ↔ has_sum f r := by simp only [has_sum, coe_sum.symm, tendsto_coe] lemma has_sum_of_real_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : has_sum (λ n, real.to_nnreal (f n)) (real.to_nnreal (∑' n, f n)) := begin have h_sum : (λ s, ∑ b in s, real.to_nnreal (f b)) = λ s, real.to_nnreal (∑ b in s, f b), from funext (λ _, (real.to_nnreal_sum_of_nonneg (λ n _, hf_nonneg n)).symm), simp_rw [has_sum, h_sum], exact tendsto_of_real hf.has_sum, end @[norm_cast] lemma summable_coe {f : α → ℝ≥0} : summable (λa, (f a : ℝ)) ↔ summable f := begin split, exact assume ⟨a, ha⟩, ⟨⟨a, has_sum_le (λa, (f a).2) has_sum_zero ha⟩, has_sum_coe.1 ha⟩, exact assume ⟨a, ha⟩, ⟨a.1, has_sum_coe.2 ha⟩ end lemma summable_coe_of_nonneg {f : α → ℝ} (hf₁ : ∀ n, 0 ≤ f n) : @summable (ℝ≥0) _ _ _ (λ n, ⟨f n, hf₁ n⟩) ↔ summable f := begin lift f to α → ℝ≥0 using hf₁ with f rfl hf₁, simp only [summable_coe, subtype.coe_eta] end open_locale classical @[norm_cast] lemma coe_tsum {f : α → ℝ≥0} : ↑∑'a, f a = ∑'a, (f a : ℝ) := if hf : summable f then (eq.symm $ (has_sum_coe.2 $ hf.has_sum).tsum_eq) else by simp [tsum, hf, mt summable_coe.1 hf] lemma coe_tsum_of_nonneg {f : α → ℝ} (hf₁ : ∀ n, 0 ≤ f n) : (⟨∑' n, f n, tsum_nonneg hf₁⟩ : ℝ≥0) = (∑' n, ⟨f n, hf₁ n⟩ : ℝ≥0) := begin lift f to α → ℝ≥0 using hf₁ with f rfl hf₁, simp_rw [← nnreal.coe_tsum, subtype.coe_eta] end lemma tsum_mul_left (a : ℝ≥0) (f : α → ℝ≥0) : ∑' x, a * f x = a * ∑' x, f x := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_left] lemma tsum_mul_right (f : α → ℝ≥0) (a : ℝ≥0) : (∑' x, f x * a) = (∑' x, f x) * a := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_right] lemma summable_comp_injective {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : summable (f ∘ i) := nnreal.summable_coe.1 $ show summable ((coe ∘ f) ∘ i), from (nnreal.summable_coe.2 hf).comp_injective hi lemma summable_nat_add (f : ℕ → ℝ≥0) (hf : summable f) (k : ℕ) : summable (λ i, f (i + k)) := summable_comp_injective hf $ add_left_injective k lemma summable_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) : summable (λ i, f (i + k)) ↔ summable f := begin rw [← summable_coe, ← summable_coe], exact @summable_nat_add_iff ℝ _ _ _ (λ i, (f i : ℝ)) k, end lemma has_sum_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) {a : ℝ≥0} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := by simp [← has_sum_coe, coe_sum, nnreal.coe_add, ← has_sum_nat_add_iff k] lemma sum_add_tsum_nat_add {f : ℕ → ℝ≥0} (k : ℕ) (hf : summable f) : ∑' i, f i = (∑ i in range k, f i) + ∑' i, f (i + k) := by rw [←nnreal.coe_eq, coe_tsum, nnreal.coe_add, coe_sum, coe_tsum, sum_add_tsum_nat_add k (nnreal.summable_coe.2 hf)] lemma infi_real_pos_eq_infi_nnreal_pos [complete_lattice α] {f : ℝ → α} : (⨅ (n : ℝ) (h : 0 < n), f n) = (⨅ (n : ℝ≥0) (h : 0 < n), f n) := le_antisymm (infi_le_infi2 $ assume r, ⟨r, infi_le_infi $ assume hr, le_rfl⟩) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, hr.le⟩ $ infi_le _ hr) end coe lemma tendsto_cofinite_zero_of_summable {α} {f : α → ℝ≥0} (hf : summable f) : tendsto f cofinite (𝓝 0) := begin have h_f_coe : f = λ n, real.to_nnreal (f n : ℝ), from funext (λ n, real.to_nnreal_coe.symm), rw [h_f_coe, ← @real.to_nnreal_coe 0], exact tendsto_of_real ((summable_coe.mpr hf).tendsto_cofinite_zero), end lemma tendsto_at_top_zero_of_summable {f : ℕ → ℝ≥0} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_summable hf } end nnreal
ff72e064db46e69cf5631c035b4a30f2f469240f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/list/cycle.lean
452345150bc77014ea78d53076ab354aa559f127
[ "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
24,222
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import data.finset.sort import data.fintype.list /-! # Cycles of a list Lists have an equivalence relation of whether they are rotational permutations of one another. This relation is defined as `is_rotated`. Based on this, we define the quotient of lists by the rotation relation, called `cycle`. We also define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ namespace list variables {α : Type*} [decidable_eq α] /-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/ def next_or : Π (xs : list α) (x default : α), α | [] x default := default | [y] x default := default -- Handles the not-found and the wraparound case | (y :: z :: xs) x default := if x = y then z else next_or (z :: xs) x default @[simp] lemma next_or_nil (x d : α) : next_or [] x d = d := rfl @[simp] lemma next_or_singleton (x y d : α) : next_or [y] x d = d := rfl @[simp] lemma next_or_self_cons_cons (xs : list α) (x y d : α) : next_or (x :: y :: xs) x d = y := if_pos rfl lemma next_or_cons_of_ne (xs : list α) (y x d : α) (h : x ≠ y) : next_or (y :: xs) x d = next_or xs x d := begin cases xs with z zs, { refl }, { exact if_neg h } end /-- `next_or` does not depend on the default value, if the next value appears. -/ lemma next_or_eq_next_or_of_mem_of_ne (xs : list α) (x d d' : α) (x_mem : x ∈ xs) (x_ne : x ≠ xs.last (ne_nil_of_mem x_mem)) : next_or xs x d = next_or xs x d' := begin induction xs with y ys IH, { cases x_mem }, cases ys with z zs, { simp at x_mem x_ne, contradiction }, by_cases h : x = y, { rw [h, next_or_self_cons_cons, next_or_self_cons_cons] }, { rw [next_or, next_or, IH]; simpa [h] using x_mem } end lemma mem_of_next_or_ne {xs : list α} {x d : α} (h : next_or xs x d ≠ d) : x ∈ xs := begin induction xs with y ys IH, { simpa using h }, cases ys with z zs, { simpa using h }, { by_cases hx : x = y, { simp [hx] }, { rw [next_or_cons_of_ne _ _ _ _ hx] at h, simpa [hx] using IH h } } end lemma next_or_concat {xs : list α} {x : α} (d : α) (h : x ∉ xs) : next_or (xs ++ [x]) x d = d := begin induction xs with z zs IH, { simp }, { obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h), rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs] } end lemma next_or_mem {xs : list α} {x d : α} (hd : d ∈ xs) : next_or xs x d ∈ xs := begin revert hd, suffices : ∀ (xs' : list α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs', { exact this xs (λ _, id) }, intros xs' hxs' hd, induction xs with y ys ih, { exact hd }, cases ys with z zs, { exact hd }, rw next_or, split_ifs with h, { exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _)) }, { exact ih (λ _ h, hxs' _ (mem_cons_of_mem _ h)) }, end /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. For example: * `next [1, 2, 3] 2 _ = 3` * `next [1, 2, 3] 3 _ = 1` * `next [1, 2, 3, 2, 4] 2 _ = 3` * `next [1, 2, 3, 2] 2 _ = 3` * `next [1, 1, 2, 3, 2] 1 _ = 1` -/ def next (l : list α) (x : α) (h : x ∈ l) : α := next_or l x (l.nth_le 0 (length_pos_of_mem h)) /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. * `prev [1, 2, 3] 2 _ = 1` * `prev [1, 2, 3] 1 _ = 3` * `prev [1, 2, 3, 2, 4] 2 _ = 1` * `prev [1, 2, 3, 4, 2] 2 _ = 1` * `prev [1, 1, 2] 1 _ = 2` -/ def prev : Π (l : list α) (x : α) (h : x ∈ l), α | [] _ h := by simpa using h | [y] _ _ := y | (y :: z :: xs) x h := if hx : x = y then (last (z :: xs) (cons_ne_nil _ _)) else if x = z then y else prev (z :: xs) x (by simpa [hx] using h) variables (l : list α) (x : α) (h : x ∈ l) @[simp] lemma next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y := rfl @[simp] lemma prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y := rfl lemma next_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : next (y :: z :: l) x h = z := by rw [next, next_or, if_pos hx] @[simp] lemma next_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : next (x :: z :: l) x h = z := next_cons_cons_eq' l x x z h rfl lemma next_ne_head_ne_last (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x ≠ last (y :: l) (cons_ne_nil _ _)) : next (y :: l) x h = next l x (by simpa [hy] using h) := begin rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne], { rwa last_cons at hx }, { simpa [hy] using h } end lemma next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l) (h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) : next (y :: l ++ [x]) x h = y := begin rw [next, next_or_concat], { refl }, { simp [hy, hx] } end lemma next_last_cons (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x = last (y :: l) (cons_ne_nil _ _)) (hl : nodup l) : next (y :: l) x h = y := begin rw [next, nth_le, ←init_append_last (cons_ne_nil y l), hx, next_or_concat], subst hx, intro H, obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H, { simpa [init_eq_take, nth_le_take', hy.symm] using hk' }, suffices : k.succ = l.length, { simpa [this] using hk }, cases l with hd tl, { simpa using hk }, { rw nodup_iff_nth_le_inj at hl, rw [length, nat.succ_inj'], apply hl, simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk' } end lemma prev_last_cons' (y : α) (h : x ∈ (y :: l)) (hx : x = y) : prev (y :: l) x h = last (y :: l) (cons_ne_nil _ _) := begin cases l; simp [prev, hx] end @[simp] lemma prev_last_cons (h : x ∈ (x :: l)) : prev (x :: l) x h = last (x :: l) (cons_ne_nil _ _) := prev_last_cons' l x x h rfl lemma prev_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : prev (y :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx] @[simp] lemma prev_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : prev (x :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := prev_cons_cons_eq' l x x z h rfl lemma prev_cons_cons_of_ne' (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x = z) : prev (y :: z :: l) x h = y := begin cases l, { simp [prev, hy, hz] }, { rw [prev, dif_neg hy, if_pos hz] } end lemma prev_cons_cons_of_ne (y : α) (h : x ∈ (y :: x :: l)) (hy : x ≠ y) : prev (y :: x :: l) x h = y := prev_cons_cons_of_ne' _ _ _ _ _ hy rfl lemma prev_ne_cons_cons (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x ≠ z) : prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := begin cases l, { simpa [hy, hz] using h }, { rw [prev, dif_neg hy, if_neg hz] } end include h lemma next_mem : l.next x h ∈ l := next_or_mem (nth_le_mem _ _ _) lemma prev_mem : l.prev x h ∈ l := begin cases l with hd tl, { simpa using h }, induction tl with hd' tl hl generalizing hd, { simp }, { by_cases hx : x = hd, { simp only [hx, prev_cons_cons_eq], exact mem_cons_of_mem _ (last_mem _) }, { rw [prev, dif_neg hx], split_ifs with hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ (hl _ _) } } } end lemma next_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : next l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + 1) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing x n, { simp }, { cases n, { simp }, { have hn' : n.succ ≤ l.length.succ, { refine nat.succ_le_of_lt _, simpa [nat.succ_lt_succ_iff] using hn }, have hx': (x :: y :: l).nth_le n.succ hn ≠ x, { intro H, suffices : n.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, rcases hn'.eq_or_lt with hn''|hn'', { rw [next_last_cons], { simp [hn''] }, { exact hx' }, { simp [last_eq_nth_le, hn''] }, { exact nodup_of_nodup_cons h } }, { have : n < l.length := by simpa [nat.succ_lt_succ_iff] using hn'' , rw [next_ne_head_ne_last _ _ _ _ hx'], { simp [nat.mod_eq_of_lt (nat.succ_lt_succ (nat.succ_lt_succ this)), hl _ _ (nodup_of_nodup_cons h), nat.mod_eq_of_lt (nat.succ_lt_succ this)] }, { rw last_eq_nth_le, intro H, suffices : n.succ = l.length.succ, { exact absurd hn'' this.ge.not_lt }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn _ _, { simp }, { simpa using H } } } } } end lemma prev_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : prev l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + (l.length - 1)) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing n x, { simp }, { rcases n with _|_|n, { simpa [last_eq_nth_le, nat.mod_eq_of_lt (nat.succ_lt_succ l.length.lt_succ_self)] }, { simp only [mem_cons_iff, nodup_cons] at h, push_neg at h, simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm] }, { rw [prev_ne_cons_cons], { convert hl _ _ (nodup_of_nodup_cons h) _ using 1, have : ∀ k hk, (y :: l).nth_le k hk = (x :: y :: l).nth_le (k + 1) (nat.succ_lt_succ hk), { intros, simpa }, rw [this], congr, simp only [nat.add_succ_sub_one, add_zero, length], simp only [length, nat.succ_lt_succ_iff] at hn, set k := l.length, rw [nat.succ_add, ←nat.add_succ, nat.add_mod_right, nat.succ_add, ←nat.add_succ _ k, nat.add_mod_right, nat.mod_eq_of_lt, nat.mod_eq_of_lt], { exact nat.lt_succ_of_lt hn }, { exact nat.succ_lt_succ (nat.lt_succ_of_lt hn) } }, { intro H, suffices : n.succ.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, { intro H, suffices : n.succ.succ = 1, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn (nat.succ_lt_succ nat.succ_pos') _, simpa using H } } } end lemma pmap_next_eq_rotate_one (h : nodup l) : l.pmap l.next (λ _ h, h) = l.rotate 1 := begin apply list.ext_le, { simp }, { intros, rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h] } end lemma pmap_prev_eq_rotate_length_sub_one (h : nodup l) : l.pmap l.prev (λ _ h, h) = l.rotate (l.length - 1) := begin apply list.ext_le, { simp }, { intros n hn hn', rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h] } end lemma prev_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l (next l x hx) (next_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma next_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l (prev l x hx) (prev_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma prev_reverse_eq_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l.reverse x (mem_reverse.mpr hx) = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, have lpos : 0 < l.length := k.zero_le.trans_lt hk, have key : l.length - 1 - k < l.length := (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos'), rw ←nth_le_pmap l.next (λ _ h, h) (by simpa using hk), simp_rw [←nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h], rw ←nth_le_pmap l.reverse.prev (λ _ h, h), { simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse, length_reverse, nat.mod_eq_of_lt (tsub_lt_self lpos nat.succ_pos'), tsub_tsub_cancel_of_le (nat.succ_le_of_lt lpos)], rw ←nth_le_reverse, { simp [tsub_tsub_cancel_of_le (nat.le_pred_of_lt hk)] }, { simpa using (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos') } }, { simpa using (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos') } end lemma next_reverse_eq_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l.reverse x (mem_reverse.mpr hx) = prev l x hx := begin convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm, exact (reverse_reverse l).symm end lemma is_rotated_next_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.next x hx = l'.next x (h.mem_iff.mp hx) := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, obtain ⟨n, rfl⟩ := id h, rw [next_nth_le _ hn], simp_rw ←nth_le_rotate' _ n k, rw [next_nth_le _ (h.nodup_iff.mp hn), ←nth_le_rotate' _ n], simp [add_assoc] end lemma is_rotated_prev_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.prev x hx = l'.prev x (h.mem_iff.mp hx) := begin rw [←next_reverse_eq_prev _ hn, ←next_reverse_eq_prev _ (h.nodup_iff.mp hn)], exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _ end end list open list /-- `cycle α` is the quotient of `list α` by cyclic permutation. Duplicates are allowed. -/ def cycle (α : Type*) : Type* := quotient (is_rotated.setoid α) namespace cycle variables {α : Type*} instance : has_coe (list α) (cycle α) := ⟨quot.mk _⟩ @[simp] lemma coe_eq_coe {l₁ l₂ : list α} : (l₁ : cycle α) = l₂ ↔ (l₁ ~r l₂) := @quotient.eq _ (is_rotated.setoid _) _ _ @[simp] lemma mk_eq_coe (l : list α) : quot.mk _ l = (l : cycle α) := rfl @[simp] lemma mk'_eq_coe (l : list α) : quotient.mk' l = (l : cycle α) := rfl instance : inhabited (cycle α) := ⟨(([] : list α) : cycle α)⟩ /-- For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/ def mem (a : α) (s : cycle α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.mem_iff) instance : has_mem α (cycle α) := ⟨mem⟩ @[simp] lemma mem_coe_iff {a : α} {l : list α} : a ∈ (l : cycle α) ↔ a ∈ l := iff.rfl instance [decidable_eq α] : decidable_eq (cycle α) := λ s₁ s₂, quotient.rec_on_subsingleton₂' s₁ s₂ (λ l₁ l₂, decidable_of_iff' _ quotient.eq') instance [decidable_eq α] (x : α) (s : cycle α) : decidable (x ∈ s) := quotient.rec_on_subsingleton' s (λ l, list.decidable_mem x l) /-- Reverse a `s : cycle α` by reversing the underlying `list`. -/ def reverse (s : cycle α) : cycle α := quot.map reverse (λ l₁ l₂ (e : l₁ ~r l₂), e.reverse) s @[simp] lemma reverse_coe (l : list α) : (l : cycle α).reverse = l.reverse := rfl @[simp] lemma mem_reverse_iff {a : α} {s : cycle α} : a ∈ s.reverse ↔ a ∈ s := quot.induction_on s (λ _, mem_reverse) @[simp] lemma reverse_reverse (s : cycle α) : s.reverse.reverse = s := quot.induction_on s (λ _, by simp) /-- The length of the `s : cycle α`, which is the number of elements, counting duplicates. -/ def length (s : cycle α) : ℕ := quot.lift_on s length (λ l₁ l₂ (e : l₁ ~r l₂), e.perm.length_eq) @[simp] lemma length_coe (l : list α) : length (l : cycle α) = l.length := rfl @[simp] lemma length_reverse (s : cycle α) : s.reverse.length = s.length := quot.induction_on s length_reverse /-- A `s : cycle α` that is at most one element. -/ def subsingleton (s : cycle α) : Prop := s.length ≤ 1 lemma length_subsingleton_iff {s : cycle α} : subsingleton s ↔ length s ≤ 1 := iff.rfl @[simp] lemma subsingleton_reverse_iff {s : cycle α} : s.reverse.subsingleton ↔ s.subsingleton := by simp [length_subsingleton_iff] lemma subsingleton.congr {s : cycle α} (h : subsingleton s) : ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y := begin induction s using quot.induction_on with l, simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, nat.lt_add_one_iff, length_eq_zero, length_eq_one, nat.not_lt_zero, false_or] at h, rcases h with rfl|⟨z, rfl⟩; simp end /-- A `s : cycle α` that is made up of at least two unique elements. -/ def nontrivial (s : cycle α) : Prop := ∃ (x y : α) (h : x ≠ y), x ∈ s ∧ y ∈ s @[simp] lemma nontrivial_coe_nodup_iff {l : list α} (hl : l.nodup) : nontrivial (l : cycle α) ↔ 2 ≤ l.length := begin rw nontrivial, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simp }, { simp }, { simp only [mem_cons_iff, exists_prop, mem_coe_iff, list.length, ne.def, nat.succ_le_succ_iff, zero_le, iff_true], refine ⟨hd, hd', _, by simp⟩, simp only [not_or_distrib, mem_cons_iff, nodup_cons] at hl, exact hl.left.left } end @[simp] lemma nontrivial_reverse_iff {s : cycle α} : s.reverse.nontrivial ↔ s.nontrivial := by simp [nontrivial] lemma length_nontrivial {s : cycle α} (h : nontrivial s) : 2 ≤ length s := begin obtain ⟨x, y, hxy, hx, hy⟩ := h, induction s using quot.induction_on with l, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simpa using hx }, { simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy, simpa [hx, hy] using hxy }, { simp [bit0] } end /-- The `s : cycle α` contains no duplicates. -/ def nodup (s : cycle α) : Prop := quot.lift_on s nodup (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.nodup_iff) @[simp] lemma nodup_coe_iff {l : list α} : nodup (l : cycle α) ↔ l.nodup := iff.rfl @[simp] lemma nodup_reverse_iff {s : cycle α} : s.reverse.nodup ↔ s.nodup := quot.induction_on s (λ _, nodup_reverse) lemma subsingleton.nodup {s : cycle α} (h : subsingleton s) : nodup s := begin induction s using quot.induction_on with l, cases l with hd tl, { simp }, { have : tl = [] := by simpa [subsingleton, length_eq_zero] using h, simp [this] } end lemma nodup.nontrivial_iff {s : cycle α} (h : nodup s) : nontrivial s ↔ ¬ subsingleton s := begin rw length_subsingleton_iff, induction s using quotient.induction_on', simp only [mk'_eq_coe, nodup_coe_iff] at h, simp [h, nat.succ_le_iff] end /-- The `s : cycle α` as a `multiset α`. -/ def to_multiset (s : cycle α) : multiset α := quotient.lift_on' s (λ l, (l : multiset α)) (λ l₁ l₂ (h : l₁ ~r l₂), multiset.coe_eq_coe.mpr h.perm) /-- The lift of `list.map`. -/ def map {β : Type*} (f : α → β) : cycle α → cycle β := quotient.map' (list.map f) $ λ l₁ l₂ h, h.map _ /-- The `multiset` of lists that can make the cycle. -/ def lists (s : cycle α) : multiset (list α) := quotient.lift_on' s (λ l, (l.cyclic_permutations : multiset (list α))) $ λ l₁ l₂ (h : l₁ ~r l₂), by simpa using h.cyclic_permutations.perm @[simp] lemma mem_lists_iff_coe_eq {s : cycle α} {l : list α} : l ∈ s.lists ↔ (l : cycle α) = s := begin induction s using quotient.induction_on', rw [lists, quotient.lift_on'_mk'], simp end section decidable variable [decidable_eq α] /-- Auxiliary decidability algorithm for lists that contain at least two unique elements. -/ def decidable_nontrivial_coe : Π (l : list α), decidable (nontrivial (l : cycle α)) | [] := is_false (by simp [nontrivial]) | [x] := is_false (by simp [nontrivial]) | (x :: y :: l) := if h : x = y then @decidable_of_iff' _ (nontrivial ((x :: l) : cycle α)) (by simp [h, nontrivial]) (decidable_nontrivial_coe (x :: l)) else is_true ⟨x, y, h, by simp, by simp⟩ instance {s : cycle α} : decidable (nontrivial s) := quot.rec_on_subsingleton s decidable_nontrivial_coe instance {s : cycle α} : decidable (nodup s) := quot.rec_on_subsingleton s (λ (l : list α), list.nodup_decidable l) instance fintype_nodup_cycle [fintype α] : fintype {s : cycle α // s.nodup} := fintype.of_surjective (λ (l : {l : list α // l.nodup}), ⟨l.val, by simpa using l.prop⟩) (λ ⟨s, hs⟩, begin induction s using quotient.induction_on', exact ⟨⟨s, hs⟩, by simp⟩ end) instance fintype_nodup_nontrivial_cycle [fintype α] : fintype {s : cycle α // s.nodup ∧ s.nontrivial} := fintype.subtype (((finset.univ : finset {s : cycle α // s.nodup}).map (function.embedding.subtype _)).filter cycle.nontrivial) (by simp) /-- The `s : cycle α` as a `finset α`. -/ def to_finset (s : cycle α) : finset α := s.to_multiset.to_finset /-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/ def next : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, next l x hx) (λ l₁ l₂ (h : l₁ ~r l₂), function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_next_eq h h₁ _))))) /-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/ def prev : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, prev l x hx) (λ l₁ l₂ (h : l₁ ~r l₂), function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_prev_eq h h₁ _))))) @[simp] lemma prev_reverse_eq_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx := (quotient.induction_on' s prev_reverse_eq_next) hs x hx @[simp] lemma next_reverse_eq_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by simp [←prev_reverse_eq_next] @[simp] lemma next_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs x hx ∈ s := begin induction s using quot.induction_on, exact next_mem _ _ _ end lemma prev_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs x hx ∈ s := by { rw [←next_reverse_eq_prev, ←mem_reverse_iff], exact next_mem _ _ _ _ } @[simp] lemma prev_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x := (quotient.induction_on' s prev_next) hs x hx @[simp] lemma next_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x := (quotient.induction_on' s next_prev) hs x hx end decidable /-- We define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ instance [has_repr α] : has_repr (cycle α) := ⟨λ s, "c[" ++ string.intercalate ", " ((s.map repr).lists.sort (≤)).head ++ "]"⟩ end cycle
413354de2e0c10e1f4cba156f3124d7ade1dcd68
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Logic_and_Proof/Chapter4/4.41.lean
a0035d48f5c426b350dd2414ac3aaed41296e790
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
732
lean
-- 4.40 Forward Reasoning, another example (hence 4.41) -- Traditionally, we can write the following proof as: variables A B C: Prop example: (A → (B → C)) → (A ∧ B → C) := assume h1 : A → (B → C), assume h2 : A ∧ B, show C, from h1 (and.left h2) (and.right h2) -- We can write it with more of a forward-reasoning style as: example: (A → (B → C)) → (A ∧ B → C) := assume h1 : A → (B → C), assume h2 : A ∧ B, have h3: B -> C, from h1 (and.left h2), show C, from h3 (and.right h2) -- Furthermore, consider: example: (A → (B → C)) → (A ∧ B → C) := assume h1 : A → (B → C), assume h2 : A ∧ B, have h3: B, from (and.right h2), have h4: B -> C, from h1 (and.left h2), show C, from h4 h3
4d5844de804140a6ad2f5ac2fcfc4d741543f87c
ad3e8f15221a986da27c99f371922c0b3f5792b6
/src/week05/e00_intro.lean
17cd6cf5274002a35ed23c8c841a6761e0295636
[]
no_license
VArtem/lean-itmo
a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1
dc44cd06f9f5b984d051831b3aaa7364e64c2dc4
refs/heads/main
1,683,761,214,467
1,622,821,295,000
1,622,821,295,000
357,236,048
12
0
null
null
null
null
UTF-8
Lean
false
false
2,607
lean
import data.finset import data.fintype.basic import data.set.finite import tactic.derive_fintype section intro variable {α : Type*} -- Конечность типа или множества представлена в mathlib тремя основными типами: `A : finset α`, `fintype A` и `finite A` -- 1. finset - конструктивно конечное множество -- `finset` = `multiset` + `nodup` -- `multiset` = классы эквивалентности `list` по отношению "a - перестановка b" -- Для того, чтобы применять большинство операций (добавление/объединение/...), нужен инстанс `decidable_eq α`: нужно уметь разрешимо сравнивать элементы (чтобы, например, знать `card`) variable (A : finset α) #check A.card #reduce ({0,1,2,3} : finset ℕ).card #check @finset.card_insert_of_mem -- 2. fintype α - класс, говорящий о том, что α - конечный тип -- fintype α = (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) -- Можно использовать @[derive fintype], для новосозданных `inductive` -- https://github.com/leanprover-community/mathlib/pull/3772 variable [fintype α] example : fintype bool := by show_term {apply_instance} example : fintype (fin 10) := by show_term {apply_instance} #check @finset.univ @[derive fintype] inductive test (α : Type) [fintype α] : Type | c1 : bool → test | c2 : (fin 2) → (fin 3) → test | c3 : α × α → test -- 3. finite B - доказательство конечности множества B -- def finite (s : set α) : Prop := nonempty (fintype s) -- `nonempty (fintype s)` - Prop-версия того, что существует элемент типа `fintype s` -- `fintype s` - то же самое, что `fintype {x : α // x ∈ s}` или `fintype (subtype s)` - подтип `α` состоящий из пар `⟨x, h : x ∈ s⟩` -- Удобно использовать тогда, когда в API `finset` нет того, что хочется делать с множествами, а в `set` есть open set variables (β : Type) (B : set β) (hB : finite B) #check @finite.of_fintype end intro -- Докажем несколько лемм про `finset` namespace finset variables {α : Type} {A B : finset α} [decidable_eq α] lemma card_erase_of_mem' {x} (h : x ∈ A) : (A.erase x).card + 1 = A.card := begin sorry, end end finset
6c61112eba2923fddc29609cf66c29552631fbef
626e312b5c1cb2d88fca108f5933076012633192
/src/measure_theory/measure/outer_measure.lean
35654c23356a40bb139752b4b726557f8278d7b1
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
61,630
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 analysis.specific_limits import measure_theory.pi_system import data.matrix.notation import topology.algebra.infinite_sum /-! # Outer Measures An outer measure is a function `μ : set α → ℝ≥0∞`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ℝ≥0∞` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. We also define this for functions `m` defined on a subset of `set α`, by treating the function as having value `∞` outside its domain. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main definitions and statements * `outer_measure.bounded_by` is the greatest outer measure that is at most the given function. If you know that the given functions sends `∅` to `0`, then `outer_measure.of_function` is a special case. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. * `induced_outer_measure` is the measure induced by a function on a subset of `set α` ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators nnreal topological_space ennreal namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ℝ≥0∞) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ ∑'i, measure_of (s i)) namespace outer_measure section basic variables {α : Type*} {β : Type*} {ms : set (outer_measure α)} {m : outer_measure α} instance : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ @[simp] lemma measure_of_eq_coe (m : outer_measure α) : m.measure_of = m := rfl @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ ∑'i, m (s i) := rel_supr_tsum m m.empty (≤) m.Union_nat s lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma Union_finset (m : outer_measure α) (s : β → set α) (t : finset β) : m (⋃i ∈ t, s i) ≤ ∑ i in t, m (s i) := rel_supr_sum m m.empty (≤) m.Union_nat s t protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := rel_sup_add m m.empty (≤) m.Union_nat s₁ s₂ /-- If `s : ι → set α` is a sequence of sets, `S = ⋃ n, s n`, and `m (S \ s n)` tends to zero along some nontrivial filter (usually `at_top` on `α = ℕ`), then `m S = ⨆ n, m (s n)`. -/ lemma Union_of_tendsto_zero {ι} (m : outer_measure α) {s : ι → set α} (l : filter ι) [ne_bot l] (h0 : tendsto (λ k, m ((⋃ n, s n) \ s k)) l (𝓝 0)) : m (⋃ n, s n) = ⨆ n, m (s n) := begin set S := ⋃ n, s n, set M := ⨆ n, m (s n), have hsS : ∀ {k}, s k ⊆ S, from λ k, subset_Union _ _, refine le_antisymm _ (supr_le $ λ n, m.mono hsS), have A : ∀ k, m S ≤ M + m (S \ s k), from λ k, calc m S = m (s k ∪ S \ s k) : by rw [union_diff_self, union_eq_self_of_subset_left hsS] ... ≤ m (s k) + m (S \ s k) : m.union _ _ ... ≤ M + m (S \ s k) : add_le_add_right (le_supr _ k) _, have B : tendsto (λ k, M + m (S \ s k)) l (𝓝 (M + 0)), from tendsto_const_nhds.add h0, rw add_zero at B, exact ge_of_tendsto' B A end /-- If `s : ℕ → set α` is a monotone sequence of sets such that `∑' k, m (s (k + 1) \ s k) ≠ ∞`, then `m (⋃ n, s n) = ⨆ n, m (s n)`. -/ lemma Union_nat_of_monotone_of_tsum_ne_top (m : outer_measure α) {s : ℕ → set α} (h_mono : ∀ n, s n ⊆ s (n + 1)) (h0 : ∑' k, m (s (k + 1) \ s k) ≠ ∞) : m (⋃ n, s n) = ⨆ n, m (s n) := begin refine m.Union_of_tendsto_zero at_top _, refine tendsto_nhds_bot_mono' (ennreal.tendsto_sum_nat_add _ h0) (λ n, _), refine (m.mono _).trans (m.Union _), /- Current goal: `(⋃ k, s k) \ s n ⊆ ⋃ k, s (k + n + 1) \ s (k + n)` -/ have h' : monotone s := @monotone_nat_of_le_succ (set α) _ _ h_mono, simp only [diff_subset_iff, Union_subset_iff], intros i x hx, rcases nat.find_x ⟨i, hx⟩ with ⟨j, hj, hlt⟩, clear hx i, cases le_or_lt j n with hjn hnj, { exact or.inl (h' hjn hj) }, have : j - (n + 1) + n + 1 = j, by rw [add_assoc, nat.sub_add_cancel hnj], refine or.inr (mem_Union.2 ⟨j - (n + 1), _, hlt _ _⟩), { rwa this }, { rw [← nat.succ_le_iff, nat.succ_eq_add_one, this] } end lemma le_inter_add_diff {m : outer_measure α} {t : set α} (s : set α) : m t ≤ m (t ∩ s) + m (t \ s) := by { convert m.union _ _, rw inter_union_diff t s } lemma diff_null (m : outer_measure α) (s : set α) {t : set α} (ht : m t = 0) : m (s \ t) = m s := begin refine le_antisymm (m.mono $ diff_subset _ _) _, calc m s ≤ m (s ∩ t) + m (s \ t) : le_inter_add_diff _ ... ≤ m t + m (s \ t) : add_le_add_right (m.mono $ inter_subset_right _ _) _ ... = m (s \ t) : by rw [ht, zero_add] end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ lemma coe_fn_injective : injective (λ (μ : outer_measure α) (s : set α), μ s) := λ μ₁ μ₂ h, by { cases μ₁, cases μ₂, congr, exact h } @[ext] lemma ext {μ₁ μ₂ : outer_measure α} (h : ∀ s, μ₁ s = μ₂ s) : μ₁ = μ₂ := coe_fn_injective $ funext h /-- A version of `measure_theory.outer_measure.ext` that assumes `μ₁ s = μ₂ s` on all *nonempty* sets `s`, and gets `μ₁ ∅ = μ₂ ∅` from `measure_theory.outer_measure.empty'`. -/ lemma ext_nonempty {μ₁ μ₂ : outer_measure α} (h : ∀ s : set α, s.nonempty → μ₁ s = μ₂ s) : μ₁ = μ₂ := ext $ λ s, s.eq_empty_or_nonempty.elim (λ he, by rw [he, empty', empty']) (h s) instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem coe_zero : ⇑(0 : outer_measure α) = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem coe_add (m₁ m₂ : outer_measure α) : ⇑(m₁ + m₂) = m₁ + m₂ := rfl theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), .. injective.add_comm_monoid (show outer_measure α → set α → ℝ≥0∞, from coe_fn) coe_fn_injective rfl (λ _ _, rfl) } instance : has_scalar ℝ≥0∞ (outer_measure α) := ⟨λ c m, { measure_of := λ s, c * m s, empty := by simp, mono := λ s t h, ennreal.mul_left_mono $ m.mono h, Union_nat := λ s, by { rw [ennreal.tsum_mul_left], exact ennreal.mul_left_mono (m.Union _) } }⟩ @[simp] lemma coe_smul (c : ℝ≥0∞) (m : outer_measure α) : ⇑(c • m) = c • m := rfl lemma smul_apply (c : ℝ≥0∞) (m : outer_measure α) (s : set α) : (c • m) s = c * m s := rfl instance : module ℝ≥0∞ (outer_measure α) := { smul := (•), .. injective.module ℝ≥0∞ ⟨show outer_measure α → set α → ℝ≥0∞, from coe_fn, coe_zero, coe_add⟩ coe_fn_injective coe_smul } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆ m ∈ ms, (m : outer_measure α) s, empty := nonpos_iff_eq_zero.1 $ bsupr_le $ λ m h, le_of_eq m.empty, mono := assume s₁ s₂ hs, bsupr_le_bsupr $ assume m hm, m.mono hs, Union_nat := assume f, bsupr_le $ assume m hm, calc m (⋃i, f i) ≤ ∑' (i : ℕ), m (f i) : m.Union_nat _ ... ≤ ∑'i, (⨆ m ∈ ms, (m : outer_measure α) (f i)) : ennreal.tsum_le_tsum $ assume i, le_bsupr m hm }⟩ instance : complete_lattice (outer_measure α) := { .. outer_measure.order_bot, .. complete_lattice_of_Sup (outer_measure α) (λ ms, ⟨λ m hm s, le_bsupr m hm, λ m hm s, bsupr_le (λ m' hm', hm hm' s)⟩) } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m ∈ ms, (m : outer_measure α) s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := by rw [supr, Sup_apply, supr_range, supr] @[norm_cast] theorem coe_supr {ι} (f : ι → outer_measure α) : ⇑(⨆ i, f i) = ⨆ i, f i := funext $ λ s, by rw [supr_apply, _root_.supr_apply] @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this theorem smul_supr {ι} (f : ι → outer_measure α) (c : ℝ≥0∞) : c • (⨆ i, f i) = ⨆ i, c • f i := ext $ λ s, by simp only [smul_apply, supr_apply, ennreal.mul_supr] end supremum @[mono] lemma mono'' {m₁ m₂ : outer_measure α} {s₁ s₂ : set α} (hm : m₁ ≤ m₂) (hs : s₁ ⊆ s₂) : m₁ s₁ ≤ m₂ s₂ := (hm s₁).trans (m₂.mono hs) /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) : outer_measure α →ₗ[ℝ≥0∞] outer_measure β := { to_fun := λ m, { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) }, map_add' := λ m₁ m₂, coe_fn_injective rfl, map_smul' := λ c m, coe_fn_injective rfl } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl @[mono] theorem map_mono {β} (f : α → β) : monotone (map f) := λ m m' h s, h _ @[simp] theorem map_sup {β} (f : α → β) (m m' : outer_measure α) : map f (m ⊔ m') = map f m ⊔ map f m' := ext $ λ s, by simp only [map_apply, sup_apply] @[simp] theorem map_supr {β ι} (f : α → β) (m : ι → outer_measure α) : map f (⨆ i, m i) = ⨆ i, map f (m i) := ext $ λ s, by simp only [map_apply, supr_apply] instance : functor outer_measure := {map := λ α β f, map f} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, indicator s (λ _, 1) a, empty := by simp, mono := λ s t h, indicator_le_indicator_of_subset h (λ _, zero_le _) a, Union_nat := λ s, if hs : a ∈ ⋃ n, s n then let ⟨i, hi⟩ := mem_Union.1 hs in calc indicator (⋃ n, s n) (λ _, (1 : ℝ≥0∞)) a = 1 : indicator_of_mem hs _ ... = indicator (s i) (λ _, 1) a : (indicator_of_mem hi _).symm ... ≤ ∑' n, indicator (s n) (λ _, 1) a : ennreal.le_tsum _ else by simp only [indicator_of_not_mem hs, zero_le]} @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = indicator s (λ _, 1) a := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl theorem smul_dirac_apply (a : ℝ≥0∞) (b : α) (s : set α) : (a • dirac b) s = indicator s (λ _, a) b := by simp only [smul_apply, dirac_apply, ← indicator_mul_right _ (λ _, a), mul_one] /-- Pullback of an `outer_measure`: `comap f μ s = μ (f '' s)`. -/ def comap {β} (f : α → β) : outer_measure β →ₗ[ℝ≥0∞] outer_measure α := { to_fun := λ m, { measure_of := λ s, m (f '' s), empty := by simp, mono := λ s t h, m.mono $ image_subset f h, Union_nat := λ s, by { rw [image_Union], apply m.Union_nat } }, map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } @[simp] lemma comap_apply {β} (f : α → β) (m : outer_measure β) (s : set α) : comap f m s = m (f '' s) := rfl @[mono] lemma comap_mono {β} (f : α → β) : monotone (comap f) := λ m m' h s, h _ @[simp] theorem comap_supr {β ι} (f : α → β) (m : ι → outer_measure β) : comap f (⨆ i, m i) = ⨆ i, comap f (m i) := ext $ λ s, by simp only [comap_apply, supr_apply] /-- Restrict an `outer_measure` to a set. -/ def restrict (s : set α) : outer_measure α →ₗ[ℝ≥0∞] outer_measure α := (map coe).comp (comap (coe : s → α)) @[simp] lemma restrict_apply (s t : set α) (m : outer_measure α) : restrict s m t = m (t ∩ s) := by simp [restrict] @[mono] lemma restrict_mono {s t : set α} (h : s ⊆ t) {m m' : outer_measure α} (hm : m ≤ m') : restrict s m ≤ restrict t m' := λ u, by { simp only [restrict_apply], exact (hm _).trans (m'.mono $ inter_subset_inter_right _ h) } @[simp] lemma restrict_univ (m : outer_measure α) : restrict univ m = m := ext $ λ s, by simp @[simp] lemma restrict_empty (m : outer_measure α) : restrict ∅ m = 0 := ext $ λ s, by simp @[simp] lemma restrict_supr {ι} (s : set α) (m : ι → outer_measure α) : restrict s (⨆ i, m i) = ⨆ i, restrict s (m i) := by simp [restrict] lemma map_comap {β} (f : α → β) (m : outer_measure β) : map f (comap f m) = restrict (range f) m := ext $ λ s, congr_arg m $ by simp only [image_preimage_eq_inter_range, subtype.range_coe] lemma map_comap_le {β} (f : α → β) (m : outer_measure β) : map f (comap f m) ≤ m := λ s, m.mono $ image_preimage_subset _ _ lemma restrict_le_self (m : outer_measure α) (s : set α) : restrict s m ≤ m := map_comap_le _ _ @[simp] lemma map_le_restrict_range {β} {ma : outer_measure α} {mb : outer_measure β} {f : α → β} : map f ma ≤ restrict (range f) mb ↔ map f ma ≤ mb := ⟨λ h, h.trans (restrict_le_self _ _), λ h s, by simpa using h (s ∩ range f)⟩ lemma map_comap_of_surjective {β} {f : α → β} (hf : surjective f) (m : outer_measure β) : map f (comap f m) = m := ext $ λ s, by rw [map_apply, comap_apply, hf.image_preimage] lemma le_comap_map {β} (f : α → β) (m : outer_measure α) : m ≤ comap f (map f m) := λ s, m.mono $ subset_preimage_image _ _ lemma comap_map {β} {f : α → β} (hf : injective f) (m : outer_measure α) : comap f (map f m) = m := ext $ λ s, by rw [comap_apply, map_apply, hf.preimage_image] @[simp] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ∞ := let ⟨a, as⟩ := h in top_unique $ le_trans (by simp [smul_dirac_apply, as]) (le_bsupr (∞ • dirac a) trivial) theorem top_apply' (s : set α) : (⊤ : outer_measure α) s = ⨅ (h : s = ∅), 0 := s.eq_empty_or_nonempty.elim (λ h, by simp [h]) (λ h, by simp [h, h.ne_empty]) @[simp] theorem comap_top (f : α → β) : comap f ⊤ = ⊤ := ext_nonempty $ λ s hs, by rw [comap_apply, top_apply hs, top_apply (hs.image _)] theorem map_top (f : α → β) : map f ⊤ = restrict (range f) ⊤ := ext $ λ s, by rw [map_apply, restrict_apply, ← image_preimage_eq_inter_range, top_apply', top_apply', set.image_eq_empty] theorem map_top_of_surjective (f : α → β) (hf : surjective f) : map f ⊤ = ⊤ := by rw [map_top, hf.range_eq, restrict_univ] end basic section of_function set_option eqn_compiler.zeta true variables {α : Type*} (m : set α → ℝ≥0∞) (m_empty : m ∅ = 0) include m_empty /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_pos_le_add $ begin assume ε hε (hb : ∑'i, μ (s i) < ∞), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left (le_of_lt hl) _), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ ∑'i, m (f i) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← equiv.nat_prod_nat_equiv_nat.symm.tsum_eq], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } lemma of_function_apply (s : set α) : outer_measure.of_function m m_empty s = (⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, m (t n)) := rfl variables {m m_empty} theorem of_function_le (s : set α) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.cases_on i s (λ _, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ tsum_eq_single 0 $ by rintro (_|i); simp [f, m_empty] theorem of_function_eq (s : set α) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : outer_measure.of_function m m_empty s = m s := le_antisymm (of_function_le s) $ le_infi $ λ f, le_infi $ λ hf, le_trans (m_mono hf) (m_subadd f) theorem le_of_function {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H s) (of_function_le s), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ lemma is_greatest_of_function : is_greatest {μ : outer_measure α | ∀ s, μ s ≤ m s} (outer_measure.of_function m m_empty) := ⟨λ s, of_function_le _, λ μ, le_of_function.2⟩ lemma of_function_eq_Sup : outer_measure.of_function m m_empty = Sup {μ | ∀ s, μ s ≤ m s} := (@is_greatest_of_function α m m_empty).is_lub.Sup_eq.symm /-- If `m u = ∞` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = measure_theory.outer_measure.of_function m m_empty`. E.g., if `α` is an (e)metric space and `m u = ∞` on any set of diameter `≥ r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma of_function_union_of_top_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → m u = ∞) : outer_measure.of_function m m_empty (s ∪ t) = outer_measure.of_function m m_empty s + outer_measure.of_function m m_empty t := begin refine le_antisymm (outer_measure.union _ _ _) (le_infi $ λ f, le_infi $ λ hf, _), set μ := outer_measure.of_function m m_empty, rcases em (∃ i, (s ∩ f i).nonempty ∧ (t ∩ f i).nonempty) with ⟨i, hs, ht⟩|he, { calc μ s + μ t ≤ ∞ : le_top ... = m (f i) : (h (f i) hs ht).symm ... ≤ ∑' i, m (f i) : ennreal.le_tsum i }, set I := λ s, {i : ℕ | (s ∩ f i).nonempty}, have hd : disjoint (I s) (I t), from λ i hi, he ⟨i, hi⟩, have hI : ∀ u ⊆ s ∪ t, μ u ≤ ∑' i : I u, μ (f i), from λ u hu, calc μ u ≤ μ (⋃ i : I u, f i) : μ.mono (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hf (hu hx)) in mem_Union.2 ⟨⟨i, ⟨x, hx, hi⟩⟩, hi⟩) ... ≤ ∑' i : I u, μ (f i) : μ.Union _, calc μ s + μ t ≤ (∑' i : I s, μ (f i)) + (∑' i : I t, μ (f i)) : add_le_add (hI _ $ subset_union_left _ _) (hI _ $ subset_union_right _ _) ... = ∑' i : I s ∪ I t, μ (f i) : (@tsum_union_disjoint _ _ _ _ _ (λ i, μ (f i)) _ _ _ hd ennreal.summable ennreal.summable).symm ... ≤ ∑' i, μ (f i) : tsum_le_tsum_of_inj coe subtype.coe_injective (λ _ _, zero_le _) (λ _, le_rfl) ennreal.summable ennreal.summable ... ≤ ∑' i, m (f i) : ennreal.tsum_le_tsum (λ i, of_function_le _) end lemma comap_of_function {β} (f : β → α) (h : monotone m ∨ surjective f) : comap f (outer_measure.of_function m m_empty) = outer_measure.of_function (λ s, m (f '' s)) (by rwa set.image_empty) := begin refine le_antisymm (le_of_function.2 $ λ s, _) (λ s, _), { rw comap_apply, apply of_function_le }, { rw [comap_apply, of_function_apply, of_function_apply], refine infi_le_infi2 (λ t, ⟨λ k, f ⁻¹' (t k), _⟩), refine infi_le_infi2 (λ ht, _), rw [set.image_subset_iff, preimage_Union] at ht, refine ⟨ht, ennreal.tsum_le_tsum $ λ n, _⟩, cases h, exacts [h (image_preimage_subset _ _), (congr_arg m (h.image_preimage (t n))).le] } end lemma map_of_function_le {β} (f : α → β) : map f (outer_measure.of_function m m_empty) ≤ outer_measure.of_function (λ s, m (f ⁻¹' s)) m_empty := le_of_function.2 $ λ s, by { rw map_apply, apply of_function_le } lemma map_of_function {β} {f : α → β} (hf : injective f) : map f (outer_measure.of_function m m_empty) = outer_measure.of_function (λ s, m (f ⁻¹' s)) m_empty := begin refine (map_of_function_le _).antisymm (λ s, _), simp only [of_function_apply, map_apply, le_infi_iff], intros t ht, refine infi_le_of_le (λ n, (range f)ᶜ ∪ f '' (t n)) (infi_le_of_le _ _), { rw [← union_Union, ← inter_subset, ← image_preimage_eq_inter_range, ← image_Union], exact image_subset _ ht }, { refine ennreal.tsum_le_tsum (λ n, le_of_eq _), simp [hf.preimage_image] } end lemma restrict_of_function (s : set α) (hm : monotone m) : restrict s (outer_measure.of_function m m_empty) = outer_measure.of_function (λ t, m (t ∩ s)) (by rwa set.empty_inter) := by simp only [restrict, linear_map.comp_apply, comap_of_function _ (or.inl hm), map_of_function subtype.coe_injective, subtype.image_preimage_coe] lemma smul_of_function {c : ℝ≥0∞} (hc : c ≠ ∞) : c • outer_measure.of_function m m_empty = outer_measure.of_function (c • m) (by simp [m_empty]) := begin ext1 s, haveI : nonempty {t : ℕ → set α // s ⊆ ⋃ i, t i} := ⟨⟨λ _, s, subset_Union (λ _, s) 0⟩⟩, simp only [smul_apply, of_function_apply, ennreal.tsum_mul_left, pi.smul_apply, smul_eq_mul, infi_subtype', ennreal.infi_mul_left (λ h, (hc h).elim)], end end of_function section bounded_by variables {α : Type*} (m : set α → ℝ≥0∞) /-- Given any function `m` assigning measures to sets, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. This is the same as `outer_measure.of_function`, except that it doesn't require `m ∅ = 0`. -/ def bounded_by : outer_measure α := outer_measure.of_function (λ s, ⨆ (h : s.nonempty), m s) (by simp [empty_not_nonempty]) variables {m} theorem bounded_by_le (s : set α) : bounded_by m s ≤ m s := (of_function_le _).trans supr_const_le theorem bounded_by_eq_of_function (m_empty : m ∅ = 0) (s : set α) : bounded_by m s = outer_measure.of_function m m_empty s := begin have : (λ s : set α, ⨆ (h : s.nonempty), m s) = m, { ext1 t, cases t.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty, m_empty] }, simp [bounded_by, this] end theorem bounded_by_apply (s : set α) : bounded_by m s = ⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, ⨆ (h : (t n).nonempty), m (t n) := by simp [bounded_by, of_function_apply] theorem bounded_by_eq (s : set α) (m_empty : m ∅ = 0) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ ∑'i, m (s i)) : bounded_by m s = m s := by rw [bounded_by_eq_of_function m_empty, of_function_eq s m_mono m_subadd] theorem le_bounded_by {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s, μ s ≤ m s := begin rw [bounded_by, le_of_function, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty] end theorem le_bounded_by' {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s : set α, s.nonempty → μ s ≤ m s := by { rw [le_bounded_by, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h] } lemma smul_bounded_by {c : ℝ≥0∞} (hc : c ≠ ∞) : c • bounded_by m = bounded_by (c • m) := begin simp only [bounded_by, smul_of_function hc], congr' 1 with s : 1, rcases s.eq_empty_or_nonempty with rfl|hs; simp * end lemma comap_bounded_by {β} (f : β → α) (h : monotone (λ s : {s : set α // s.nonempty}, m s) ∨ surjective f) : comap f (bounded_by m) = bounded_by (λ s, m (f '' s)) := begin refine (comap_of_function _ _).trans _, { refine h.imp (λ H s t hst, supr_le $ λ hs, _) id, have ht : t.nonempty := hs.mono hst, exact (@H ⟨s, hs⟩ ⟨t, ht⟩ hst).trans (le_supr (λ h : t.nonempty, m t) ht) }, { dunfold bounded_by, congr' with s : 1, rw nonempty_image_iff } end /-- If `m u = ∞` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = measure_theory.outer_measure.bounded_by m`. E.g., if `α` is an (e)metric space and `m u = ∞` on any set of diameter `≥ r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma bounded_by_union_of_top_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → m u = ∞) : bounded_by m (s ∪ t) = bounded_by m s + bounded_by m t := of_function_union_of_top_of_nonempty_inter $ λ u hs ht, top_unique $ (h u hs ht).ge.trans $ le_supr (λ h, m u) (hs.mono $ inter_subset_right s u) end bounded_by section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ def is_caratheodory (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) lemma is_caratheodory_iff_le' {s : set α} : is_caratheodory s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ le_inter_add_diff _ @[simp] lemma is_caratheodory_empty : is_caratheodory ∅ := by simp [is_caratheodory, m.empty, diff_empty] lemma is_caratheodory_compl : is_caratheodory s₁ → is_caratheodory s₁ᶜ := by simp [is_caratheodory, diff_eq, add_comm] @[simp] lemma is_caratheodory_compl_iff : is_caratheodory sᶜ ↔ is_caratheodory s := ⟨λ h, by simpa using is_caratheodory_compl m h, is_caratheodory_compl⟩ lemma is_caratheodory_union (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : is_caratheodory s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] lemma is_caratheodory_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, is_caratheodory (s i)) → is_caratheodory (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw bUnion_lt_succ; exact is_caratheodory_union m (is_caratheodory_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) (h n (le_refl (n + 1))) lemma is_caratheodory_inter (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∩ s₂) := by { rw [← is_caratheodory_compl_iff, compl_inter], exact is_caratheodory_union _ (is_caratheodory_compl _ h₁) (is_caratheodory_compl _ h₂) } lemma is_caratheodory_sum {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin rw [bUnion_lt_succ, finset.sum_range_succ, set.union_comm, is_caratheodory_sum, m.measure_inter_union _ (h n), add_comm], intro a, simpa using λ (h₁ : a ∈ s n) i (hi : i < n) h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end lemma is_caratheodory_Union_nat {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : is_caratheodory (⋃i, s i) := is_caratheodory_iff_le'.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, is_caratheodory_sum m h hd] } }, refine le_trans (add_le_add_right hp _) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left _ _) (ge_of_eq (is_caratheodory_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end lemma f_Union {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @is_caratheodory_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ def caratheodory_dynkin : measurable_space.dynkin_system α := { has := is_caratheodory, has_empty := is_caratheodory_empty, has_compl := assume s, is_caratheodory_compl, has_Union_nat := assume f hf hn, is_caratheodory_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, is_caratheodory_inter lemma is_caratheodory_iff {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_iff_le {s : set α} : caratheodory.measurable_set' s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := is_caratheodory_iff_le' protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.measurable_set' (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma of_function_caratheodory {m : set α → ℝ≥0∞} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.measurable_set' s := begin apply (is_caratheodory_iff_le _).mpr, refine λ t, le_infi (λ f, le_infi $ λ hf, _), refine le_trans (add_le_add (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end lemma bounded_by_caratheodory {m : set α → ℝ≥0∞} {s : set α} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (bounded_by m).caratheodory.measurable_set' s := begin apply of_function_caratheodory, intro t, cases t.eq_empty_or_nonempty with h h, { simp [h, empty_not_nonempty] }, { convert le_trans _ (hs t), { simp [h] }, exact add_le_add supr_const_le supr_const_le } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_iff_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.measurable_set_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ℝ≥0∞) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases ht : a ∈ t, swap, by simp [ht], by_cases hs : a ∈ s; simp* end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ℝ≥0∞ := ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s lemma Inf_gen_def (m : set (outer_measure α)) (t : set α) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := rfl lemma Inf_eq_bounded_by_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.bounded_by (Inf_gen m) := begin refine le_antisymm _ _, { refine (le_bounded_by.2 $ λ s, _), refine le_binfi _, intros μ hμ, refine (show Inf m ≤ μ, from Inf_le hμ) s }, { refine le_Inf _, intros μ hμ t, refine le_trans (bounded_by_le t) (binfi_le μ hμ) } end lemma supr_Inf_gen_nonempty {m : set (outer_measure α)} (h : m.nonempty) (t : set α) : (⨆ (h : t.nonempty), Inf_gen m t) = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin rcases t.eq_empty_or_nonempty with rfl|ht, { rcases h with ⟨μ, hμ⟩, rw [eq_false_intro empty_not_nonempty, supr_false, eq_comm], simp_rw [empty'], apply bot_unique, refine infi_le_of_le μ (infi_le _ hμ) }, { simp [ht, Inf_gen_def] } end /-- The value of the Infimum of a nonempty set of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply {m : set (outer_measure α)} {s : set α} (h : m.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := by simp_rw [Inf_eq_bounded_by_Inf_gen, bounded_by_apply, supr_Inf_gen_nonempty h] /-- The value of the Infimum of a set of outer measures on a nonempty set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply' {m : set (outer_measure α)} {s : set α} (h : s.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := m.eq_empty_or_nonempty.elim (λ hm, by simp [hm, h]) Inf_apply /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma infi_apply {ι} [nonempty ι] (m : ι → outer_measure α) (s : set α) : (⨅ i, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i, m i (t n) := by { rw [infi, Inf_apply (range_nonempty m)], simp only [infi_range] } /-- The value of the Infimum of a family of outer measures on a nonempty set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma infi_apply' {ι} (m : ι → outer_measure α) {s : set α} (hs : s.nonempty) : (⨅ i, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i, m i (t n) := by { rw [infi, Inf_apply' hs], simp only [infi_range] } /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma binfi_apply {ι} {I : set ι} (hI : I.nonempty) (m : ι → outer_measure α) (s : set α) : (⨅ i ∈ I, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i ∈ I, m i (t n) := by { haveI := hI.to_subtype, simp only [← infi_subtype'', infi_apply] } /-- The value of the Infimum of a nonempty family of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma binfi_apply' {ι} (I : set ι) (m : ι → outer_measure α) {s : set α} (hs : s.nonempty) : (⨅ i ∈ I, m i) s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ i ∈ I, m i (t n) := by { simp only [← infi_subtype'', infi_apply' _ hs] } lemma map_infi_le {ι β} (f : α → β) (m : ι → outer_measure α) : map f (⨅ i, m i) ≤ ⨅ i, map f (m i) := (map_mono f).map_infi_le lemma comap_infi {ι β} (f : α → β) (m : ι → outer_measure β) : comap f (⨅ i, m i) = ⨅ i, comap f (m i) := begin refine ext_nonempty (λ s hs, _), refine ((comap_mono f).map_infi_le s).antisymm _, simp only [comap_apply, infi_apply' _ hs, infi_apply' _ (hs.image _), le_infi_iff, set.image_subset_iff, preimage_Union], refine λ t ht, infi_le_of_le _ (infi_le_of_le ht $ ennreal.tsum_le_tsum $ λ k, _), exact infi_le_infi (λ i, (m i).mono (image_preimage_subset _ _)) end lemma map_infi {ι β} {f : α → β} (hf : injective f) (m : ι → outer_measure α) : map f (⨅ i, m i) = restrict (range f) (⨅ i, map f (m i)) := begin refine eq.trans _ (map_comap _ _), simp only [comap_infi, comap_map hf] end lemma map_infi_comap {ι β} [nonempty ι] {f : α → β} (m : ι → outer_measure β) : map f (⨅ i, comap f (m i)) = ⨅ i, map f (comap f (m i)) := begin refine (map_infi_le _ _).antisymm (λ s, _), simp only [map_apply, comap_apply, infi_apply, le_infi_iff], refine λ t ht, infi_le_of_le (λ n, f '' (t n) ∪ (range f)ᶜ) (infi_le_of_le _ _), { rw [← Union_union, set.union_comm, ← inter_subset, ← image_Union, ← image_preimage_eq_inter_range], exact image_subset _ ht }, { refine ennreal.tsum_le_tsum (λ n, infi_le_infi (λ i, (m i).mono _)), simp } end lemma map_binfi_comap {ι β} {I : set ι} (hI : I.nonempty) {f : α → β} (m : ι → outer_measure β) : map f (⨅ i ∈ I, comap f (m i)) = ⨅ i ∈ I, map f (comap f (m i)) := by { haveI := hI.to_subtype, rw [← infi_subtype'', ← infi_subtype''], exact map_infi_comap _ } lemma restrict_infi_restrict {ι} (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i, restrict s (m i)) = restrict s (⨅ i, m i) := calc restrict s (⨅ i, restrict s (m i)) = restrict (range (coe : s → α)) (⨅ i, restrict s (m i)) : by rw [subtype.range_coe] ... = map (coe : s → α) (⨅ i, comap coe (m i)) : (map_infi subtype.coe_injective _).symm ... = restrict s (⨅ i, m i) : congr_arg (map coe) (comap_infi _ _).symm lemma restrict_infi {ι} [nonempty ι] (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i, m i) = ⨅ i, restrict s (m i) := (congr_arg (map coe) (comap_infi _ _)).trans (map_infi_comap _) lemma restrict_binfi {ι} {I : set ι} (hI : I.nonempty) (s : set α) (m : ι → outer_measure α) : restrict s (⨅ i ∈ I, m i) = ⨅ i ∈ I, restrict s (m i) := by { haveI := hI.to_subtype, rw [← infi_subtype'', ← infi_subtype''], exact restrict_infi _ _ } /-- This proves that Inf and restrict commute for outer measures, so long as the set of outer measures is nonempty. -/ lemma restrict_Inf_eq_Inf_restrict (m : set (outer_measure α)) {s : set α} (hm : m.nonempty) : restrict s (Inf m) = Inf ((restrict s) '' m) := by simp only [Inf_eq_infi, restrict_binfi, hm, infi_image] end Inf_gen end outer_measure open outer_measure /-! ### Induced Outer Measure We can extend a function defined on a subset of `set α` to an outer measure. The underlying function is called `extend`, and the measure it induces is called `induced_outer_measure`. Some lemmas below are proven twice, once in the general case, and one where the function `m` is only defined on measurable sets (i.e. when `P = measurable_set`). In the latter cases, we can remove some hypotheses in the statement. The general version has the same name, but with a prime at the end. -/ section extend variables {α : Type*} {P : α → Prop} variables (m : Π (s : α), P s → ℝ≥0∞) /-- We can trivially extend a function defined on a subclass of objects (with codomain `ℝ≥0∞`) to all objects by defining it to be `∞` on the objects not in the class. -/ def extend (s : α) : ℝ≥0∞ := ⨅ h : P s, m s h lemma extend_eq {s : α} (h : P s) : extend m s = m s h := by simp [extend, h] lemma extend_eq_top {s : α} (h : ¬P s) : extend m s = ∞ := by simp [extend, h] lemma le_extend {s : α} (h : P s) : m s h ≤ extend m s := by { simp only [extend, le_infi_iff], intro, refl' } -- TODO: why this is a bad `congr` lemma? lemma extend_congr {β : Type*} {Pb : β → Prop} {mb : Π s : β, Pb s → ℝ≥0∞} {sa : α} {sb : β} (hP : P sa ↔ Pb sb) (hm : ∀ (ha : P sa) (hb : Pb sb), m sa ha = mb sb hb) : extend m sa = extend mb sb := infi_congr_Prop hP (λ h, hm _ _) end extend section extend_set variables {α : Type*} {P : set α → Prop} variables {m : Π (s : set α), P s → ℝ≥0∞} variables (P0 : P ∅) (m0 : m ∅ P0 = 0) variables (PU : ∀{{f : ℕ → set α}} (hm : ∀i, P (f i)), P (⋃i, f i)) variables (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), pairwise (disjoint on f) → m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) variables (msU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), m (⋃i, f i) (PU hm) ≤ ∑'i, m (f i) (hm i)) variables (m_mono : ∀⦃s₁ s₂ : set α⦄ (hs₁ : P s₁) (hs₂ : P s₂), s₁ ⊆ s₂ → m s₁ hs₁ ≤ m s₂ hs₂) lemma extend_empty : extend m ∅ = 0 := (extend_eq _ P0).trans m0 lemma extend_Union_nat {f : ℕ → set α} (hm : ∀i, P (f i)) (mU : m (⋃i, f i) (PU hm) = ∑'i, m (f i) (hm i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := (extend_eq _ _).trans $ mU.trans $ by { congr' with i, rw extend_eq } section subadditive include PU msU lemma extend_Union_le_tsum_nat' (s : ℕ → set α) : extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin by_cases h : ∀i, P (s i), { rw [extend_eq _ (PU h), congr_arg tsum _], { apply msU h }, funext i, apply extend_eq _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end end subadditive section mono include m_mono lemma extend_mono' ⦃s₁ s₂ : set α⦄ (h₁ : P s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := by { refine le_infi _, intro h₂, rw [extend_eq m h₁], exact m_mono h₁ h₂ hs } end mono section unions include P0 m0 PU mU lemma extend_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, P (f i)) : extend m (⋃i, f i) = ∑'i, extend m (f i) := begin rw [← encodable.Union_decode₂, ← tsum_Union_decode₂], { exact extend_Union_nat PU (λ n, encodable.Union_decode₂_cases P0 hm) (mU _ (encodable.Union_decode₂_disjoint_on hd)) }, { exact extend_empty P0 m0 } end lemma extend_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : P s₁) (h₂ : P s₂) : extend m (s₁ ∪ s₂) = extend m s₁ + extend m s₂ := begin rw [union_eq_Union, extend_Union P0 m0 PU mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], simp end end unions variable (m) /-- Given an arbitrary function on a subset of sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on the domain of `m`). -/ def induced_outer_measure : outer_measure α := outer_measure.of_function (extend m) (extend_empty P0 m0) variables {m P0 m0} lemma le_induced_outer_measure {μ : outer_measure α} : μ ≤ induced_outer_measure m P0 m0 ↔ ∀ s (hs : P s), μ s ≤ m s hs := le_of_function.trans $ forall_congr $ λ s, le_infi_iff /-- If `P u` is `false` for any set `u` that has nonempty intersection both with `s` and `t`, then `μ (s ∪ t) = μ s + μ t`, where `μ = induced_outer_measure m P0 m0`. E.g., if `α` is an (e)metric space and `P u = diam u < r`, then this lemma implies that `μ (s ∪ t) = μ s + μ t` on any two sets such that `r ≤ edist x y` for all `x ∈ s` and `y ∈ t`. -/ lemma induced_outer_measure_union_of_false_of_nonempty_inter {s t : set α} (h : ∀ u, (s ∩ u).nonempty → (t ∩ u).nonempty → ¬P u) : induced_outer_measure m P0 m0 (s ∪ t) = induced_outer_measure m P0 m0 s + induced_outer_measure m P0 m0 t := of_function_union_of_top_of_nonempty_inter $ λ u hsu htu, @infi_of_empty _ _ _ ⟨h u hsu htu⟩ _ include msU m_mono lemma induced_outer_measure_eq_extend' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = extend m s := of_function_eq s (λ t, extend_mono' m_mono hs) (extend_Union_le_tsum_nat' PU msU) lemma induced_outer_measure_eq' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = m s hs := (induced_outer_measure_eq_extend' PU msU m_mono hs).trans $ extend_eq _ _ lemma induced_outer_measure_eq_infi (s : set α) : induced_outer_measure m P0 m0 s = ⨅ (t : set α) (ht : P t) (h : s ⊆ t), m t ht := begin apply le_antisymm, { simp only [le_infi_iff], intros t ht, simp only [le_infi_iff], intro hs, refine le_trans (mono' _ hs) _, exact le_of_eq (induced_outer_measure_eq' _ msU m_mono _) }, { refine le_infi _, intro f, refine le_infi _, intro hf, refine le_trans _ (extend_Union_le_tsum_nat' _ msU _), refine le_infi _, intro h2f, refine infi_le_of_le _ (infi_le_of_le h2f $ infi_le _ hf) } end lemma induced_outer_measure_preimage (f : α ≃ α) (Pm : ∀ (s : set α), P (f ⁻¹' s) ↔ P s) (mm : ∀ (s : set α) (hs : P s), m (f ⁻¹' s) ((Pm _).mpr hs) = m s hs) {A : set α} : induced_outer_measure m P0 m0 (f ⁻¹' A) = induced_outer_measure m P0 m0 A := begin simp only [induced_outer_measure_eq_infi _ msU m_mono], symmetry, refine infi_congr (preimage f) f.injective.preimage_surjective _, intro s, refine infi_congr_Prop (Pm s) _, intro hs, refine infi_congr_Prop f.surjective.preimage_subset_preimage_iff _, intro h2s, exact mm s hs end lemma induced_outer_measure_exists_set {s : set α} (hs : induced_outer_measure m P0 m0 s < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ (t : set α) (ht : P t), s ⊆ t ∧ induced_outer_measure m P0 m0 t ≤ induced_outer_measure m P0 m0 s + ε := begin have := ennreal.lt_add_right hs (ennreal.zero_lt_coe_iff.2 hε), conv at this {to_lhs, rw induced_outer_measure_eq_infi _ msU m_mono }, simp only [infi_lt_iff] at this, rcases this with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, h2t, le_trans (le_of_eq $ induced_outer_measure_eq' _ msU m_mono h1t) (le_of_lt h3t)⟩ end /-- To test whether `s` is Carathéodory-measurable we only need to check the sets `t` for which `P t` holds. See `of_function_caratheodory` for another way to show the Carathéodory-measurability of `s`. -/ lemma induced_outer_measure_caratheodory (s : set α) : (induced_outer_measure m P0 m0).caratheodory.measurable_set' s ↔ ∀ (t : set α), P t → induced_outer_measure m P0 m0 (t ∩ s) + induced_outer_measure m P0 m0 (t \ s) ≤ induced_outer_measure m P0 m0 t := begin rw is_caratheodory_iff_le, split, { intros h t ht, exact h t }, { intros h u, conv_rhs { rw induced_outer_measure_eq_infi _ msU m_mono }, refine le_infi _, intro t, refine le_infi _, intro ht, refine le_infi _, intro h2t, refine le_trans _ (le_trans (h t ht) $ le_of_eq $ induced_outer_measure_eq' _ msU m_mono ht), refine add_le_add (mono' _ $ set.inter_subset_inter_left _ h2t) (mono' _ $ diff_subset_diff_left h2t) } end end extend_set /-! If `P` is `measurable_set` for some measurable space, then we can remove some hypotheses of the above lemmas. -/ section measurable_space variables {α : Type*} [measurable_space α] variables {m : Π (s : set α), measurable_set s → ℝ≥0∞} variables (m0 : m ∅ measurable_set.empty = 0) variable (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, measurable_set (f i)), pairwise (disjoint on f) → m (⋃i, f i) (measurable_set.Union hm) = ∑'i, m (f i) (hm i)) include m0 mU lemma extend_mono {s₁ s₂ : set α} (h₁ : measurable_set s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := begin refine le_infi _, intro h₂, have := extend_union measurable_set.empty m0 measurable_set.Union mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← extend_eq m, exact le_iff_exists_add.2 ⟨_, this⟩, end lemma extend_Union_le_tsum_nat : ∀ (s : ℕ → set α), extend m (⋃i, s i) ≤ ∑'i, extend m (s i) := begin refine extend_Union_le_tsum_nat' measurable_set.Union _, intros f h, simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (measurable_set.disjointed h) (disjoint_disjointed _)], refine ennreal.tsum_le_tsum (λ i, _), rw [← extend_eq m, ← extend_eq m], exact extend_mono m0 mU (measurable_set.disjointed h _) (disjointed_le f _), end lemma induced_outer_measure_eq_extend {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = extend m s := of_function_eq s (λ t, extend_mono m0 mU hs) (extend_Union_le_tsum_nat m0 mU) lemma induced_outer_measure_eq {s : set α} (hs : measurable_set s) : induced_outer_measure m measurable_set.empty m0 s = m s hs := (induced_outer_measure_eq_extend m0 mU hs).trans $ extend_eq _ _ end measurable_space namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := induced_outer_measure (λ s _, m s) measurable_set.empty m.empty theorem le_trim : m ≤ m.trim := le_of_function.mpr $ λ s, le_infi $ λ _, le_refl _ theorem trim_eq {s : set α} (hs : measurable_set s) : m.trim s = m s := induced_outer_measure_eq' measurable_set.Union (λ f hf, m.Union_nat f) (λ _ _ _ _ h, m.mono h) hs theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, measurable_set s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by { unfold trim, congr, funext s hs, exact H hs } @[mono] theorem trim_mono : monotone (trim : outer_measure α → outer_measure α) := λ m₁ m₂ H s, binfi_le_binfi $ λ f hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, measurable_set s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_le_trim_iff {m₁ m₂ : outer_measure α} : m₁.trim ≤ m₂.trim ↔ ∀ s, measurable_set s → m₁ s ≤ m₂ s := le_trim_iff.trans $ forall_congr $ λ s, forall_congr $ λ hs, by rw [trim_eq _ hs] theorem trim_eq_trim_iff {m₁ m₂ : outer_measure α} : m₁.trim = m₂.trim ↔ ∀ s, measurable_set s → m₁ s = m₂ s := by simp only [le_antisymm_iff, trim_le_trim_iff, forall_and_distrib] theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : measurable_set t), m t := by { simp only [infi_comm] {single_pass := tt}, exact induced_outer_measure_eq_infi measurable_set.Union (λ f _, m.Union_nat f) (λ _ _ _ _ h, m.mono h) s } theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ measurable_set t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := trim_eq_trim_iff.2 $ λ s, m.trim_eq @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ measurable_set.univ) (zero_le _) theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_measurable_superset_eq_trim (m : outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ m t = m.trim s := begin simp only [trim_eq_infi], set ms := ⨅ (t : set α) (st : s ⊆ t) (ht : measurable_set t), m t, by_cases hs : ms = ∞, { simp only [hs], simp only [infi_eq_top] at hs, exact ⟨univ, subset_univ s, measurable_set.univ, hs _ (subset_univ s) measurable_set.univ⟩ }, { have : ∀ r > ms, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < r, { intros r hs, simpa [infi_lt_iff] using hs }, have : ∀ n : ℕ, ∃ t, s ⊆ t ∧ measurable_set t ∧ m t < ms + n⁻¹, { assume n, refine this _ (ennreal.lt_add_right (lt_top_iff_ne_top.2 hs) _), exact (ennreal.inv_pos.2 $ ennreal.nat_ne_top _) }, choose t hsub hm hm', refine ⟨⋂ n, t n, subset_Inter hsub, measurable_set.Inter hm, _⟩, have : tendsto (λ n : ℕ, ms + n⁻¹) at_top (𝓝 (ms + 0)), from tendsto_const_nhds.add ennreal.tendsto_inv_nat_nhds_zero, rw add_zero at this, refine le_antisymm (ge_of_tendsto' this $ λ n, _) _, { exact le_trans (m.mono' $ Inter_subset t n) (hm' n).le }, { refine infi_le_of_le (⋂ n, t n) _, refine infi_le_of_le (subset_Inter hsub) _, refine infi_le _ (measurable_set.Inter hm) } } end lemma exists_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ measurable_set t ∧ m t = 0 := begin rcases exists_measurable_superset_eq_trim m s with ⟨t, hst, ht, hm⟩, exact ⟨t, hst, ht, h ▸ hm⟩ end /-- If `μ i` is a countable family of outer measures, then for every set `s` there exists a measurable set `t ⊇ s` such that `μ i t = (μ i).trim s` for all `i`. -/ lemma exists_measurable_superset_forall_eq_trim {ι} [encodable ι] (μ : ι → outer_measure α) (s : set α) : ∃ t, s ⊆ t ∧ measurable_set t ∧ ∀ i, μ i t = (μ i).trim s := begin choose t hst ht hμt using λ i, (μ i).exists_measurable_superset_eq_trim s, replace hst := subset_Inter hst, replace ht := measurable_set.Inter ht, refine ⟨⋂ i, t i, hst, ht, λ i, le_antisymm _ _⟩, exacts [hμt i ▸ (μ i).mono (Inter_subset _ _), (mono' _ hst).trans_eq ((μ i).trim_eq ht)] end /-- If `m₁ s = op (m₂ s) (m₃ s)` for all `s`, then the same is true for `m₁.trim`, `m₂.trim`, and `m₃ s`. -/ theorem trim_binop {m₁ m₂ m₃ : outer_measure α} {op : ℝ≥0∞ → ℝ≥0∞ → ℝ≥0∞} (h : ∀ s, m₁ s = op (m₂ s) (m₃ s)) (s : set α) : m₁.trim s = op (m₂.trim s) (m₃.trim s) := begin rcases exists_measurable_superset_forall_eq_trim (![m₁, m₂, m₃]) s with ⟨t, hst, ht, htm⟩, simp only [fin.forall_fin_succ, matrix.cons_val_zero, matrix.cons_val_succ] at htm, rw [← htm.1, ← htm.2.1, ← htm.2.2.1, h] end /-- If `m₁ s = op (m₂ s)` for all `s`, then the same is true for `m₁.trim` and `m₂.trim`. -/ theorem trim_op {m₁ m₂ : outer_measure α} {op : ℝ≥0∞ → ℝ≥0∞} (h : ∀ s, m₁ s = op (m₂ s)) (s : set α) : m₁.trim s = op (m₂.trim s) := @trim_binop α _ m₁ m₂ 0 (λ a b, op a) h s /-- `trim` is additive. -/ theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := ext $ trim_binop (add_apply m₁ m₂) /-- `trim` respects scalar multiplication. -/ theorem trim_smul (c : ℝ≥0∞) (m : outer_measure α) : (c • m).trim = c • m.trim := ext $ trim_op (smul_apply c m) /-- `trim` sends the supremum of two outer measures to the supremum of the trimmed measures. -/ theorem trim_sup (m₁ m₂ : outer_measure α) : (m₁ ⊔ m₂).trim = m₁.trim ⊔ m₂.trim := ext $ λ s, (trim_binop (sup_apply m₁ m₂) s).trans (sup_apply _ _ _).symm /-- `trim` sends the supremum of a countable family of outer measures to the supremum of the trimmed measures. -/ lemma trim_supr {ι} [encodable ι] (μ : ι → outer_measure α) : trim (⨆ i, μ i) = ⨆ i, trim (μ i) := begin ext1 s, rcases exists_measurable_superset_forall_eq_trim (λ o, option.elim o (supr μ) μ) s with ⟨t, hst, ht, hμt⟩, simp only [option.forall, option.elim] at hμt, simp only [supr_apply, ← hμt.1, ← hμt.2] end /-- The trimmed property of a measure μ states that `μ.to_outer_measure.trim = μ.to_outer_measure`. This theorem shows that a restricted trimmed outer measure is a trimmed outer measure. -/ lemma restrict_trim {μ : outer_measure α} {s : set α} (hs : measurable_set s) : (restrict s μ).trim = restrict s μ.trim := begin refine le_antisymm (λ t, _) (le_trim_iff.2 $ λ t ht, _), { rw restrict_apply, rcases μ.exists_measurable_superset_eq_trim (t ∩ s) with ⟨t', htt', ht', hμt'⟩, rw [← hμt'], rw inter_subset at htt', refine (mono' _ htt').trans _, rw [trim_eq _ (hs.compl.union ht'), restrict_apply, union_inter_distrib_right, compl_inter_self, set.empty_union], exact μ.mono' (inter_subset_left _ _) }, { rw [restrict_apply, trim_eq _ (ht.inter hs), restrict_apply], exact le_rfl } end end outer_measure end measure_theory
413d80fe909d5d80622dde49c3bf1442a4249263
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/hott/bug_struct_level.hlean
3cf440d69697fddf5965ff8ecbbfbbdb77c19a3c
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,190
hlean
import algebra.precategory.basic open category section parameter {D₀ : Type} parameter (C : precategory D₀) parameter (D₂ : Π ⦃a b c d : D₀⦄ (f : hom a b) (g : hom c d) (h : hom a c) (i : hom b d), Type) attribute comp [reducible] definition comp₁_type [reducible] : Type := Π ⦃a b c₁ d₁ c₂ d₂ : D₀⦄ ⦃f₁ : hom a b⦄ ⦃g₁ : hom c₁ d₁⦄ ⦃h₁ : hom a c₁⦄ ⦃i₁ : hom b d₁⦄ ⦃g₂ : hom c₂ d₂⦄ ⦃h₂ : hom c₁ c₂⦄ ⦃i₂ : hom d₁ d₂⦄, (D₂ g₁ g₂ h₂ i₂) → (D₂ f₁ g₁ h₁ i₁) → (@D₂ a b c₂ d₂ f₁ g₂ (h₂ ∘ h₁) (i₂ ∘ i₁)) definition ID₁_type [reducible] : Type := Π ⦃a b : D₀⦄ (f : hom a b), D₂ f f (ID a) (ID b) structure worm_precat [class] : Type := (comp₁ : comp₁_type) (ID₁ : ID₁_type) end section parameter {D₀ : Type} parameter [C : precategory D₀] parameter {D₂ : Π ⦃a b c d : D₀⦄ (f : hom a b) (g : hom c d) (h : hom a c) (i : hom b d), Type} parameter [D : worm_precat C D₂] include D structure two_cell_ob : Type := (vo1 : D₀) (vo2 : D₀) (vo3 : hom vo1 vo2) end
b304804d9281338c15ea0536240489ade9adfcd6
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/IRbug.lean
8adc37f9fe483e96eaefdfa0bdf1df6c359184f4
[ "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
706
lean
new_frontend namespace Repro def FooM (α : Type) : Type := Unit → α def FooM.run {α : Type} (ψ : FooM α) (x : Unit) : α := ψ x def bind {α β : Type} : ∀ (ψ₁ : FooM α) (ψ₂ : α → FooM β), FooM β | ψ₁, ψ₂ => λ _ => ψ₂ (ψ₁.run ()) () instance : HasPure FooM := ⟨λ x => λ _ => x⟩ instance : HasBind FooM := ⟨@bind⟩ instance : Monad FooM := {} def unexpectedBehavior : FooM String := do let b : Bool := (#[] : Array Nat).isEmpty; let trueBranch ← pure "trueBranch"; let falseBranch ← pure "falseBranch"; (1 : Nat).foldM (λ _ (s : String) => do let s ← pure $ if b then trueBranch else falseBranch; pure s) "" #eval unexpectedBehavior () end Repro
57f9e9b5f1ee59062dfb8f9c072991991df2c366
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/big_operators/nat_antidiagonal.lean
cb274d2f3fc6397ddfa35e5b9acf60dfd81da62b
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,056
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.finset.nat_antidiagonal import algebra.big_operators.basic /-! # Big operators for `nat_antidiagonal` This file contains theorems relevant to big operators over `finset.nat.antidiagonal`. -/ open_locale big_operators variables {M N : Type*} [comm_monoid M] [add_comm_monoid N] namespace finset namespace nat lemma prod_antidiagonal_succ {n : ℕ} {f : ℕ × ℕ → M} : ∏ p in antidiagonal (n + 1), f p = f (0, n + 1) * ∏ p in antidiagonal n, f (p.1 + 1, p.2) := begin rw [antidiagonal_succ, prod_insert, prod_map], refl, intro con, rcases mem_map.1 con with ⟨⟨a,b⟩, ⟨h1, h2⟩⟩, simp only [prod.mk.inj_iff, function.embedding.coe_prod_map, prod.map_mk] at h2, apply nat.succ_ne_zero a h2.1, end lemma sum_antidiagonal_succ {n : ℕ} {f : ℕ × ℕ → N} : ∑ p in antidiagonal (n + 1), f p = f (0, n + 1) + ∑ p in antidiagonal n, f (p.1 + 1, p.2) := @prod_antidiagonal_succ (multiplicative N) _ _ _ @[to_additive] lemma prod_antidiagonal_swap {n : ℕ} {f : ℕ × ℕ → M} : ∏ p in antidiagonal n, f p.swap = ∏ p in antidiagonal n, f p := by { nth_rewrite 1 ← map_swap_antidiagonal, rw [prod_map], refl } lemma prod_antidiagonal_succ' {n : ℕ} {f : ℕ × ℕ → M} : ∏ p in antidiagonal (n + 1), f p = f (n + 1, 0) * ∏ p in antidiagonal n, f (p.1, p.2 + 1) := begin rw [← prod_antidiagonal_swap, prod_antidiagonal_succ, ← prod_antidiagonal_swap], refl end lemma sum_antidiagonal_succ' {n : ℕ} {f : ℕ × ℕ → N} : ∑ p in antidiagonal (n + 1), f p = f (n + 1, 0) + ∑ p in antidiagonal n, f (p.1, p.2 + 1) := @prod_antidiagonal_succ' (multiplicative N) _ _ _ @[to_additive] lemma prod_antidiagonal_subst {n : ℕ} {f : ℕ × ℕ → ℕ → M} : ∏ p in antidiagonal n, f p n = ∏ p in antidiagonal n, f p (p.1 + p.2) := prod_congr rfl $ λ p hp, by rw [nat.mem_antidiagonal.1 hp] end nat end finset