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
a1842e1eaa4279b5d389e159b7c87a2f7d809553
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/binsearch.lean
f15e091f3be0d47f4dd46371b4139a749e880459
[ "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
439
lean
def mkAssocArray : Nat → Array (Nat × Bool) → Array (Nat × Bool) | 0, as => as | i+1, as => mkAssocArray i (as.push (i, i % 2 == 0)) def tst (n : Nat) : IO Unit := do let as := mkAssocArray n Array.empty; IO.println as; let as := as.qsort (fun a b => a.1 < b.1); (2*n).forM $ fun i => do let entry := as.binSearch (i, false) (fun a b => a.1 < b.1); IO.println (">> " ++ toString i ++ " ==> " ++ toString entry) #eval tst 10
e97e0199d29e8aed7dc653ef9e7c8fc7eb67e9da
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/group/fundamental_domain.lean
5c6d9641c328de51da577380389bab4201d23ab4
[ "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
17,351
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.group.action import measure_theory.group.pointwise import measure_theory.integral.set_integral /-! # Fundamental domain of a group action A set `s` is said to be a *fundamental domain* of an action of a group `G` on a measurable space `α` with respect to a measure `μ` if * `s` is a measurable set; * the sets `g • s` over all `g : G` cover almost all points of the whole space; * the sets `g • s`, are pairwise a.e. disjoint, i.e., `μ (g₁ • s ∩ g₂ • s) = 0` whenever `g₁ ≠ g₂`; we require this for `g₂ = 1` in the definition, then deduce it for any two `g₁ ≠ g₂`. In this file we prove that in case of a countable group `G` and a measure preserving action, any two fundamental domains have the same measure, and for a `G`-invariant function, its integrals over any two fundamental domains are equal to each other. We also generate additive versions of all theorems in this file using the `to_additive` attribute. -/ open_locale ennreal pointwise topological_space nnreal ennreal measure_theory open measure_theory measure_theory.measure set function topological_space filter namespace measure_theory /-- A measurable set `s` is a *fundamental domain* for an additive action of an additive group `G` on a measurable space `α` with respect to a measure `α` if the sets `g +ᵥ s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj] structure is_add_fundamental_domain (G : Type*) {α : Type*} [has_zero G] [has_vadd G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g +ᵥ x ∈ s) (ae_disjoint : ∀ g ≠ (0 : G), ae_disjoint μ (g +ᵥ s) s) /-- A measurable set `s` is a *fundamental domain* for an action of a group `G` on a measurable space `α` with respect to a measure `α` if the sets `g • s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj, to_additive is_add_fundamental_domain] structure is_fundamental_domain (G : Type*) {α : Type*} [has_one G] [has_smul G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g • x ∈ s) (ae_disjoint : ∀ g ≠ (1 : G), ae_disjoint μ (g • s) s) namespace is_fundamental_domain variables {G α E : Type*} [group G] [mul_action G α] [measurable_space α] [normed_group E] {s t : set α} {μ : measure α} /-- If for each `x : α`, exactly one of `g • x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the action of `G` on `α`. -/ @[to_additive "If for each `x : α`, exactly one of `g +ᵥ x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the additive action of `G` on `α`."] lemma mk' (h_meas : null_measurable_set s μ) (h_exists : ∀ x : α, ∃! g : G, g • x ∈ s) : is_fundamental_domain G s μ := { null_measurable_set := h_meas, ae_covers := eventually_of_forall $ λ x, (h_exists x).exists, ae_disjoint := λ g hne, disjoint.ae_disjoint $ disjoint_left.2 begin rintro _ ⟨x, hx, rfl⟩ hgx, rw ← one_smul G x at hx, exact hne ((h_exists x).unique hgx hx) end } @[to_additive] lemma Union_smul_ae_eq (h : is_fundamental_domain G s μ) : (⋃ g : G, g • s) =ᵐ[μ] univ := eventually_eq_univ.2 $ h.ae_covers.mono $ λ x ⟨g, hg⟩, mem_Union.2 ⟨g⁻¹, _, hg, inv_smul_smul _ _⟩ @[to_additive] lemma mono (h : is_fundamental_domain G s μ) {ν : measure α} (hle : ν ≪ μ) : is_fundamental_domain G s ν := ⟨h.1.mono_ac hle, hle h.2, λ g hg, hle (h.3 g hg)⟩ variables [measurable_space G] [has_measurable_smul G α] [smul_invariant_measure G α μ] @[to_additive] lemma null_measurable_set_smul (h : is_fundamental_domain G s μ) (g : G) : null_measurable_set (g • s) μ := h.null_measurable_set.smul g @[to_additive] lemma restrict_restrict (h : is_fundamental_domain G s μ) (g : G) (t : set α) : (μ.restrict t).restrict (g • s) = μ.restrict (g • s ∩ t) := restrict_restrict₀ ((h.null_measurable_set_smul g).mono restrict_le_self) @[to_additive] lemma pairwise_ae_disjoint (h : is_fundamental_domain G s μ) : pairwise (λ g₁ g₂ : G, ae_disjoint μ (g₁ • s) (g₂ • s)) := λ g₁ g₂ hne, calc μ (g₁ • s ∩ g₂ • s) = μ (g₂ • ((g₂⁻¹ * g₁) • s ∩ s)) : by rw [smul_set_inter, smul_smul, mul_inv_cancel_left] ... = μ ((g₂⁻¹ * g₁) • s ∩ s) : measure_smul_set _ _ _ ... = 0 : h.ae_disjoint _ $ mt inv_mul_eq_one.1 hne.symm @[to_additive] lemma pairwise_ae_disjoint_of_ac {ν} (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : pairwise (λ g₁ g₂ : G, ae_disjoint ν (g₁ • s) (g₂ • s)) := h.pairwise_ae_disjoint.mono $ λ g₁ g₂ H, hν H @[to_additive] lemma preimage_of_equiv (h : is_fundamental_domain G s μ) {f : α → α} (hf : quasi_measure_preserving f μ μ) {e : G → G} (he : bijective e) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain G (f ⁻¹' s) μ := { null_measurable_set := h.null_measurable_set.preimage hf, ae_covers := (hf.ae h.ae_covers).mono $ λ x ⟨g, hg⟩, ⟨e g, by rwa [mem_preimage, hef g x]⟩, ae_disjoint := λ g hg, begin lift e to G ≃ G using he, have : (e.symm g⁻¹)⁻¹ ≠ (e.symm 1)⁻¹, by simp [hg], convert (h.pairwise_ae_disjoint _ _ this).preimage hf using 1, { simp only [← preimage_smul_inv, preimage_preimage, ← hef _ _, e.apply_symm_apply, inv_inv] }, { ext1 x, simp only [mem_preimage, ← preimage_smul, ← hef _ _, e.apply_symm_apply, one_smul] } end } @[to_additive] lemma image_of_equiv (h : is_fundamental_domain G s μ) (f : α ≃ᵐ α) (hfμ : measure_preserving f μ μ) (e : equiv.perm G) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain G (f '' s) μ := begin rw f.image_eq_preimage, refine h.preimage_of_equiv (hfμ.symm f).quasi_measure_preserving e.symm.bijective (λ g x, _), rcases f.surjective x with ⟨x, rfl⟩, rw [← hef _ _, f.symm_apply_apply, f.symm_apply_apply, e.apply_symm_apply] end @[to_additive] lemma smul (h : is_fundamental_domain G s μ) (g : G) : is_fundamental_domain G (g • s) μ := h.image_of_equiv (measurable_equiv.smul g) (measure_preserving_smul _ _) ⟨λ g', g⁻¹ * g' * g, λ g', g * g' * g⁻¹, λ g', by simp [mul_assoc], λ g', by simp [mul_assoc]⟩ $ λ g' x, by simp [smul_smul, mul_assoc] @[to_additive] lemma smul_of_comm {G' : Type*} [group G'] [mul_action G' α] [measurable_space G'] [has_measurable_smul G' α] [smul_invariant_measure G' α μ] [smul_comm_class G' G α] (h : is_fundamental_domain G s μ) (g : G') : is_fundamental_domain G (g • s) μ := h.image_of_equiv (measurable_equiv.smul g) (measure_preserving_smul _ _) (equiv.refl _) $ smul_comm g variables [encodable G] {ν : measure α} @[to_additive] lemma sum_restrict_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : sum (λ g : G, ν.restrict (g • s)) = ν := by rw [← restrict_Union_ae (h.pairwise_ae_disjoint.mono $ λ i j h, hν h) (λ g, (h.null_measurable_set_smul g).mono_ac hν), restrict_congr_set (hν h.Union_smul_ae_eq), restrict_univ] @[to_additive] lemma lintegral_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂ν = ∑' g : G, ∫⁻ x in g • s, f x ∂ν := by rw [← lintegral_sum_measure, h.sum_restrict_of_ac hν] @[to_additive] lemma sum_restrict (h : is_fundamental_domain G s μ) : sum (λ g : G, μ.restrict (g • s)) = μ := h.sum_restrict_of_ac (refl _) @[to_additive] lemma lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂μ := h.lintegral_eq_tsum_of_ac (refl _) f @[to_additive] lemma set_lintegral_eq_tsum' (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂(μ.restrict t) : h.lintegral_eq_tsum_of_ac restrict_le_self.absolutely_continuous _ ... = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : by simp only [h.restrict_restrict, inter_comm] @[to_additive] lemma set_lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : h.set_lintegral_eq_tsum' f t ... = ∑' g : G, ∫⁻ x in t ∩ g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫⁻ x in g⁻¹ • (g • t ∩ s), f (x) ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, ((measure_preserving_smul g⁻¹ μ).set_lintegral_comp_emb (measurable_embedding_const_smul _) _ _).symm @[to_additive] lemma measure_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (t : set α) : ν t = ∑' g : G, ν (t ∩ g • s) := have H : ν.restrict t ≪ μ, from measure.restrict_le_self.absolutely_continuous.trans hν, by simpa only [set_lintegral_one, pi.one_def, measure.restrict_apply₀ ((h.null_measurable_set_smul _).mono_ac H), inter_comm] using h.lintegral_eq_tsum_of_ac H 1 @[to_additive] lemma measure_eq_tsum' (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (t ∩ g • s) := h.measure_eq_tsum_of_ac absolutely_continuous.rfl t @[to_additive] lemma measure_eq_tsum (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (g • t ∩ s) := by simpa only [set_lintegral_one] using h.set_lintegral_eq_tsum (λ _, 1) t @[to_additive] lemma measure_zero_of_invariant (h : is_fundamental_domain G s μ) (t : set α) (ht : ∀ g : G, g • t = t) (hts : μ (t ∩ s) = 0) : μ t = 0 := by simp [measure_eq_tsum h, ht, hts] @[to_additive] protected lemma set_lintegral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) (f : α → ℝ≥0∞) (hf : ∀ (g : G) x, f (g • x) = f x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := calc ∫⁻ x in s, f x ∂μ = ∑' g : G, ∫⁻ x in s ∩ g • t, f x ∂μ : ht.set_lintegral_eq_tsum' _ _ ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : by simp only [hf, inter_comm] ... = ∫⁻ x in t, f x ∂μ : (hs.set_lintegral_eq_tsum _ _).symm @[to_additive] lemma measure_set_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {A : set α} (hA₀ : measurable_set A) (hA : ∀ (g : G), (λ x, g • x) ⁻¹' A = A) : μ (A ∩ s) = μ (A ∩ t) := begin have : ∫⁻ x in s, A.indicator 1 x ∂μ = ∫⁻ x in t, A.indicator 1 x ∂μ, { refine hs.set_lintegral_eq ht (set.indicator A (λ _, 1)) _, intros g x, convert (set.indicator_comp_right (λ x : α, g • x)).symm, rw hA g }, simpa [measure.restrict_apply hA₀, lintegral_indicator _ hA₀] using this end /-- If `s` and `t` are two fundamental domains of the same action, then their measures are equal. -/ @[to_additive "If `s` and `t` are two fundamental domains of the same action, then their measures are equal."] protected lemma measure_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) : μ s = μ t := by simpa only [set_lintegral_one] using hs.set_lintegral_eq ht (λ _, 1) (λ _ _, rfl) @[to_additive] protected lemma ae_strongly_measurable_on_iff {β : Type*} [topological_space β] [pseudo_metrizable_space β] (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → β} (hf : ∀ (g : G) x, f (g • x) = f x) : ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (μ.restrict t) := calc ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (measure.sum $ λ g : G, (μ.restrict (g • t ∩ s))) : by simp only [← ht.restrict_restrict, ht.sum_restrict_of_ac restrict_le_self.absolutely_continuous] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • (g⁻¹ • s ∩ t))) : by simp only [smul_set_inter, inter_comm, smul_inv_smul, ae_strongly_measurable_sum_measure_iff] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g⁻¹⁻¹ • s ∩ t))) : inv_surjective.forall ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g • s ∩ t))) : by simp only [inv_inv] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • s ∩ t)) : begin refine forall_congr (λ g, _), have he : measurable_embedding ((•) g⁻¹ : α → α) := measurable_embedding_const_smul _, rw [← image_smul, ← ((measure_preserving_smul g⁻¹ μ).restrict_image_emb he _).ae_strongly_measurable_comp_iff he], simp only [(∘), hf] end ... ↔ ae_strongly_measurable f (μ.restrict t) : by simp only [← ae_strongly_measurable_sum_measure_iff, ← hs.restrict_restrict, hs.sum_restrict_of_ac restrict_le_self.absolutely_continuous] @[to_additive] protected lemma has_finite_integral_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : has_finite_integral f (μ.restrict s) ↔ has_finite_integral f (μ.restrict t) := begin dunfold has_finite_integral, rw hs.set_lintegral_eq ht, intros g x, rw hf end @[to_additive] protected lemma integrable_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : integrable_on f s μ ↔ integrable_on f t μ := and_congr (hs.ae_strongly_measurable_on_iff ht hf) (hs.has_finite_integral_on_iff ht hf) variables [normed_space ℝ E] [complete_space E] @[to_additive] protected lemma set_integral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := begin by_cases hfs : integrable_on f s μ, { have hft : integrable_on f t μ, by rwa ht.integrable_on_iff hs hf, have hac : ∀ {u}, μ.restrict u ≪ μ := λ u, restrict_le_self.absolutely_continuous, calc ∫ x in s, f x ∂μ = ∫ x in ⋃ g : G, g • t, f x ∂(μ.restrict s) : by rw [restrict_congr_set (hac ht.Union_smul_ae_eq), restrict_univ] ... = ∑' g : G, ∫ x in g • t, f x ∂(μ.restrict s) : integral_Union_ae (λ g, (ht.null_measurable_set_smul g).mono_ac hac) (ht.pairwise_ae_disjoint_of_ac hac) hfs.integrable.integrable_on ... = ∑' g : G, ∫ x in s ∩ g • t, f x ∂μ : by simp only [ht.restrict_restrict, inter_comm] ... = ∑' g : G, ∫ x in s ∩ g⁻¹ • t, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫ x in g⁻¹ • (g • s ∩ t), f x ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫ x in g • s ∩ t, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, (measure_preserving_smul g⁻¹ μ).set_integral_image_emb (measurable_embedding_const_smul _) _ _ ... = ∑' g : G, ∫ x in g • s, f x ∂(μ.restrict t) : by simp only [hf, hs.restrict_restrict] ... = ∫ x in ⋃ g : G, g • s, f x ∂(μ.restrict t) : (integral_Union_ae (λ g, (hs.null_measurable_set_smul g).mono_ac hac) (hs.pairwise_ae_disjoint.mono $ λ i j h, hac h) hft.integrable.integrable_on).symm ... = ∫ x in t, f x ∂μ : by rw [restrict_congr_set (hac hs.Union_smul_ae_eq), restrict_univ] }, { rw [integral_undef hfs, integral_undef], rwa [hs.integrable_on_iff ht hf] at hfs } end /-- If `f` is invariant under the action of a countable group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain. -/ @[to_additive "If `f` is invariant under the action of a countable additive group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain."] lemma ess_sup_measure_restrict (hs : is_fundamental_domain G s μ) {f : α → ℝ≥0∞} (hf : ∀ γ : G, ∀ x: α, f (γ • x) = f x) : ess_sup f (μ.restrict s) = ess_sup f μ := begin refine le_antisymm (ess_sup_mono_measure' measure.restrict_le_self) _, rw [ess_sup_eq_Inf (μ.restrict s) f, ess_sup_eq_Inf μ f], refine Inf_le_Inf _, rintro a (ha : (μ.restrict s) {x : α | a < f x} = 0), rw measure.restrict_apply₀' hs.null_measurable_set at ha, refine measure_zero_of_invariant hs _ _ ha, intros γ, ext x, rw mem_smul_set_iff_inv_smul_mem, simp only [mem_set_of_eq, hf (γ⁻¹) x], end end is_fundamental_domain end measure_theory
4c7e7b81ee628d1c2f8adc2036f9972849185494
abc24f6c7fc917103329a1d2b75463d93511f4ab
/src/integrals.lean
b250ff3c71da9897dd707a2fbc6e74c0e87a3b7f
[]
no_license
mmasdeu/euler
5073bb6b747aaca1a95692027de1f390b7648c28
a323d777dee611f2a06cc81e2f2567cd9522a381
refs/heads/main
1,682,109,127,673
1,620,655,192,000
1,620,655,192,000
323,932,638
1
0
null
null
null
null
UTF-8
Lean
false
false
14,188
lean
import tactic import measure_theory.interval_integral import measure_theory.lebesgue_measure import measure_theory.set_integral import analysis.calculus.deriv import analysis.special_functions.exp_log import analysis.special_functions.trigonometric import data.finset noncomputable theory open_locale classical open_locale big_operators open measure_theory open interval_integral open set open real namespace tactic.interactive meta def show_continuous := `[ all_goals {try {simp}}, apply_rules [ continuous_on.neg, continuous.continuous_on, differentiable.continuous, differentiable_on.continuous_on, continuous.Icc_extend, continuous_on.mono, continuous.neg, continuous_id, continuous_sin, continuous_cos, continuous_const, continuous.pow, continuous.mul, continuous.smul, continuous.sub, continuous.add ] 10, all_goals {try {norm_num}} ] meta def show_differentiable := `[ apply_rules [ differentiable.differentiable_on, differentiable.neg, differentiable.smul, differentiable.cos, differentiable.sin, differentiable_const, differentiable_id, differentiable.mul, differentiable_fpow ] 10, all_goals {try {norm_num}} ] meta def show_nonzero := `[ apply_rules [ mul_ne_zero, sub_ne_zero_of_ne, pow_ne_zero, ne_of_gt, ne_of_lt ] 10, all_goals {try {norm_cast}, try {norm_num}} ] meta def show_pos := `[ apply_rules [ nat.succ_pos, mul_pos, div_pos, inv_pos.mpr, pow_pos ] 10, all_goals {try {norm_cast}, try {norm_num}, try {nlinarith}} ] meta def clear_denoms := `[ try {rw div_eq_div_iff}, try {rw eq_div_iff}, try {symmetry, rw eq_div_iff}, try { ring_exp }, all_goals {show_nonzero} ] meta def discrete_field := `[ try {ext}, try {field_simp *}, try {clear_denoms}, try {ring_exp}, try {norm_num}, try {linarith} ] end tactic.interactive lemma integrable_of_cont {f : ℝ → ℝ} (a b : ℝ) (h : continuous f): interval_integrable f measure_theory.measure_space.volume a b := begin have hmeas : measurable f := continuous.measurable h, have hconton : continuous_on f (interval a b) := continuous.continuous_on h, exact continuous_on.interval_integrable hconton, end /- lemma self_mem_ae_restrict {s : set ℝ} (hs : is_measurable s): s ∈ (measure.restrict measure_space.volume s).ae := begin rw ae_restrict_eq hs, simp only [exists_prop, filter.mem_principal_sets, filter.mem_inf_sets], exact ⟨univ, filter.univ_mem_sets, s, by simp⟩, end -/ lemma nonempty_inter_of_nonempty_inter_closure {α : Type*} [topological_space α] {s t : set α} (hs : is_open s) (h : (s ∩ closure t).nonempty) : (s ∩ t).nonempty := let ⟨x, xs, xt⟩ := h in _root_.mem_closure_iff.1 xt s hs xs lemma real.volume_pos_of_is_open_of_nonempty {s : set ℝ} (h : is_open s) (h' : s.nonempty) : 0 < volume s := begin rcases h' with ⟨x, hx⟩, have : ∀ᶠ (y : ℝ) in nhds x, y ∈ s := filter.eventually_of_mem (mem_nhds_sets h hx) (λ y H, H), exact filter.eventually.volume_pos_of_nhds_real this, end theorem integral_strictly_pos_of_cont (f : ℝ → ℝ) (a b : ℝ) (hf : continuous f) (hab : a < b) (h : ∀ (x : ℝ), a ≤ x → x ≤ b → 0 ≤ f x) (hneq: ∃ x, a ≤ x ∧ x ≤ b ∧ 0 < f x) : 0 < ∫ x in a..b, f x := begin rw integral_pos_iff_support_of_nonneg_ae', { refine ⟨hab, _⟩, let s := {b : ℝ | 0 < f b}, have s_open : is_open s := is_open_lt continuous_const hf, have : (s ∩ closure (Ioo a b)).nonempty, { rw closure_Ioo hab, rcases hneq with ⟨x, ax, xb, fxpos⟩, have : x ∈ s ∩ Icc a b := ⟨fxpos, ax, xb⟩, exact nonempty_of_mem this }, have : (s ∩ Ioo a b).nonempty := nonempty_inter_of_nonempty_inter_closure s_open this, have : 0 < volume (s ∩ Ioo a b) := real.volume_pos_of_is_open_of_nonempty (is_open_inter s_open is_open_Ioo) this, refine this.trans_le (measure_mono (λ x hx, _)), split, { exact ne_of_gt (show 0 < f x, from hx.1) }, { exact ⟨hx.2.1, hx.2.2.le⟩ } }, { have : Ioc b a = ∅ := Ioc_eq_empty hab.le, simp only [this, union_empty], apply filter.eventually_of_mem _ _, exact Icc a b, { simp, use univ, simp, use Icc a b, exact ⟨Ioc_subset_Icc_self, rfl.subset⟩, }, simpa using h }, { exact integrable_of_cont a b hf } end theorem integral_strictly_monotone_of_cont (f g : ℝ → ℝ) (a b : ℝ) (hf : continuous f) (hg : continuous g) (hab : a < b) (h : ∀ (x : ℝ), a ≤ x → x ≤ b → f x ≤ g x) (hneq: ∃ x, a ≤ x ∧ x ≤ b ∧ f x < g x) : ∫ x in a..b, f x < ∫ x in a..b, g x := begin have H : 0 < ∫ x in a..b, (g x - f x), { apply integral_strictly_pos_of_cont (g-f) a b (continuous.sub hg hf) hab, all_goals { simp [sub_pos], assumption, }, }, rw [←sub_pos, ←interval_integral.integral_sub (integrable_of_cont a b hg) (integrable_of_cont a b hf)], exact H, end lemma int_pos_of_pos {f : ℝ → ℝ} {a b : ℝ} (hab : a < b) (hf : continuous f) (hnonneg : ∀ x, a ≤ x → x ≤ b → 0 ≤ f x) (hx : ∃ x, a ≤ x ∧ x ≤ b ∧ 0 < f x) : 0 < ∫ x in a..b, f x := begin rw ← (integral_zero : ∫ x in a..b, (0:ℝ) = 0 ), exact integral_strictly_monotone_of_cont (λ x, (0:ℝ)) f a b continuous_const hf hab hnonneg hx, end lemma int_pos_of_square {f : ℝ → ℝ} {a b} (x : ℝ) (hab : a < b) (hf : continuous f) (hx : a ≤ x ∧ x ≤ b ∧ f x ≠ 0) : 0 < ∫ x in a..b, (f x)^2 := begin refine int_pos_of_pos hab _ (λ x hx1 hx2, pow_two_nonneg (f x)) ⟨x, ⟨hx.1, hx.2.1, pow_two_pos_of_ne_zero (f x) hx.2.2⟩⟩, show_continuous, end theorem my_integral_smul (f : ℝ → ℝ) (a b c : ℝ) : ∫ x in a..b, c * (f x) = c * ∫ x in a..b, f x := begin suffices : ∫ x in a..b, c • (f x) = c • ∫ x in a..b, f x, by exact this, rw_mod_cast interval_integral.integral_smul, end theorem product_rule {f g : ℝ → ℝ} (hdf : differentiable ℝ f) (hdg : differentiable ℝ g) : deriv (f * g) = (deriv f) * g + f * deriv g := begin ext, have hdf0 : differentiable_at ℝ f x := hdf x, have hdg0 : differentiable_at ℝ g x := hdg x, apply deriv_mul hdf0 hdg0, end theorem differentiable_fpow {f : ℝ → ℝ} {n : ℕ} : differentiable ℝ f → differentiable ℝ (f^n) := begin induction n with d hd, { intro h, simp only [pow_zero], exact differentiable_const 1 }, { intro h, rw pow_succ, exact h.mul (hd h), } end theorem power_rule {f : ℝ → ℝ} {n : ℕ} (hfd : differentiable ℝ f): deriv (f^(n+1)) = ((n : ℝ) + 1) • f^n * (deriv f) := begin induction n with d hd, by norm_num, have H : f^(d+1) = f^d * f := pow_succ' f d, calc deriv (f^(d.succ+1)) = deriv (f^(d.succ) * f) : by {rw pow_succ' f (d.succ),} ... = (deriv (f^(d.succ))) * f + f^(d+1) * (deriv f) : begin rw product_rule, exact differentiable_fpow hfd, exact hfd, end ... = ((d:ℝ) + 1) • f^d * deriv f * f + f^d.succ * deriv f : by {rw hd} ... = ((d:ℝ) + 1) • (f^(d.succ)) * deriv f + f^(d.succ) * deriv f : begin simp only [add_left_inj, H], norm_num, rw mul_assoc, nth_rewrite_lhs 1 mul_comm, rw ←mul_assoc, end ... = ((d.succ:ℝ) + 1) • (f^(d.succ)) * deriv f : begin simp only [nat.cast_succ, algebra.smul_mul_assoc], nth_rewrite 1 add_smul, rw one_smul, end end lemma pow_fun_def {f : ℝ → ℝ} {n : ℕ} : f^n = λ x, (f x)^n := begin induction n with d hd, all_goals { try {rw [pow_succ, hd]}, refl, } end lemma pow_deriv_fun_def {f : ℝ → ℝ} {n : ℕ} : ((n : ℝ) + 1) • f^n * (deriv f) = λ (x : ℝ), ((n : ℝ) + 1) • ((f x)^n * deriv f x) := begin rw pow_fun_def, simpa, end @[simp] lemma power_rule' {f : ℝ → ℝ} (n : ℕ) (hfd : differentiable ℝ f): deriv (λ (x : ℝ), (f x)^(n + 1)) = λ (x : ℝ), ((n : ℝ) + 1) • ((f x)^n * deriv f x) := begin rw [←pow_fun_def, ←pow_deriv_fun_def], exact power_rule hfd, end @[simp] lemma power_rule'' (n : ℕ) : deriv (λ (x : ℝ), x^(n + 1)) = λ (x : ℝ), ((n : ℝ) + 1) • (x^n) := begin have hfd : differentiable ℝ (λ (x:ℝ), (x:ℝ)) := differentiable_id', have deriv_id_my : deriv (λ x, x) = λ (x : ℝ), (1:ℝ) := deriv_id', have H := power_rule' n hfd, rw deriv_id_my at H, rw H, simp only [mul_one, algebra.id.smul_eq_mul], end theorem int_by_parts (u v : ℝ → ℝ) {a b : ℝ} (hu : differentiable ℝ u) (hv : differentiable ℝ v) (hcu : continuous(deriv u)) (hcv : continuous(deriv v)) : ∫ x in a..b, u x * deriv v x = u b * v b - u a * v a - ∫ x in a..b, v x * deriv u x := begin have hu' : ∀ (x : ℝ), differentiable_at ℝ u x := hu, have hv' : ∀ (x : ℝ), differentiable_at ℝ v x := hv, have huv : deriv (u * v) = (deriv u) * v + u * deriv v := product_rule hu hv, have H : ∫ x in a..b, ((deriv u) x) * (v x) + (u x) * ((deriv v) x) = ∫ x in a..b, (deriv (u*v)) x, { congr, solve_by_elim, }, have duv_cont : continuous (deriv (u * v)), { rw product_rule hu hv, apply continuous.add, rw mul_comm, all_goals { apply continuous.mul, work_on_goal 0 { apply @differentiable.continuous ℝ _ _ _ _ _ _ _, }, repeat {assumption}, }, }, have duv_cont' : continuous_on (deriv (u * v)) (interval a b), { intros x hx, exact continuous.continuous_within_at duv_cont, }, have H2 : ∫ x in a..b, deriv (u*v) x = u b * v b - u a * v a, { apply integral_deriv_eq_sub, intros x hx, exact differentiable_at.mul (hu' x) (hv' x), exact duv_cont', }, rw [←H2, ←interval_integral.integral_sub], { congr, ext, rw huv, simp only [pi.add_apply, pi.mul_apply], rw mul_comm (v x) (deriv u x), ring, }, { apply integrable_of_cont, assumption, }, apply integrable_of_cont, apply continuous.mul, apply @differentiable.continuous ℝ _ _ _ _ _ _ _, repeat {assumption}, end lemma int_by_parts_zero_ends (u v : ℝ → ℝ) {a b : ℝ} (hu : differentiable ℝ u) (hv : differentiable ℝ v) (hcu : continuous(deriv u)) (hcv : continuous(deriv v)) (ha : u a * v a = 0) (hb : u b * v b = 0) : ∫ x in a..b, u x * deriv v x = - ∫ x in a..b, v x * deriv u x := begin rw int_by_parts, repeat {assumption}, rw [ha, hb], norm_num, end @[simp] lemma pow_ext (f : ℝ → ℝ) (n : ℕ) : f^n = λ x, (f x)^n := begin induction n with d hd, { norm_num, refl, }, { change f^(d+1) = λ x, (f x)^(d+1), rw [pow_add, hd, pow_one], ext, norm_num, ring_nf, } end lemma differentiable_cospow_at (n: ℕ) {x : ℝ} : differentiable_at ℝ (cos^(n+1)) x:= by show_differentiable lemma deriv_cospow (n: ℕ) : deriv (λ (x : ℝ), cos x ^ (n+1)) = λ x, -((n : ℝ)+1) * (cos x)^n * sin x := begin suffices : (λ (x : ℝ), -(((n:ℝ) + 1) * (cos x ^ n * sin x))) = λ (x : ℝ), (-1 + -n) * cos x^n * sin x, by simpa, ext, ring, end lemma continuous_cospow {n: ℕ} : continuous (λ (x : ℝ), (cos x)^n) := begin exact continuous.pow continuous_cos n, end lemma continuous_cospow' {c : ℝ} {m : ℕ} : continuous (λ (x : ℝ), c * cos x ^m) := by show_continuous lemma differentiable_cospow {n: ℕ} : differentiable ℝ (λ (x : ℝ), (cos x)^n) := begin simp only [differentiable_id', differentiable.pow, differentiable.cos], end lemma continuous_deriv_cospow (n: ℕ) : continuous (deriv (λ (x : ℝ), cos x ^ (n+1))) := begin rw deriv_cospow, apply continuous.mul continuous_cospow' continuous_sin, end @[simp] lemma deriv_sin_times_cos {x : ℝ} : deriv(sin * cos) x = 2 * cos x ^ 2 - 1 := begin have H : deriv (λ (y : ℝ), sin y * cos y) x = deriv sin x * cos x + sin x * deriv cos x := deriv_mul differentiable_at_sin differentiable_at_cos, have h0 : sin * cos = λ y, sin y * cos y, by refl, have hsin : sin x^2 = 1 - cos x^2, { rw eq_sub_iff_add_eq, exact sin_sq_add_cos_sq x, }, rw [h0, H, real.deriv_sin, real.deriv_cos], ring_nf, rw hsin, ring, end @[simp] lemma deriv_sin_cos {m : ℕ} : deriv (λ x, sin x * cos x^(m+1)) = λ x, (m+2) * cos x^(m+2) - (m+1) * cos x^m := begin ext, suffices : deriv(sin * cos^(m+1)) x = (m+2) * (cos x)^(m+2) - (m+1) * (cos x)^m, { rw pow_ext at this, exact this, }, induction m with d hd, { simp only [mul_one, nat.cast_zero, pow_one, zero_add, pow_zero], exact deriv_sin_times_cos, }, { simp, have H := deriv_mul (@differentiable_at_sin x) (differentiable_cospow_at d.succ), repeat {rw pow_succ,}, have h2 : (λ (y : ℝ), sin y * (cos ^ (d.succ + 1)) y) x = sin x * (cos ^ (d.succ + 1)) x, by tauto, have hsin : sin * (λ (x : ℝ), cos x ^ (d.succ + 1)) = (λ x, sin x * cos x ^ (d.succ + 1)), by tauto, rw hsin, have hhd : (sin * cos ^ (d + 1) = λ (y : ℝ), sin y * cos y ^ (d + 1)), { ext, simp only [pi.mul_apply, pow_ext], }, simp [pow_ext], ring_exp, have sin_to_cos : sin x^2 = 1 - cos x^2, { rw eq_sub_iff_add_eq, exact sin_sq_add_cos_sq x, }, rw sin_to_cos, discrete_field, }, end
9e9dc1c379262ed2ae7321a5307331f7bcd24f17
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/def_complete_bug.lean
1a1b7111e3f7bfb77b8380c8667543a6425bf57f
[ "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
400
lean
definition g : list nat → list nat → nat | [] (y::ys) := y | [] ys := 0 | (x1::x2::xs) ys := g xs ys | (x::xs) (y::ys) := g xs ys + y | (x::xs) [] := g xs [] #print g._main.equations._eqn_1 #print g._main.equations._eqn_2 #print g._main.equations._eqn_3 #print g._main.equations._eqn_4 #print g._main.equations._eqn_5 #print g._main.equations._eqn_6
c6f68d16271aa51a0fb6c85142dd1e605f052590
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/sheaves/sheaf_condition/pairwise_intersections.lean
098146619b7d0fb1b7852efcb38dada29c0e40b8
[ "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,948
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 topology.sheaves.sheaf import category_theory.limits.preserves.basic import category_theory.category.pairwise /-! # Equivalent formulations of the sheaf condition We give an equivalent formulation of the sheaf condition. Given any indexed type `ι`, we define `overlap ι`, a category with objects corresponding to * individual open sets, `single i`, and * intersections of pairs of open sets, `pair i j`, with morphisms from `pair i j` to both `single i` and `single j`. Any open cover `U : ι → opens X` provides a functor `diagram U : overlap ι ⥤ (opens X)ᵒᵖ`. There is a canonical cone over this functor, `cone U`, whose cone point is `supr U`, and in fact this is a limit cone. A presheaf `F : presheaf C X` is a sheaf precisely if it preserves this limit. We express this in two equivalent ways, as * `is_limit (F.map_cone (cone U))`, or * `preserves_limit (diagram U) F` -/ noncomputable theory universes v u open topological_space open Top open opposite open category_theory open category_theory.limits namespace Top.presheaf variables {X : Top.{v}} variables {C : Type u} [category.{v} C] /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `sheaf_condition_equiv_sheaf_condition_pairwise_intersections`). A presheaf is a sheaf if `F` sends the cone `(pairwise.cocone U).op` to a limit cone. (Recall `pairwise.cocone U` has cone point `supr U`, mapping down to the `U i` and the `U i ⊓ U j`.) -/ def is_sheaf_pairwise_intersections (F : presheaf C X) : Prop := ∀ ⦃ι : Type v⦄ (U : ι → opens X), nonempty (is_limit (F.map_cone (pairwise.cocone U).op)) /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections`). A presheaf is a sheaf if `F` preserves the limit of `pairwise.diagram U`. (Recall `pairwise.diagram U` is the diagram consisting of the pairwise intersections `U i ⊓ U j` mapping into the open sets `U i`. This diagram has limit `supr U`.) -/ def is_sheaf_preserves_limit_pairwise_intersections (F : presheaf C X) : Prop := ∀ ⦃ι : Type v⦄ (U : ι → opens X), nonempty (preserves_limit (pairwise.diagram U).op F) /-! The remainder of this file shows that these conditions are equivalent to the usual sheaf condition. -/ variables [has_products C] namespace sheaf_condition_pairwise_intersections open category_theory.pairwise category_theory.pairwise.hom open sheaf_condition_equalizer_products /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor_obj (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone ((diagram U).op ⋙ F)) : limits.cone (sheaf_condition_equalizer_products.diagram F U) := { X := c.X, π := { app := λ Z, walking_parallel_pair.cases_on Z (pi.lift (λ (i : ι), c.π.app (op (single i)))) (pi.lift (λ (b : ι × ι), c.π.app (op (pair b.1 b.2)))), naturality' := λ Y Z f, begin cases Y; cases Z; cases f, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.left_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.left i j)), dsimp at h, simpa using h, }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.right_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.right i j)), dsimp at h, simpa using h, }, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, end, }, } section local attribute [tidy] tactic.case_bash /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) : limits.cone ((diagram U).op ⋙ F) ⥤ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { obj := λ c, cone_equiv_functor_obj F U c, map := λ c c' f, { hom := f.hom, w' := λ j, begin cases j; { ext, simp only [limits.fan.mk_π_app, limits.cone_morphism.w, limits.limit.lift_π, category.assoc, cone_equiv_functor_obj_π_app], }, end }, }. end /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse_obj (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone (sheaf_condition_equalizer_products.diagram F U)) : limits.cone ((diagram U).op ⋙ F) := { X := c.X, π := { app := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { exact c.π.app (walking_parallel_pair.zero) ≫ pi.π _ i, }, { exact c.π.app (walking_parallel_pair.one) ≫ pi.π _ (i, j), } end, naturality' := begin intros x y f, induction x using opposite.rec, induction y using opposite.rec, have ef : f = f.unop.op := rfl, revert ef, generalize : f.unop = f', rintro rfl, rcases x with ⟨i⟩|⟨⟩; rcases y with ⟨⟩|⟨j,j⟩; rcases f' with ⟨⟩, { dsimp, erw [F.map_id], simp, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.left), dsimp [sheaf_condition_equalizer_products.left_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (i, j), rw h', simp, refl, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.right), dsimp [sheaf_condition_equalizer_products.right_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (j, i), rw h', simp, refl, }, { dsimp, erw [F.map_id], simp, }, end, }, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) : limits.cone (sheaf_condition_equalizer_products.diagram F U) ⥤ limits.cone ((diagram U).op ⋙ F) := { obj := λ c, cone_equiv_inverse_obj F U c, map := λ c c' f, { hom := f.hom, w' := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { dsimp, rw [←(f.w walking_parallel_pair.zero), category.assoc], }, { dsimp, rw [←(f.w walking_parallel_pair.one), category.assoc], }, end }, }. /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso_app (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : cone ((diagram U).op ⋙ F)) : (𝟭 (cone ((diagram U).op ⋙ F))).obj c ≅ (cone_equiv_functor F U ⋙ cone_equiv_inverse F U).obj c := { hom := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end, }, inv := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end }, hom_inv_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, inv_hom_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : 𝟭 (limits.cone ((diagram U).op ⋙ F)) ≅ cone_equiv_functor F U ⋙ cone_equiv_inverse F U := nat_iso.of_components (cone_equiv_unit_iso_app F U) (by tidy) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_counit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : cone_equiv_inverse F U ⋙ cone_equiv_functor F U ≅ 𝟭 (limits.cone (sheaf_condition_equalizer_products.diagram F U)) := nat_iso.of_components (λ c, { hom := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end, }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, }) (λ c d f, by { ext, dsimp, simp only [category.comp_id, category.id_comp], }) /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def cone_equiv (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : limits.cone ((diagram U).op ⋙ F) ≌ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { functor := cone_equiv_functor F U, inverse := cone_equiv_inverse F U, unit_iso := cone_equiv_unit_iso F U, counit_iso := cone_equiv_counit_iso F U, } local attribute [reducible] sheaf_condition_equalizer_products.res sheaf_condition_equalizer_products.left_res /-- If `sheaf_condition_equalizer_products.fork` is an equalizer, then `F.map_cone (cone U)` is a limit cone. -/ def is_limit_map_cone_of_is_limit_sheaf_condition_fork (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) (P : is_limit (sheaf_condition_equalizer_products.fork F U)) : is_limit (F.map_cone (cocone U).op) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U).symm).symm P) { hom := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } /-- If `F.map_cone (cone U)` is a limit cone, then `sheaf_condition_equalizer_products.fork` is an equalizer. -/ def is_limit_sheaf_condition_fork_of_is_limit_map_cone (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) (Q : is_limit (F.map_cone (cocone U).op)) : is_limit (sheaf_condition_equalizer_products.fork F U) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U)).symm Q) { hom := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } end sheaf_condition_pairwise_intersections open sheaf_condition_pairwise_intersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ lemma is_sheaf_iff_is_sheaf_pairwise_intersections (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_pairwise_intersections := iff.intro (λ h ι U, ⟨is_limit_map_cone_of_is_limit_sheaf_condition_fork F U (h U).some⟩) (λ h ι U, ⟨is_limit_sheaf_condition_fork_of_is_limit_map_cone F U (h U).some⟩) /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of the presheaf preserving the limit of the diagram consisting of the `U i` and `U i ⊓ U j`. -/ lemma is_sheaf_iff_is_sheaf_preserves_limit_pairwise_intersections (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_preserves_limit_pairwise_intersections := begin rw is_sheaf_iff_is_sheaf_pairwise_intersections, split, { intros h ι U, exact ⟨preserves_limit_of_preserves_limit_cone (pairwise.cocone_is_colimit U).op (h U).some⟩ }, { intros h ι U, haveI := (h U).some, exact ⟨preserves_limit.preserves (pairwise.cocone_is_colimit U).op⟩ } end end Top.presheaf
7111d119b70d3dce1d31535a6257e7ffbda69e87
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/src/Lean/Elab/AuxDef.lean
33cce375b0137664e18061fb56184e1469eae66d
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
1,363
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Lean.Elab.Command namespace Lean.Elab.Command open Lean.Parser.Command open Lean.Parser.Term /-- Declares an auxiliary definition with an automatically generated name. For example, `aux_def foo : Nat := 42` creates a definition with an internal, unused name based on the suggestion `foo`. -/ scoped syntax (name := aux_def) docComment ? attributes ? "aux_def" ident+ ":" term ":=" term : command @[builtinCommandElab «aux_def»] def elabAuxDef : CommandElab | `($[$doc?:docComment]? $[$attrs?:attributes]? aux_def $[$suggestion:ident]* : $ty := $body) => do let id := suggestion.map (·.getId.eraseMacroScopes) |>.foldl (· ++ ·) Name.anonymous let id := `_aux ++ (← getMainModule) ++ `_ ++ id let id := String.intercalate "_" <| id.components.map (·.toString) let ns ← getCurrNamespace -- make sure we only add a single component so that scoped workes let id ← mkAuxName (ns.mkStr id) 1 let id := id.replacePrefix ns Name.anonymous -- TODO: replace with def _root_.id elabCommand <| ← `($[$doc?:docComment]? $[$attrs?:attributes]? def $(mkIdentFrom (mkNullNode suggestion) id):ident : $ty := $body) | _ => throwUnsupportedSyntax
975b74ae52bcaec18ec9fdd1b894b59d8c8935b2
ea916b7f42baf59c02ca82e274a87b3e45397968
/src/super/eqn_lemmas.lean
84c982a7c68996009f71505a5534bcc44f2a4ea1
[]
no_license
robertylewis/super2
2926383b166e43ebd815b81ae8fba976393a160c
8ba522fd609d25752cd3d9b478bc48b6453e3c1e
refs/heads/master
1,670,062,676,962
1,597,795,530,000
1,597,795,530,000
289,744,671
0
0
null
1,598,207,476,000
1,598,207,476,000
null
UTF-8
Lean
false
false
2,318
lean
import super.utils super.clause open tactic expr namespace super meta def get_eqn_lemma_clauses (n : name) : tactic (list clause) := do els ← get_eqn_lemmas_for tt n, els.mmap clause.of_const meta def mk_inst_equations_core : expr → expr → tactic (list expr) | lhs rhs := do type ← infer_type lhs, (type_args, tgt) ← mk_local_pis_whnf type, tgt ← whnf tgt, let str := tgt.get_app_fn.const_name, is_cls ← has_attribute' `class str, e ← get_env, if is_cls ∧ e.is_structure str then do if type_args ≠ [] then do let lhs := lhs.mk_app type_args, let rhs := rhs.instantiate_lambdas_or_apps type_args, eqns ← mk_inst_equations_core lhs rhs, pure $ eqns.map (mk_lambdas type_args) else do lhs ← whnf lhs transparency.reducible, 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 rhs ← whnf rhs, if is_constant_of rhs.get_app_fn intro then do -- if the value is a constructor application let rhs_args := rhs.get_app_args.drop params.length, -- the fields of the structure guard (rhs_args.length = projs.length) <|> fail "unreachable code (2)", list.join <$> (projs.zip rhs_args).mmap (λ ⟨proj, new_rhs⟩, do new_type ← infer_type new_rhs, b ← is_prop new_type, if b then -- Prop field pure [] else do new_lhs ← mk_mapp proj ((params ++ [lhs]).map some), mk_inst_equations_core new_lhs new_rhs) else do -- class subfield that doesn't reduce to a constructor pure [] else do -- non-class field e ← mk_mapp ``eq [none, lhs, rhs], prfl ← mk_eq_refl lhs, pure <$> (expr.app <$> mk_mapp ``id_rhs [e] <*> pure prfl) meta def mk_inst_equations (n : name) : tactic (list expr) := do lhs ← mk_const n, rhs ← whnf lhs, mk_inst_equations_core lhs rhs meta def mk_inst_eqn_clauses (n : name) : tactic (list clause) := do prfs ← mk_inst_equations n, prfs.mmap $ λ prf, clause.of_proof prf >>= clause.clone meta def get_aux_lemma_clauses (n : name) : tactic (list clause) := do is_inst ← has_attribute' `instance n, if is_inst then mk_inst_eqn_clauses n else get_eqn_lemma_clauses n end super
93db1b0df1690c9ee5dd8bba49d0b9ccb3c8bb80
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/closure_bug5.lean
41a8aea45ab61e7300ba2e1080b06217d81c585a
[ "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
540
lean
def f (x : Nat) : Nat × (Nat → String) := let x1 := x + 1; let x2 := x + 2; let x3 := x + 3; let x4 := x + 4; let x5 := x + 5; let x6 := x + 6; let x7 := x + 7; let x8 := x + 8; let x9 := x + 9; let x10 := x + 10; let x11 := x + 11; let x12 := x + 12; let x13 := x + 13; let x14 := x + 14; let x15 := x + 15; let x16 := x + 16; let x17 := x + 17; (x, fun y => toString [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14]) def main (xs : List String) : IO Unit := IO.println ((f (xs.headD "0").toNat!).2 (xs.headD "0").toNat!)
ac258b074d0eb33eb29fea8549288309f26e331e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/hom_auto.lean
5123eefd60b2242e9f58606a76a4b3b1b3fba537
[]
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
40,409
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.commute import Mathlib.algebra.group_with_zero.defs import Mathlib.PostPort universes u_6 u_7 l u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # monoid and group homomorphisms This file defines the bundled structures for monoid and group homomorphisms. Namely, we define `monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp., additive) monoids or groups. We also define coercion to a function, and usual operations: composition, identity homomorphism, pointwise multiplication and pointwise inversion. This file also defines the lesser-used (and notation-less) homomorphism types which are used as building blocks for other homomorphisms: * `zero_hom` * `one_hom` * `add_hom` * `mul_hom` * `monoid_with_zero_hom` ## Notations * `→*` for bundled monoid homs (also use for group homs) * `→+` for bundled add_monoid homs (also use for add_group homs) ## implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. Historically this file also included definitions of unbundled homomorphism classes; they were deprecated and moved to `deprecated/group`. ## Tags monoid_hom, add_monoid_hom -/ -- for easy multiple inheritance /-- Homomorphism that preserves zero -/ structure zero_hom (M : Type u_6) (N : Type u_7) [HasZero M] [HasZero N] where to_fun : M → N map_zero' : to_fun 0 = 0 /-- Homomorphism that preserves addition -/ structure add_hom (M : Type u_6) (N : Type u_7) [Add M] [Add N] where to_fun : M → N map_add' : ∀ (x y : M), to_fun (x + y) = to_fun x + to_fun y /-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/ structure add_monoid_hom (M : Type u_6) (N : Type u_7) [add_monoid M] [add_monoid N] extends zero_hom M N, add_hom M N where infixr:25 " →+ " => Mathlib.add_monoid_hom /-- Homomorphism that preserves one -/ structure one_hom (M : Type u_6) (N : Type u_7) [HasOne M] [HasOne N] where to_fun : M → N map_one' : to_fun 1 = 1 /-- Homomorphism that preserves multiplication -/ structure mul_hom (M : Type u_6) (N : Type u_7) [Mul M] [Mul N] where to_fun : M → N map_mul' : ∀ (x y : M), to_fun (x * y) = to_fun x * to_fun y /-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/ structure monoid_hom (M : Type u_6) (N : Type u_7) [monoid M] [monoid N] extends one_hom M N, mul_hom M N where /-- Bundled monoid with zero homomorphisms; use this for bundled group with zero homomorphisms too. -/ structure monoid_with_zero_hom (M : Type u_6) (N : Type u_7) [monoid_with_zero M] [monoid_with_zero N] extends zero_hom M N, monoid_hom M N where infixr:25 " →* " => Mathlib.monoid_hom -- completely uninteresting lemmas about coercion to function, that all homs need /-! Bundled morphisms can be down-cast to weaker bundlings -/ protected instance monoid_hom.has_coe_to_one_hom {M : Type u_1} {N : Type u_2} {mM : monoid M} {mN : monoid N} : has_coe (M →* N) (one_hom M N) := has_coe.mk monoid_hom.to_one_hom protected instance add_monoid_hom.has_coe_to_add_hom {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} : has_coe (M →+ N) (add_hom M N) := has_coe.mk add_monoid_hom.to_add_hom protected instance monoid_with_zero_hom.has_coe_to_monoid_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} : has_coe (monoid_with_zero_hom M N) (M →* N) := has_coe.mk monoid_with_zero_hom.to_monoid_hom protected instance monoid_with_zero_hom.has_coe_to_zero_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} : has_coe (monoid_with_zero_hom M N) (zero_hom M N) := has_coe.mk monoid_with_zero_hom.to_zero_hom /-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because this is the way things were before the above coercions were introduced. Bundled morphisms defined elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/ @[simp] theorem monoid_hom.coe_eq_to_one_hom {M : Type u_1} {N : Type u_2} {mM : monoid M} {mN : monoid N} (f : M →* N) : ↑f = monoid_hom.to_one_hom f := rfl @[simp] theorem add_monoid_hom.coe_eq_to_add_hom {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) : ↑f = add_monoid_hom.to_add_hom f := rfl @[simp] theorem monoid_with_zero_hom.coe_eq_to_monoid_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} (f : monoid_with_zero_hom M N) : ↑f = monoid_with_zero_hom.to_monoid_hom f := rfl @[simp] theorem monoid_with_zero_hom.coe_eq_to_zero_hom {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} (f : monoid_with_zero_hom M N) : ↑f = monoid_with_zero_hom.to_zero_hom f := rfl protected instance zero_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : HasZero M} {mN : HasZero N} : has_coe_to_fun (zero_hom M N) := has_coe_to_fun.mk (fun (x : zero_hom M N) => M → N) zero_hom.to_fun protected instance mul_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : Mul M} {mN : Mul N} : has_coe_to_fun (mul_hom M N) := has_coe_to_fun.mk (fun (x : mul_hom M N) => M → N) mul_hom.to_fun protected instance add_monoid_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} : has_coe_to_fun (M →+ N) := has_coe_to_fun.mk (fun (x : M →+ N) => M → N) add_monoid_hom.to_fun protected instance monoid_with_zero_hom.has_coe_to_fun {M : Type u_1} {N : Type u_2} {mM : monoid_with_zero M} {mN : monoid_with_zero N} : has_coe_to_fun (monoid_with_zero_hom M N) := has_coe_to_fun.mk (fun (x : monoid_with_zero_hom M N) => M → N) monoid_with_zero_hom.to_fun -- these must come after the coe_to_fun definitions @[simp] theorem zero_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] (f : zero_hom M N) : zero_hom.to_fun f = ⇑f := rfl @[simp] theorem mul_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) : mul_hom.to_fun f = ⇑f := rfl @[simp] theorem add_monoid_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) : add_monoid_hom.to_fun f = ⇑f := rfl @[simp] theorem monoid_with_zero_hom.to_fun_eq_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : monoid_with_zero_hom.to_fun f = ⇑f := rfl @[simp] theorem one_hom.coe_mk {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : M → N) (h1 : f 1 = 1) : ⇑(one_hom.mk f h1) = f := rfl @[simp] theorem add_hom.coe_mk {M : Type u_1} {N : Type u_2} [Add M] [Add N] (f : M → N) (hmul : ∀ (x y : M), f (x + y) = f x + f y) : ⇑(add_hom.mk f hmul) = f := rfl @[simp] theorem add_monoid_hom.coe_mk {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M → N) (h1 : f 0 = 0) (hmul : ∀ (x y : M), f (x + y) = f x + f y) : ⇑(add_monoid_hom.mk f h1 hmul) = f := rfl @[simp] theorem monoid_with_zero_hom.coe_mk {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : M → N) (h0 : f 0 = 0) (h1 : f 1 = 1) (hmul : ∀ (x y : M), f (x * y) = f x * f y) : ⇑(monoid_with_zero_hom.mk f h0 h1 hmul) = f := rfl @[simp] theorem monoid_hom.to_one_hom_coe {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (f : M →* N) : ⇑(monoid_hom.to_one_hom f) = ⇑f := rfl @[simp] theorem add_monoid_hom.to_add_hom_coe {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) : ⇑(add_monoid_hom.to_add_hom f) = ⇑f := rfl @[simp] theorem monoid_with_zero_hom.to_zero_hom_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : ⇑(monoid_with_zero_hom.to_zero_hom f) = ⇑f := rfl @[simp] theorem monoid_with_zero_hom.to_monoid_hom_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : ⇑(monoid_with_zero_hom.to_monoid_hom f) = ⇑f := rfl theorem one_hom.congr_fun {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] {f : one_hom M N} {g : one_hom M N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x := congr_arg (fun (h : one_hom M N) => coe_fn h x) h theorem add_hom.congr_fun {M : Type u_1} {N : Type u_2} [Add M] [Add N] {f : add_hom M N} {g : add_hom M N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x := congr_arg (fun (h : add_hom M N) => coe_fn h x) h theorem add_monoid_hom.congr_fun {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x := congr_arg (fun (h : M →+ N) => coe_fn h x) h theorem monoid_with_zero_hom.congr_fun {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} (h : f = g) (x : M) : coe_fn f x = coe_fn g x := congr_arg (fun (h : monoid_with_zero_hom M N) => coe_fn h x) h theorem one_hom.congr_arg {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : one_hom M N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y := congr_arg (fun (x : M) => coe_fn f x) h theorem add_hom.congr_arg {M : Type u_1} {N : Type u_2} [Add M] [Add N] (f : add_hom M N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y := congr_arg (fun (x : M) => coe_fn f x) h theorem add_monoid_hom.congr_arg {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y := congr_arg (fun (x : M) => coe_fn f x) h theorem monoid_with_zero_hom.congr_arg {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) {x : M} {y : M} (h : x = y) : coe_fn f x = coe_fn f y := congr_arg (fun (x : M) => coe_fn f x) h theorem one_hom.coe_inj {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] {f : one_hom M N} {g : one_hom M N} (h : ⇑f = ⇑g) : f = g := sorry theorem mul_hom.coe_inj {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] {f : mul_hom M N} {g : mul_hom M N} (h : ⇑f = ⇑g) : f = g := sorry theorem add_monoid_hom.coe_inj {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} (h : ⇑f = ⇑g) : f = g := sorry theorem monoid_with_zero_hom.coe_inj {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} (h : ⇑f = ⇑g) : f = g := sorry theorem zero_hom.ext {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] {f : zero_hom M N} {g : zero_hom M N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g := zero_hom.coe_inj (funext h) theorem mul_hom.ext {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] {f : mul_hom M N} {g : mul_hom M N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g := mul_hom.coe_inj (funext h) theorem add_monoid_hom.ext {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g := add_monoid_hom.coe_inj (funext h) theorem monoid_with_zero_hom.ext {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} (h : ∀ (x : M), coe_fn f x = coe_fn g x) : f = g := monoid_with_zero_hom.coe_inj (funext h) theorem zero_hom.ext_iff {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] {f : zero_hom M N} {g : zero_hom M N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => zero_hom.ext h } theorem mul_hom.ext_iff {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] {f : mul_hom M N} {g : mul_hom M N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => mul_hom.ext h } theorem add_monoid_hom.ext_iff {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {f : M →+ N} {g : M →+ N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => add_monoid_hom.ext h } theorem monoid_with_zero_hom.ext_iff {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] {f : monoid_with_zero_hom M N} {g : monoid_with_zero_hom M N} : f = g ↔ ∀ (x : M), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := fun (h : ∀ (x : M), coe_fn f x = coe_fn g x) => monoid_with_zero_hom.ext h } @[simp] theorem zero_hom.mk_coe {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] (f : zero_hom M N) (h1 : coe_fn f 0 = 0) : zero_hom.mk (⇑f) h1 = f := zero_hom.ext fun (_x : M) => rfl @[simp] theorem mul_hom.mk_coe {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) (hmul : ∀ (x y : M), coe_fn f (x * y) = coe_fn f x * coe_fn f y) : mul_hom.mk (⇑f) hmul = f := mul_hom.ext fun (_x : M) => rfl @[simp] theorem add_monoid_hom.mk_coe {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) (h1 : coe_fn f 0 = 0) (hmul : ∀ (x y : M), coe_fn f (x + y) = coe_fn f x + coe_fn f y) : add_monoid_hom.mk (⇑f) h1 hmul = f := add_monoid_hom.ext fun (_x : M) => rfl @[simp] theorem monoid_with_zero_hom.mk_coe {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) (h0 : coe_fn f 0 = 0) (h1 : coe_fn f 1 = 1) (hmul : ∀ (x y : M), coe_fn f (x * y) = coe_fn f x * coe_fn f y) : monoid_with_zero_hom.mk (⇑f) h0 h1 hmul = f := monoid_with_zero_hom.ext fun (_x : M) => rfl /-- If `f` is a monoid homomorphism then `f 1 = 1`. -/ @[simp] theorem one_hom.map_one {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : one_hom M N) : coe_fn f 1 = 1 := one_hom.map_one' f @[simp] theorem monoid_hom.map_one {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (f : M →* N) : coe_fn f 1 = 1 := monoid_hom.map_one' f @[simp] theorem monoid_with_zero_hom.map_one {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : coe_fn f 1 = 1 := monoid_with_zero_hom.map_one' f /-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/ @[simp] theorem monoid_with_zero_hom.map_zero {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : coe_fn f 0 = 0 := monoid_with_zero_hom.map_zero' f @[simp] theorem mul_hom.map_mul {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) (a : M) (b : M) : coe_fn f (a * b) = coe_fn f a * coe_fn f b := mul_hom.map_mul' f a b /-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/ @[simp] theorem add_monoid_hom.map_add {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) (a : M) (b : M) : coe_fn f (a + b) = coe_fn f a + coe_fn f b := add_monoid_hom.map_add' f a b @[simp] theorem monoid_with_zero_hom.map_mul {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) (a : M) (b : M) : coe_fn f (a * b) = coe_fn f a * coe_fn f b := monoid_with_zero_hom.map_mul' f a b /-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/ namespace monoid_hom theorem Mathlib.add_monoid_hom.map_add_eq_zero {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) {a : M} {b : M} (h : a + b = 0) : coe_fn f a + coe_fn f b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f a + coe_fn f b = 0)) (Eq.symm (add_monoid_hom.map_add f a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f (a + b) = 0)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f 0 = 0)) (add_monoid_hom.map_zero f))) (Eq.refl 0))) /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse, then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/ theorem Mathlib.add_monoid_hom.map_exists_right_neg {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) {x : M} (hx : ∃ (y : M), x + y = 0) : ∃ (y : N), coe_fn f x + y = 0 := sorry /-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/ theorem Mathlib.add_monoid_hom.map_exists_left_neg {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_monoid N} (f : M →+ N) {x : M} (hx : ∃ (y : M), y + x = 0) : ∃ (y : N), y + coe_fn f x = 0 := sorry end monoid_hom /-- The identity map from a type with 1 to itself. -/ def one_hom.id (M : Type u_1) [HasOne M] : one_hom M M := one_hom.mk id sorry /-- The identity map from a type with multiplication to itself. -/ def add_hom.id (M : Type u_1) [Add M] : add_hom M M := add_hom.mk id sorry /-- The identity map from a monoid to itself. -/ def add_monoid_hom.id (M : Type u_1) [add_monoid M] : M →+ M := add_monoid_hom.mk id sorry sorry /-- The identity map from a monoid_with_zero to itself. -/ def monoid_with_zero_hom.id (M : Type u_1) [monoid_with_zero M] : monoid_with_zero_hom M M := monoid_with_zero_hom.mk id sorry sorry sorry /-- The identity map from an type with zero to itself. -/ /-- The identity map from an type with addition to itself. -/ /-- The identity map from an additive monoid to itself. -/ @[simp] theorem zero_hom.id_apply {M : Type u_1} [HasZero M] (x : M) : coe_fn (zero_hom.id M) x = x := rfl @[simp] theorem mul_hom.id_apply {M : Type u_1} [Mul M] (x : M) : coe_fn (mul_hom.id M) x = x := rfl @[simp] theorem monoid_hom.id_apply {M : Type u_1} [monoid M] (x : M) : coe_fn (monoid_hom.id M) x = x := rfl @[simp] theorem monoid_with_zero_hom.id_apply {M : Type u_1} [monoid_with_zero M] (x : M) : coe_fn (monoid_with_zero_hom.id M) x = x := rfl /-- Composition of `one_hom`s as a `one_hom`. -/ def zero_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] (hnp : zero_hom N P) (hmn : zero_hom M N) : zero_hom M P := zero_hom.mk (⇑hnp ∘ ⇑hmn) sorry /-- Composition of `mul_hom`s as a `mul_hom`. -/ def mul_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [Mul M] [Mul N] [Mul P] (hnp : mul_hom N P) (hmn : mul_hom M N) : mul_hom M P := mul_hom.mk (⇑hnp ∘ ⇑hmn) sorry /-- Composition of monoid morphisms as a monoid morphism. -/ def monoid_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] (hnp : N →* P) (hmn : M →* N) : M →* P := monoid_hom.mk (⇑hnp ∘ ⇑hmn) sorry sorry /-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/ def monoid_with_zero_hom.comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] (hnp : monoid_with_zero_hom N P) (hmn : monoid_with_zero_hom M N) : monoid_with_zero_hom M P := monoid_with_zero_hom.mk (⇑hnp ∘ ⇑hmn) sorry sorry sorry /-- Composition of `zero_hom`s as a `zero_hom`. -/ /-- Composition of `add_hom`s as a `add_hom`. -/ /-- Composition of additive monoid morphisms as an additive monoid morphism. -/ @[simp] theorem one_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] (g : one_hom N P) (f : one_hom M N) : ⇑(one_hom.comp g f) = ⇑g ∘ ⇑f := rfl @[simp] theorem add_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [Add M] [Add N] [Add P] (g : add_hom N P) (f : add_hom M N) : ⇑(add_hom.comp g f) = ⇑g ∘ ⇑f := rfl @[simp] theorem add_monoid_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_monoid N] [add_monoid P] (g : N →+ P) (f : M →+ N) : ⇑(add_monoid_hom.comp g f) = ⇑g ∘ ⇑f := rfl @[simp] theorem monoid_with_zero_hom.coe_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] (g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) : ⇑(monoid_with_zero_hom.comp g f) = ⇑g ∘ ⇑f := rfl theorem one_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] (g : one_hom N P) (f : one_hom M N) (x : M) : coe_fn (one_hom.comp g f) x = coe_fn g (coe_fn f x) := rfl theorem add_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [Add M] [Add N] [Add P] (g : add_hom N P) (f : add_hom M N) (x : M) : coe_fn (add_hom.comp g f) x = coe_fn g (coe_fn f x) := rfl theorem monoid_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] (g : N →* P) (f : M →* N) (x : M) : coe_fn (monoid_hom.comp g f) x = coe_fn g (coe_fn f x) := rfl theorem monoid_with_zero_hom.comp_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] (g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) (x : M) : coe_fn (monoid_with_zero_hom.comp g f) x = coe_fn g (coe_fn f x) := rfl /-- Composition of monoid homomorphisms is associative. -/ theorem zero_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [HasZero M] [HasZero N] [HasZero P] [HasZero Q] (f : zero_hom M N) (g : zero_hom N P) (h : zero_hom P Q) : zero_hom.comp (zero_hom.comp h g) f = zero_hom.comp h (zero_hom.comp g f) := rfl theorem mul_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [Mul M] [Mul N] [Mul P] [Mul Q] (f : mul_hom M N) (g : mul_hom N P) (h : mul_hom P Q) : mul_hom.comp (mul_hom.comp h g) f = mul_hom.comp h (mul_hom.comp g f) := rfl theorem add_monoid_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [add_monoid M] [add_monoid N] [add_monoid P] [add_monoid Q] (f : M →+ N) (g : N →+ P) (h : P →+ Q) : add_monoid_hom.comp (add_monoid_hom.comp h g) f = add_monoid_hom.comp h (add_monoid_hom.comp g f) := rfl theorem monoid_with_zero_hom.comp_assoc {M : Type u_1} {N : Type u_2} {P : Type u_3} {Q : Type u_4} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] [monoid_with_zero Q] (f : monoid_with_zero_hom M N) (g : monoid_with_zero_hom N P) (h : monoid_with_zero_hom P Q) : monoid_with_zero_hom.comp (monoid_with_zero_hom.comp h g) f = monoid_with_zero_hom.comp h (monoid_with_zero_hom.comp g f) := rfl theorem one_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] {g₁ : one_hom N P} {g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective ⇑f) : one_hom.comp g₁ f = one_hom.comp g₂ f ↔ g₁ = g₂ := sorry theorem add_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [Add M] [Add N] [Add P] {g₁ : add_hom N P} {g₂ : add_hom N P} {f : add_hom M N} (hf : function.surjective ⇑f) : add_hom.comp g₁ f = add_hom.comp g₂ f ↔ g₁ = g₂ := sorry theorem add_monoid_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_monoid N] [add_monoid P] {g₁ : N →+ P} {g₂ : N →+ P} {f : M →+ N} (hf : function.surjective ⇑f) : add_monoid_hom.comp g₁ f = add_monoid_hom.comp g₂ f ↔ g₁ = g₂ := sorry theorem monoid_with_zero_hom.cancel_right {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] {g₁ : monoid_with_zero_hom N P} {g₂ : monoid_with_zero_hom N P} {f : monoid_with_zero_hom M N} (hf : function.surjective ⇑f) : monoid_with_zero_hom.comp g₁ f = monoid_with_zero_hom.comp g₂ f ↔ g₁ = g₂ := sorry theorem one_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasOne M] [HasOne N] [HasOne P] {g : one_hom N P} {f₁ : one_hom M N} {f₂ : one_hom M N} (hg : function.injective ⇑g) : one_hom.comp g f₁ = one_hom.comp g f₂ ↔ f₁ = f₂ := sorry theorem add_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] {g : zero_hom N P} {f₁ : zero_hom M N} {f₂ : zero_hom M N} (hg : function.injective ⇑g) : zero_hom.comp g f₁ = zero_hom.comp g f₂ ↔ f₁ = f₂ := sorry theorem monoid_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] {g : N →* P} {f₁ : M →* N} {f₂ : M →* N} (hg : function.injective ⇑g) : monoid_hom.comp g f₁ = monoid_hom.comp g f₂ ↔ f₁ = f₂ := sorry theorem monoid_with_zero_hom.cancel_left {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] {g : monoid_with_zero_hom N P} {f₁ : monoid_with_zero_hom M N} {f₂ : monoid_with_zero_hom M N} (hg : function.injective ⇑g) : monoid_with_zero_hom.comp g f₁ = monoid_with_zero_hom.comp g f₂ ↔ f₁ = f₂ := sorry @[simp] theorem one_hom.comp_id {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (f : one_hom M N) : one_hom.comp f (one_hom.id M) = f := one_hom.ext fun (x : M) => rfl @[simp] theorem mul_hom.comp_id {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) : mul_hom.comp f (mul_hom.id M) = f := mul_hom.ext fun (x : M) => rfl @[simp] theorem add_monoid_hom.comp_id {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (f : M →+ N) : add_monoid_hom.comp f (add_monoid_hom.id M) = f := add_monoid_hom.ext fun (x : M) => rfl @[simp] theorem monoid_with_zero_hom.comp_id {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : monoid_with_zero_hom.comp f (monoid_with_zero_hom.id M) = f := monoid_with_zero_hom.ext fun (x : M) => rfl @[simp] theorem zero_hom.id_comp {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] (f : zero_hom M N) : zero_hom.comp (zero_hom.id N) f = f := zero_hom.ext fun (x : M) => rfl @[simp] theorem mul_hom.id_comp {M : Type u_1} {N : Type u_2} [Mul M] [Mul N] (f : mul_hom M N) : mul_hom.comp (mul_hom.id N) f = f := mul_hom.ext fun (x : M) => rfl @[simp] theorem monoid_hom.id_comp {M : Type u_1} {N : Type u_2} [monoid M] [monoid N] (f : M →* N) : monoid_hom.comp (monoid_hom.id N) f = f := monoid_hom.ext fun (x : M) => rfl @[simp] theorem monoid_with_zero_hom.id_comp {M : Type u_1} {N : Type u_2} [monoid_with_zero M] [monoid_with_zero N] (f : monoid_with_zero_hom M N) : monoid_with_zero_hom.comp (monoid_with_zero_hom.id N) f = f := monoid_with_zero_hom.ext fun (x : M) => rfl namespace monoid /-- The monoid of endomorphisms. -/ protected def End (M : Type u_1) [monoid M] := M →* M namespace End protected instance monoid (M : Type u_1) [monoid M] : monoid (monoid.End M) := mk monoid_hom.comp sorry (monoid_hom.id M) monoid_hom.id_comp monoid_hom.comp_id protected instance inhabited (M : Type u_1) [monoid M] : Inhabited (monoid.End M) := { default := 1 } protected instance has_coe_to_fun (M : Type u_1) [monoid M] : has_coe_to_fun (monoid.End M) := has_coe_to_fun.mk (fun (x : monoid.End M) => M → M) monoid_hom.to_fun end End @[simp] theorem coe_one (M : Type u_1) [monoid M] : ⇑1 = id := rfl @[simp] theorem coe_mul (M : Type u_1) [monoid M] (f : monoid.End M) (g : monoid.End M) : ⇑(f * g) = ⇑f ∘ ⇑g := rfl end monoid namespace add_monoid /-- The monoid of endomorphisms. -/ protected def End (A : Type u_6) [add_monoid A] := A →+ A namespace End protected instance monoid (A : Type u_6) [add_monoid A] : monoid (add_monoid.End A) := monoid.mk add_monoid_hom.comp sorry (add_monoid_hom.id A) add_monoid_hom.id_comp add_monoid_hom.comp_id protected instance inhabited (A : Type u_6) [add_monoid A] : Inhabited (add_monoid.End A) := { default := 1 } protected instance has_coe_to_fun (A : Type u_6) [add_monoid A] : has_coe_to_fun (add_monoid.End A) := has_coe_to_fun.mk (fun (x : add_monoid.End A) => A → A) add_monoid_hom.to_fun end End @[simp] theorem coe_one (A : Type u_6) [add_monoid A] : ⇑1 = id := rfl @[simp] theorem coe_mul (A : Type u_6) [add_monoid A] (f : add_monoid.End A) (g : add_monoid.End A) : ⇑(f * g) = ⇑f ∘ ⇑g := rfl end add_monoid /-- `1` is the homomorphism sending all elements to `1`. -/ /-- `1` is the multiplicative homomorphism sending all elements to `1`. -/ protected instance zero_hom.has_zero {M : Type u_1} {N : Type u_2} [HasZero M] [HasZero N] : HasZero (zero_hom M N) := { zero := zero_hom.mk (fun (_x : M) => 0) sorry } /-- `1` is the monoid homomorphism sending all elements to `1`. -/ protected instance add_hom.has_zero {M : Type u_1} {N : Type u_2} [Add M] [add_monoid N] : HasZero (add_hom M N) := { zero := add_hom.mk (fun (_x : M) => 0) sorry } protected instance add_monoid_hom.has_zero {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] : HasZero (M →+ N) := { zero := add_monoid_hom.mk (fun (_x : M) => 0) sorry sorry } /-- `0` is the homomorphism sending all elements to `0`. -/ /-- `0` is the additive homomorphism sending all elements to `0`. -/ /-- `0` is the additive monoid homomorphism sending all elements to `0`. -/ @[simp] theorem one_hom.one_apply {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] (x : M) : coe_fn 1 x = 1 := rfl @[simp] theorem add_monoid_hom.zero_apply {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] (x : M) : coe_fn 0 x = 0 := rfl @[simp] theorem zero_hom.zero_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] (f : zero_hom M N) : zero_hom.comp 0 f = 0 := rfl @[simp] theorem zero_hom.comp_zero {M : Type u_1} {N : Type u_2} {P : Type u_3} [HasZero M] [HasZero N] [HasZero P] (f : zero_hom N P) : zero_hom.comp f 0 = 0 := sorry protected instance one_hom.inhabited {M : Type u_1} {N : Type u_2} [HasOne M] [HasOne N] : Inhabited (one_hom M N) := { default := 1 } protected instance add_hom.inhabited {M : Type u_1} {N : Type u_2} [Add M] [add_monoid N] : Inhabited (add_hom M N) := { default := 0 } -- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0` protected instance add_monoid_hom.inhabited {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] : Inhabited (M →+ N) := { default := 0 } protected instance monoid_with_zero_hom.inhabited {M : Type u_1} [monoid_with_zero M] : Inhabited (monoid_with_zero_hom M M) := { default := monoid_with_zero_hom.id M } namespace monoid_hom /-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism sending `x` to `f x * g x`. -/ protected instance has_mul {M : Type u_1} {N : Type u_2} {mM : monoid M} [comm_monoid N] : Mul (M →* N) := { mul := fun (f g : M →* N) => mk (fun (m : M) => coe_fn f m * coe_fn g m) sorry sorry } /-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the additive monoid morphism sending `x` to `f x + g x`. -/ @[simp] theorem Mathlib.add_monoid_hom.add_apply {M : Type u_1} {N : Type u_2} {mM : add_monoid M} {mN : add_comm_monoid N} (f : M →+ N) (g : M →+ N) (x : M) : coe_fn (f + g) x = coe_fn f x + coe_fn g x := rfl @[simp] theorem one_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [monoid N] [monoid P] (f : M →* N) : comp 1 f = 1 := rfl @[simp] theorem Mathlib.add_monoid_hom.comp_zero {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_monoid N] [add_monoid P] (f : N →+ P) : add_monoid_hom.comp f 0 = 0 := sorry theorem mul_comp {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [comm_monoid N] [comm_monoid P] (g₁ : N →* P) (g₂ : N →* P) (f : M →* N) : comp (g₁ * g₂) f = comp g₁ f * comp g₂ f := rfl theorem comp_mul {M : Type u_1} {N : Type u_2} {P : Type u_3} [monoid M] [comm_monoid N] [comm_monoid P] (g : N →* P) (f₁ : M →* N) (f₂ : M →* N) : comp g (f₁ * f₂) = comp g f₁ * comp g f₂ := sorry /-- (M →* N) is a comm_monoid if N is commutative. -/ protected instance comm_monoid {M : Type u_1} {N : Type u_2} [monoid M] [comm_monoid N] : comm_monoid (M →* N) := comm_monoid.mk Mul.mul sorry 1 sorry sorry sorry /-- `flip` arguments of `f : M →* N →* P` -/ def Mathlib.add_monoid_hom.flip {M : Type u_1} {N : Type u_2} {P : Type u_3} {mM : add_monoid M} {mN : add_monoid N} {mP : add_comm_monoid P} (f : M →+ N →+ P) : N →+ M →+ P := add_monoid_hom.mk (fun (y : N) => add_monoid_hom.mk (fun (x : M) => coe_fn (coe_fn f x) y) sorry sorry) sorry sorry @[simp] theorem flip_apply {M : Type u_1} {N : Type u_2} {P : Type u_3} {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) (x : M) (y : N) : coe_fn (coe_fn (flip f) y) x = coe_fn (coe_fn f x) y := rfl /-- Evaluation of a `monoid_hom` at a point as a monoid homomorphism. See also `monoid_hom.apply` for the evaluation of any function at a point. -/ def Mathlib.add_monoid_hom.eval {M : Type u_1} {N : Type u_2} [add_monoid M] [add_comm_monoid N] : M →+ (M →+ N) →+ N := add_monoid_hom.flip (add_monoid_hom.id (M →+ N)) @[simp] theorem Mathlib.add_monoid_hom.eval_apply {M : Type u_1} {N : Type u_2} [add_monoid M] [add_comm_monoid N] (x : M) (f : M →+ N) : coe_fn (coe_fn add_monoid_hom.eval x) f = coe_fn f x := rfl /-- Composition of monoid morphisms (`monoid_hom.comp`) as a monoid morphism. -/ def Mathlib.add_monoid_hom.comp_hom {M : Type u_1} {N : Type u_2} {P : Type u_3} [add_monoid M] [add_comm_monoid N] [add_comm_monoid P] : (N →+ P) →+ (M →+ N) →+ M →+ P := add_monoid_hom.mk (fun (g : N →+ P) => add_monoid_hom.mk (add_monoid_hom.comp g) sorry (add_monoid_hom.comp_add g)) sorry sorry /-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/ theorem eq_on_inv {M : Type u_1} {G : Type u_2} [group G] [monoid M] {f : G →* M} {g : G →* M} {x : G} (h : coe_fn f x = coe_fn g x) : coe_fn f (x⁻¹) = coe_fn g (x⁻¹) := left_inv_eq_right_inv (map_mul_eq_one f (inv_mul_self x)) (Eq.subst (Eq.symm h) (map_mul_eq_one g) (mul_inv_self x)) /-- Group homomorphisms preserve inverse. -/ @[simp] theorem Mathlib.add_monoid_hom.map_neg {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G →+ H) (g : G) : coe_fn f (-g) = -coe_fn f g := eq_neg_of_add_eq_zero (add_monoid_hom.map_add_eq_zero f (neg_add_self g)) /-- Group homomorphisms preserve division. -/ @[simp] theorem Mathlib.add_monoid_hom.map_add_neg {G : Type u_1} {H : Type u_2} [add_group G] [add_group H] (f : G →+ H) (g : G) (h : G) : coe_fn f (g + -h) = coe_fn f g + -coe_fn f h := sorry /-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. -/ theorem injective_iff {G : Type u_1} {H : Type u_2} [group G] [monoid H] (f : G →* H) : function.injective ⇑f ↔ ∀ (a : G), coe_fn f a = 1 → a = 1 := sorry /-- Makes a group homomorphism from a proof that the map preserves multiplication. -/ def Mathlib.add_monoid_hom.mk' {M : Type u_1} {G : Type u_4} [mM : add_monoid M] [add_group G] (f : M → G) (map_mul : ∀ (a b : M), f (a + b) = f a + f b) : M →+ G := add_monoid_hom.mk f sorry map_mul @[simp] theorem Mathlib.add_monoid_hom.coe_mk' {M : Type u_1} {G : Type u_4} [mM : add_monoid M] [add_group G] {f : M → G} (map_mul : ∀ (a b : M), f (a + b) = f a + f b) : ⇑(add_monoid_hom.mk' f map_mul) = f := rfl /-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`. -/ def of_map_mul_inv {G : Type u_4} [group G] {H : Type u_1} [group H] (f : G → H) (map_div : ∀ (a b : G), f (a * (b⁻¹)) = f a * (f b⁻¹)) : G →* H := mk' f sorry @[simp] theorem Mathlib.add_monoid_hom.coe_of_map_add_neg {G : Type u_4} [add_group G] {H : Type u_1} [add_group H] (f : G → H) (map_div : ∀ (a b : G), f (a + -b) = f a + -f b) : ⇑(add_monoid_hom.of_map_add_neg f map_div) = f := rfl /-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending `x` to `(f x)⁻¹`. -/ protected instance Mathlib.add_monoid_hom.has_neg {M : Type u_1} {G : Type u_2} [add_monoid M] [add_comm_group G] : Neg (M →+ G) := { neg := fun (f : M →+ G) => add_monoid_hom.mk' (fun (g : M) => -coe_fn f g) sorry } /-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the homomorphism sending `x` to `-(f x)`. -/ @[simp] theorem inv_apply {M : Type u_1} {G : Type u_2} {mM : monoid M} {gG : comm_group G} (f : M →* G) (x : M) : coe_fn (f⁻¹) x = (coe_fn f x⁻¹) := rfl /-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism sending `x` to `(f x) / (g x). -/ protected instance has_div {M : Type u_1} {G : Type u_2} [monoid M] [comm_group G] : Div (M →* G) := { div := fun (f g : M →* G) => mk' (fun (x : M) => coe_fn f x / coe_fn g x) sorry } /-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g` is the homomorphism sending `x` to `(f x) - (g x). -/ @[simp] theorem Mathlib.add_monoid_hom.sub_apply {M : Type u_1} {G : Type u_2} {mM : add_monoid M} {gG : add_comm_group G} (f : M →+ G) (g : M →+ G) (x : M) : coe_fn (f - g) x = coe_fn f x - coe_fn g x := rfl /-- If `G` is a commutative group, then `M →* G` a commutative group too. -/ protected instance Mathlib.add_monoid_hom.add_comm_group {M : Type u_1} {G : Type u_2} [add_monoid M] [add_comm_group G] : add_comm_group (M →+ G) := add_comm_group.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry Neg.neg Sub.sub sorry sorry /-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/ end monoid_hom namespace add_monoid_hom /-- Additive group homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {G : Type u_4} {H : Type u_5} [add_group G] [add_group H] (f : G →+ H) (g : G) (h : G) : coe_fn f (g - h) = coe_fn f g - coe_fn f h := sorry /-- Define a morphism of additive groups given a map which respects difference. -/ def of_map_sub {G : Type u_4} {H : Type u_5} [add_group G] [add_group H] (f : G → H) (hf : ∀ (x y : G), f (x - y) = f x - f y) : G →+ H := of_map_add_neg f sorry @[simp] theorem coe_of_map_sub {G : Type u_4} {H : Type u_5} [add_group G] [add_group H] (f : G → H) (hf : ∀ (x y : G), f (x - y) = f x - f y) : ⇑(of_map_sub f hf) = f := rfl end add_monoid_hom @[simp] protected theorem add_semiconj_by.map {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {a : M} {x : M} {y : M} (h : add_semiconj_by a x y) (f : M →+ N) : add_semiconj_by (coe_fn f a) (coe_fn f x) (coe_fn f y) := sorry @[simp] protected theorem add_commute.map {M : Type u_1} {N : Type u_2} [add_monoid M] [add_monoid N] {x : M} {y : M} (h : add_commute x y) (f : M →+ N) : add_commute (coe_fn f x) (coe_fn f y) := add_semiconj_by.map h f end Mathlib
53c7ad3bbe93334ce7abc52730af36387f9d6f62
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Ringoid1Sig.lean
07549a680f042324e3ead30195e996cd4cc280f0
[]
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
9,531
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 Ringoid1Sig structure Ringoid1Sig (A : Type) : Type := (times : (A → (A → A))) (one : A) (plus : (A → (A → A))) open Ringoid1Sig structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (oneS : AS) (plusS : (AS → (AS → 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)))) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (Ringoid1Sig A1)) (Ri2 : (Ringoid1Sig A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Ri1) x1 x2)) = ((times Ri2) (hom x1) (hom x2)))) (pres_one : (hom (one Ri1)) = (one Ri2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ri1) x1 x2)) = ((plus Ri2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (Ringoid1Sig A1)) (Ri2 : (Ringoid1Sig A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Ri1) x1 x2) ((times Ri2) y1 y2)))))) (interp_one : (interp (one Ri1) (one Ri2))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ri1) x1 x2) ((plus Ri2) y1 y2)))))) inductive Ringoid1SigTerm : Type | timesL : (Ringoid1SigTerm → (Ringoid1SigTerm → Ringoid1SigTerm)) | oneL : Ringoid1SigTerm | plusL : (Ringoid1SigTerm → (Ringoid1SigTerm → Ringoid1SigTerm)) open Ringoid1SigTerm inductive ClRingoid1SigTerm (A : Type) : Type | sing : (A → ClRingoid1SigTerm) | timesCl : (ClRingoid1SigTerm → (ClRingoid1SigTerm → ClRingoid1SigTerm)) | oneCl : ClRingoid1SigTerm | plusCl : (ClRingoid1SigTerm → (ClRingoid1SigTerm → ClRingoid1SigTerm)) open ClRingoid1SigTerm inductive OpRingoid1SigTerm (n : ℕ) : Type | v : ((fin n) → OpRingoid1SigTerm) | timesOL : (OpRingoid1SigTerm → (OpRingoid1SigTerm → OpRingoid1SigTerm)) | oneOL : OpRingoid1SigTerm | plusOL : (OpRingoid1SigTerm → (OpRingoid1SigTerm → OpRingoid1SigTerm)) open OpRingoid1SigTerm inductive OpRingoid1SigTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRingoid1SigTerm2) | sing2 : (A → OpRingoid1SigTerm2) | timesOL2 : (OpRingoid1SigTerm2 → (OpRingoid1SigTerm2 → OpRingoid1SigTerm2)) | oneOL2 : OpRingoid1SigTerm2 | plusOL2 : (OpRingoid1SigTerm2 → (OpRingoid1SigTerm2 → OpRingoid1SigTerm2)) open OpRingoid1SigTerm2 def simplifyCl {A : Type} : ((ClRingoid1SigTerm A) → (ClRingoid1SigTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | oneCl := oneCl | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRingoid1SigTerm n) → (OpRingoid1SigTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | oneOL := oneOL | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRingoid1SigTerm2 n A) → (OpRingoid1SigTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | oneOL2 := oneOL2 | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Ringoid1Sig A) → (Ringoid1SigTerm → A)) | Ri (timesL x1 x2) := ((times Ri) (evalB Ri x1) (evalB Ri x2)) | Ri oneL := (one Ri) | Ri (plusL x1 x2) := ((plus Ri) (evalB Ri x1) (evalB Ri x2)) def evalCl {A : Type} : ((Ringoid1Sig A) → ((ClRingoid1SigTerm A) → A)) | Ri (sing x1) := x1 | Ri (timesCl x1 x2) := ((times Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri oneCl := (one Ri) | Ri (plusCl x1 x2) := ((plus Ri) (evalCl Ri x1) (evalCl Ri x2)) def evalOpB {A : Type} {n : ℕ} : ((Ringoid1Sig A) → ((vector A n) → ((OpRingoid1SigTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (timesOL x1 x2) := ((times Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars oneOL := (one Ri) | Ri vars (plusOL x1 x2) := ((plus Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) def evalOp {A : Type} {n : ℕ} : ((Ringoid1Sig A) → ((vector A n) → ((OpRingoid1SigTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (timesOL2 x1 x2) := ((times Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars oneOL2 := (one Ri) | Ri vars (plusOL2 x1 x2) := ((plus Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) def inductionB {P : (Ringoid1SigTerm → Type)} : ((∀ (x1 x2 : Ringoid1SigTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((P oneL) → ((∀ (x1 x2 : Ringoid1SigTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : Ringoid1SigTerm) , (P x))))) | ptimesl p1l pplusl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl p1l pplusl x1) (inductionB ptimesl p1l pplusl x2)) | ptimesl p1l pplusl oneL := p1l | ptimesl p1l pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl p1l pplusl x1) (inductionB ptimesl p1l pplusl x2)) def inductionCl {A : Type} {P : ((ClRingoid1SigTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRingoid1SigTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((P oneCl) → ((∀ (x1 x2 : (ClRingoid1SigTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClRingoid1SigTerm A)) , (P x)))))) | psing ptimescl p1cl ppluscl (sing x1) := (psing x1) | psing ptimescl p1cl ppluscl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl p1cl ppluscl x1) (inductionCl psing ptimescl p1cl ppluscl x2)) | psing ptimescl p1cl ppluscl oneCl := p1cl | psing ptimescl p1cl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl p1cl ppluscl x1) (inductionCl psing ptimescl p1cl ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpRingoid1SigTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRingoid1SigTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((P oneOL) → ((∀ (x1 x2 : (OpRingoid1SigTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpRingoid1SigTerm n)) , (P x)))))) | pv ptimesol p1ol pplusol (v x1) := (pv x1) | pv ptimesol p1ol pplusol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol p1ol pplusol x1) (inductionOpB pv ptimesol p1ol pplusol x2)) | pv ptimesol p1ol pplusol oneOL := p1ol | pv ptimesol p1ol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol p1ol pplusol x1) (inductionOpB pv ptimesol p1ol pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpRingoid1SigTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRingoid1SigTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((P oneOL2) → ((∀ (x1 x2 : (OpRingoid1SigTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpRingoid1SigTerm2 n A)) , (P x))))))) | pv2 psing2 ptimesol2 p1ol2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 p1ol2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 p1ol2 pplusol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 x2)) | pv2 psing2 ptimesol2 p1ol2 pplusol2 oneOL2 := p1ol2 | pv2 psing2 ptimesol2 p1ol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 p1ol2 pplusol2 x2)) def stageB : (Ringoid1SigTerm → (Staged Ringoid1SigTerm)) | (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)) def stageCl {A : Type} : ((ClRingoid1SigTerm A) → (Staged (ClRingoid1SigTerm 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)) def stageOpB {n : ℕ} : ((OpRingoid1SigTerm n) → (Staged (OpRingoid1SigTerm 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)) def stageOp {n : ℕ} {A : Type} : ((OpRingoid1SigTerm2 n A) → (Staged (OpRingoid1SigTerm2 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)) 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)))) end Ringoid1Sig
302d0bfcdc68aa0324a0ffa8ff1138d49df91c72
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-22.lean
5bfa8df6a5fb52a8e84a70698c455334bd8ddff6
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
972
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic import analysis.special_functions.exp_log lemma log_inj_on_pos : set.inj_on real.log (set.Ioi 0) := real.strict_mono_incr_on_log.inj_on lemma eq_one_of_pos_of_log_eq_zero {x : ℝ} (h₁ : 0 < x) (h₂ : real.log x = 0) : x = 1 := log_inj_on_pos (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (h₂.trans real.log_one.symm) lemma log_ne_zero_of_pos_of_ne_one {x : ℝ} (hx_pos : 0 < x) (hx : x ≠ 1) : real.log x ≠ 0 := mt (eq_one_of_pos_of_log_eq_zero hx_pos) hx noncomputable def logb (b x : ℝ) : ℝ := real.log x / real.log b example : logb (5^2) (5^4) = 2 := begin rw logb, have h₀ : (5:ℝ)^4 = ((5:ℝ)^2)*((5:ℝ)^2), norm_num, rw h₀, rw real.log_mul, rw div_eq_iff, ring, refine log_ne_zero_of_pos_of_ne_one _ _, linarith, linarith, linarith, linarith, end
abf0cbc67bc35b255d04c8118da604c965e56be9
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/coe.lean
53c67b496bfd9085dc232d764ca080596e80460f
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
5,383
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 -/ /- The elaborator tries to insert coercions automatically. Only instances of has_coe type class are considered in the process. Lean also provides a "lifting" operator: ↑a. It uses all instances of has_lift type class. Every has_coe instance is also a has_lift instance. We recommend users only use has_coe for coercions that do not produce a lot of ambiguity. All coercions and lifts can be identified with the constant coe. We use the has_coe_to_fun type class for encoding coercions from a type to a function space. We use the has_coe_to_sort type class for encoding coercions from a type to a sort. -/ prelude import init.data.list.basic init.data.subtype.basic init.data.prod universe variables u v class has_lift (a : Type u) (b : Type v) := (lift : a → b) /- auxiliary class that contains the transitive closure of has_lift. -/ class has_lift_t (a : Type u) (b : Type v) := (lift : a → b) class has_coe (a : Type u) (b : Type v) := (coe : a → b) /- auxiliary class that contains the transitive closure of has_coe. -/ class has_coe_t (a : Type u) (b : Type v) := (coe : a → b) class has_coe_to_fun (a : Type u) : Type (max u (v+1)) := (F : a → Type v) (coe : Π x, F x) class has_coe_to_sort (a : Type u) : Type (max u (v+1)) := (S : Type v) (coe : a → S) def lift {a : Type u} {b : Type v} [has_lift a b] : a → b := @has_lift.lift a b _ def lift_t {a : Type u} {b : Type v} [has_lift_t a b] : a → b := @has_lift_t.lift a b _ def coe_b {a : Type u} {b : Type v} [has_coe a b] : a → b := @has_coe.coe a b _ def coe_t {a : Type u} {b : Type v} [has_coe_t a b] : a → b := @has_coe_t.coe a b _ def coe_fn_b {a : Type u} [has_coe_to_fun.{u v} a] : Π x : a, has_coe_to_fun.F.{u v} x := has_coe_to_fun.coe /- User level coercion operators -/ @[reducible] def coe {a : Type u} {b : Type v} [has_lift_t a b] : a → b := lift_t @[reducible] def coe_fn {a : Type u} [has_coe_to_fun.{u v} a] : Π x : a, has_coe_to_fun.F.{u v} x := has_coe_to_fun.coe @[reducible] def coe_sort {a : Type u} [has_coe_to_sort.{u v} a] : a → has_coe_to_sort.S.{u v} a := has_coe_to_sort.coe /- Notation -/ notation `↑`:max x:max := coe x notation `⇑`:max x:max := coe_fn x notation `↥`:max x:max := coe_sort x universe variables u₁ u₂ u₃ /- Transitive closure for has_lift, has_coe, has_coe_to_fun -/ instance lift_trans {a : Type u₁} {b : Type u₂} {c : Type u₃} [has_lift a b] [has_lift_t b c] : has_lift_t a c := ⟨λ x, lift_t (lift x : b)⟩ instance lift_base {a : Type u} {b : Type v} [has_lift a b] : has_lift_t a b := ⟨lift⟩ instance coe_trans {a : Type u₁} {b : Type u₂} {c : Type u₃} [has_coe a b] [has_coe_t b c] : has_coe_t a c := ⟨λ x, coe_t (coe_b x : b)⟩ instance coe_base {a : Type u} {b : Type v} [has_coe a b] : has_coe_t a b := ⟨coe_b⟩ instance coe_fn_trans {a : Type u₁} {b : Type u₂} [has_lift_t a b] [has_coe_to_fun.{u₂ u₃} b] : has_coe_to_fun.{u₁ u₃} a := { F := λ x, @has_coe_to_fun.F.{u₂ u₃} b _ (coe x), coe := λ x, coe_fn (coe x) } instance coe_sort_trans {a : Type u₁} {b : Type u₂} [has_lift_t a b] [has_coe_to_sort.{u₂ u₃} b] : has_coe_to_sort.{u₁ u₃} a := { S := has_coe_to_sort.S.{u₂ u₃} b, coe := λ x, coe_sort (coe x) } /- Every coercion is also a lift -/ instance coe_to_lift {a : Type u} {b : Type v} [has_coe_t a b] : has_lift_t a b := ⟨coe_t⟩ /- basic coercions -/ instance coe_bool_to_Prop : has_coe bool Prop := ⟨λ y, y = tt⟩ instance coe_decidable_eq (x : bool) : decidable (coe x) := show decidable (x = tt), from bool.decidable_eq x tt instance coe_subtype {a : Type u} {p : a → Prop} : has_coe {x // p x} a := ⟨λ s, subtype.elt_of s⟩ /- basic lifts -/ universe variables ua ua₁ ua₂ ub ub₁ ub₂ /- Remark: we cant use [has_lift_t a₂ a₁] since it will produce non-termination whenever a type class resolution problem does not have a solution. -/ instance lift_fn {a₁ : Type ua₁} {a₂ : Type ua₂} {b₁ : Type ub₁} {b₂ : Type ub₂} [has_lift a₂ a₁] [has_lift_t b₁ b₂] : has_lift (a₁ → b₁) (a₂ → b₂) := ⟨λ f x, ↑(f ↑x)⟩ instance lift_fn_range {a : Type ua} {b₁ : Type ub₁} {b₂ : Type ub₂} [has_lift_t b₁ b₂] : has_lift (a → b₁) (a → b₂) := ⟨λ f x, ↑(f x)⟩ instance lift_fn_dom {a₁ : Type ua₁} {a₂ : Type ua₂} {b : Type ub} [has_lift a₂ a₁] : has_lift (a₁ → b) (a₂ → b) := ⟨λ f x, f ↑x⟩ instance lift_pair {a₁ : Type ua₁} {a₂ : Type ub₂} {b₁ : Type ub₁} {b₂ : Type ub₂} [has_lift_t a₁ a₂] [has_lift_t b₁ b₂] : has_lift (a₁ × b₁) (a₂ × b₂) := ⟨λ p, prod.cases_on p (λ x y, (↑x, ↑y))⟩ instance lift_pair₁ {a₁ : Type ua₁} {a₂ : Type ua₂} {b : Type ub} [has_lift_t a₁ a₂] : has_lift (a₁ × b) (a₂ × b) := ⟨λ p, prod.cases_on p (λ x y, (↑x, y))⟩ instance lift_pair₂ {a : Type ua} {b₁ : Type ub₁} {b₂ : Type ub₂} [has_lift_t b₁ b₂] : has_lift (a × b₁) (a × b₂) := ⟨λ p, prod.cases_on p (λ x y, (x, ↑y))⟩ instance lift_list {a : Type u} {b : Type v} [has_lift_t a b] : has_lift (list a) (list b) := ⟨λ l, list.map (@coe a b _) l⟩
b85e9b8ca365af7e1375ebfa5256eb02f43dc207
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/793a.lean
b23173eef5854dcc55b4cf78091e1ecd1a39d57c
[ "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
195
lean
import data.rat open rat check (4.0:rat) check (2.3:rat) check (1.00:rat) check (10.213:rat) check -(0.3:rat) check (10.213:rat) check (2.3:rat) check (1.0:rat) eval (λ v, (1.0:rat)) (2:nat)
4b32fa97fbb60b70b300eefbe8f6d0be87aafcf2
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/nat_bug.lean
7d5db5dc55048db0385fcb7912a85aa33e51c9e5
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
865
lean
import logic decidable using decidable inductive nat : Type := | zero : nat | succ : nat → nat theorem induction_on {P : nat → Prop} (a : nat) (H1 : P zero) (H2 : ∀ (n : nat) (IH : P n), P (succ n)) : P a := nat_rec H1 H2 a definition pred (n : nat) := nat_rec zero (fun m x, m) n theorem pred_zero : pred zero = zero := refl _ theorem pred_succ (n : nat) : pred (succ n) = n := refl _ theorem zero_or_succ (n : nat) : n = zero ∨ n = succ (pred n) := induction_on n (or_intro_left _ (refl zero)) (take m IH, or_intro_right _ (show succ m = succ (pred (succ m)), from congr2 succ (symm (pred_succ m)))) theorem zero_or_succ2 (n : nat) : n = zero ∨ n = succ (pred n) := @induction_on _ n (or_intro_left _ (refl zero)) (take m IH, or_intro_right _ (show succ m = succ (pred (succ m)), from congr2 succ (symm (pred_succ m))))
7d87d786c255de97fb1a88b26b85d1a2da3becc6
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/normed_space/weak_dual.lean
84d4943e49221ede46a46db57e24c53af091be46
[ "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
7,016
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import topology.algebra.module.weak_dual import analysis.normed_space.dual import analysis.normed_space.operator_norm /-! # Weak dual of normed space Let `E` be a normed space over a field `𝕜`. This file is concerned with properties of the weak-* topology on the dual of `E`. By the dual, we mean either of the type synonyms `normed_space.dual 𝕜 E` or `weak_dual 𝕜 E`, depending on whether it is viewed as equipped with its usual operator norm topology or the weak-* topology. It is shown that the canonical mapping `normed_space.dual 𝕜 E → weak_dual 𝕜 E` is continuous, and as a consequence the weak-* topology is coarser than the topology obtained from the operator norm (dual norm). The file is a stub, some TODOs below. ## Main definitions The main definitions concern the canonical mapping `dual 𝕜 E → weak_dual 𝕜 E`. * `normed_space.dual.to_weak_dual` and `weak_dual.to_normed_dual`: Linear equivalences from `dual 𝕜 E` to `weak_dual 𝕜 E` and in the converse direction. * `normed_space.dual.continuous_linear_map_to_weak_dual`: A continuous linear mapping from `dual 𝕜 E` to `weak_dual 𝕜 E` (same as `normed_space.dual.to_weak_dual` but different bundled data). ## Main results The first main result concerns the comparison of the operator norm topology on `dual 𝕜 E` and the weak-* topology on (its type synonym) `weak_dual 𝕜 E`: * `dual_norm_topology_le_weak_dual_topology`: The weak-* topology on the dual of a normed space is coarser (not necessarily strictly) than the operator norm topology. TODOs: * Add that in finite dimensions, the weak-* topology and the dual norm topology coincide. * Add that in infinite dimensions, the weak-* topology is strictly coarser than the dual norm topology. * Add Banach-Alaoglu theorem (general version maybe in `topology.algebra.module.weak_dual`). * Add metrizability of the dual unit ball (more generally bounded subsets) of `weak_dual 𝕜 E` under the assumption of separability of `E`. Sequential Banach-Alaoglu theorem would then follow from the general one. ## Notations No new notation is introduced. ## Implementation notes Weak-* topology is defined generally in the file `topology.algebra.module.weak_dual`. When `E` is a normed space, the duals `dual 𝕜 E` and `weak_dual 𝕜 E` are type synonyms with different topology instances. ## References * https://en.wikipedia.org/wiki/Weak_topology#Weak-*_topology ## Tags weak-star, weak dual -/ noncomputable theory open filter open_locale topological_space section weak_star_topology_for_duals_of_normed_spaces /-! ### Weak star topology on duals of normed spaces In this section, we prove properties about the weak-* topology on duals of normed spaces. We prove in particular that the canonical mapping `dual 𝕜 E → weak_dual 𝕜 E` is continuous, i.e., that the weak-* topology is coarser (not necessarily strictly) than the topology given by the dual-norm (i.e. the operator-norm). -/ open normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- For normed spaces `E`, there is a canonical map `dual 𝕜 E → weak_dual 𝕜 E` (the "identity" mapping). It is a linear equivalence. -/ def normed_space.dual.to_weak_dual : dual 𝕜 E ≃ₗ[𝕜] weak_dual 𝕜 E := linear_equiv.refl 𝕜 (E →L[𝕜] 𝕜) /-- For normed spaces `E`, there is a canonical map `weak_dual 𝕜 E → dual 𝕜 E` (the "identity" mapping). It is a linear equivalence. Here it is implemented as the inverse of the linear equivalence `normed_space.dual.to_weak_dual` in the other direction. -/ def weak_dual.to_normed_dual : weak_dual 𝕜 E ≃ₗ[𝕜] dual 𝕜 E := normed_space.dual.to_weak_dual.symm @[simp] lemma weak_dual.coe_to_fun_eq_normed_coe_to_fun (x' : dual 𝕜 E) : (x'.to_weak_dual : E → 𝕜) = x' := rfl namespace normed_space.dual @[simp] lemma to_weak_dual_eq_iff (x' y' : dual 𝕜 E) : x'.to_weak_dual = y'.to_weak_dual ↔ x' = y' := to_weak_dual.injective.eq_iff @[simp] lemma _root_.weak_dual.to_normed_dual_eq_iff (x' y' : weak_dual 𝕜 E) : x'.to_normed_dual = y'.to_normed_dual ↔ x' = y' := weak_dual.to_normed_dual.injective.eq_iff theorem to_weak_dual_continuous : continuous (λ (x' : dual 𝕜 E), x'.to_weak_dual) := begin apply weak_dual.continuous_of_continuous_eval, intros z, exact (inclusion_in_double_dual 𝕜 E z).continuous, end /-- For a normed space `E`, according to `to_weak_dual_continuous` the "identity mapping" `dual 𝕜 E → weak_dual 𝕜 E` is continuous. This definition implements it as a continuous linear map. -/ def continuous_linear_map_to_weak_dual : dual 𝕜 E →L[𝕜] weak_dual 𝕜 E := { cont := to_weak_dual_continuous, .. to_weak_dual, } /-- The weak-star topology is coarser than the dual-norm topology. -/ theorem dual_norm_topology_le_weak_dual_topology : (by apply_instance : topological_space (dual 𝕜 E)) ≤ (by apply_instance : topological_space (weak_dual 𝕜 E)) := begin refine continuous.le_induced _, apply continuous_pi_iff.mpr, intros z, exact (inclusion_in_double_dual 𝕜 E z).continuous, end end normed_space.dual namespace weak_dual lemma to_normed_dual.preimage_closed_unit_ball : (to_normed_dual ⁻¹' metric.closed_ball (0 : dual 𝕜 E) 1) = {x' : weak_dual 𝕜 E | ∥ x'.to_normed_dual ∥ ≤ 1} := begin have eq : metric.closed_ball (0 : dual 𝕜 E) 1 = {x' : dual 𝕜 E | ∥ x' ∥ ≤ 1}, { ext x', simp only [dist_zero_right, metric.mem_closed_ball, set.mem_set_of_eq], }, rw eq, exact set.preimage_set_of_eq, end variables (𝕜) /-- The polar set `polar 𝕜 s` of `s : set E` seen as a subset of the dual of `E` with the weak-star topology is `weak_dual.polar 𝕜 s`. -/ def polar (s : set E) : set (weak_dual 𝕜 E) := to_normed_dual ⁻¹' (polar 𝕜 s) end weak_dual end weak_star_topology_for_duals_of_normed_spaces section polar_sets_in_weak_dual open metric set normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- The polar `polar 𝕜 s` of a set `s : E` is a closed subset when the weak star topology is used, i.e., when `polar 𝕜 s` is interpreted as a subset of `weak_dual 𝕜 E`. -/ lemma weak_dual.is_closed_polar (s : set E) : is_closed (weak_dual.polar 𝕜 s) := begin rw [weak_dual.polar, polar_eq_Inter, preimage_Inter₂], apply is_closed_bInter, intros z hz, rw set.preimage_set_of_eq, have eq : {x' : weak_dual 𝕜 E | ∥weak_dual.to_normed_dual x' z∥ ≤ 1} = (λ (x' : weak_dual 𝕜 E), ∥x' z∥)⁻¹' (Iic 1) := by refl, rw eq, refine is_closed.preimage _ (is_closed_Iic), apply continuous.comp continuous_norm (weak_dual.eval_continuous _ _ z), end end polar_sets_in_weak_dual
797e9becfd1446e8e60ac96fe95ed3eff8220fcb
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tst11.lean
25676cc6161164b1d999e36cad5f0083f51ce103
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
353
lean
import tactic definition xor (x y : Bool) : Bool := (not x) = y infixr 50 ⊕ : xor print xor true false variable a : Bool print a ⊕ a ⊕ a check @subst theorem EM2 (a : Bool) : a \/ (not a) := case (fun x : Bool, x \/ (not x)) (by simp) (by simp) a check EM2 check EM2 a theorem xor_neq (a b : Bool) : (a ⊕ b) ↔ ((¬ a) = b) := refl (a ⊕ b)
34ef65aa1490144bd7f7d81f811c33df5e860927
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_2254.lean
96431011bb44fd9e2b52aa940a5e0c69dd82696f
[]
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
181
lean
import data.real.basic -- BEGIN example {a : ℝ} (h : 1 < a) : a < a * a := begin convert (mul_lt_mul_right _).2 h, { rw [one_mul] }, exact lt_trans zero_lt_one h end -- END
2204df65d2f134558c9a0dc2a0d3e71b4824558f
f0f12a5b81106a798deda31dca238c11997a605e
/Playlean4/Group/Action.lean
1beb424bd49065387d8a42ae0dd159595369decd
[ "MIT" ]
permissive
thejohncrafter/playlean4
fe7119d492aab07048f78333eeda9862f6471740
81df180a71b8d84d0f45bc98db367aad203cf5df
refs/heads/master
1,683,152,783,765
1,621,879,382,000
1,621,879,382,000
366,563,501
2
0
null
null
null
null
UTF-8
Lean
false
false
5,813
lean
import Playlean4.Group.Basic import Playlean4.Group.Subgroup namespace Group open Group section variable (G : Type) (law : G → G → G) [grp : Group G law] local infixl:70 " * " => id' law @[appUnexpander id'] def normal.UnexpandGMul : Lean.PrettyPrinter.Unexpander | `(id' law $x $y) => `($x * $y) | _ => throw () local notation "one" => grp.one' -- HACK section variable {X : Type} (elaw : G → X → X) -- External Law local infix:70 " • " => id' elaw @[appUnexpander id'] def unexpandAction : Lean.PrettyPrinter.Unexpander | `(id' elaw $x $y) => `($x * $y) | _ => throw () class Action where identity' : ∀ x : X, one • x = x compat : ∀ (g g' : G) (x : X), (g * g') • x = g • (g' • x) end end section variable {G : Type} {law : G → G → G} [grp : Group G law] local infixl:70 " * " => id' law @[appUnexpander id'] def unexpandGMul : Lean.PrettyPrinter.Unexpander | `(id' Magma.law G $x $y) => `($x * $y) | _ => throw () local notation "one" => grp.one' -- HACK local notation g"⁻¹" => grp.inv g namespace Action section variable {X : Type} {elaw : G → X → X} [action : Action G law elaw] local infix:70 " • " => id' elaw @[appUnexpander id'] def unexpandAction : Lean.PrettyPrinter.Unexpander | `(id' elaw $x $y) => `($x • $y) | _ => throw () @[simp] theorem identity (x : X) : one • x = x := action.identity' x theorem reverseCompat (g g' : G) (x : X) : g • (g' • x) = (g * g') • x := Eq.symm <| action.compat g g' x end end Action end namespace Action variable {G : Type} (law : G → G → G) [grp : Group G law] local infixl:70 " * " => id' law @[appUnexpander id'] def unexpandGMul : Lean.PrettyPrinter.Unexpander | `(id' Magma.law G $x $y) => `($x * $y) | _ => throw () local notation "one" => grp.one' -- HACK local notation g"⁻¹" => grp.inv g section variable {X : Type} (elaw : G → X → X) [action : Action G law elaw] local infix:70 " • " => id' elaw @[appUnexpander id'] def unexpandAction' : Lean.PrettyPrinter.Unexpander | `(id' elaw $x $y) => `($x • $y) | _ => throw () def isStable (Y : Set X) : Prop := ∀ y : X, y ∈ Y → ∀ g : G, g • y ∈ Y def orbit (x : X) : Set X := λ y => ∃ g : G, y = g • x def memOfSelfOrbit (x : X) : x ∈ orbit elaw x := ⟨ one, by simp ⟩ theorem translatorOfMemOfOrbit {x : X} (y : orbit elaw x) : ∃ g : G, y.val = g • x := y.2 theorem orbitIsStable (x : X) : isStable elaw (orbit elaw x) := λ y yIn g => match yIn with | ⟨ g', h ⟩ => ⟨ (g * g'), by rw [h, ← action.compat] ⟩ def stabilizer (x : X) : Set G := λ g => g • x = x class Transitive where singleOrbit : ∀ x y : X, ∃ g : G, y = g • x end namespace Remarkable section def onSelf : G → G → G := id' law instance onSelfIsAction : Action G law (@onSelf G law) where identity' := λ g => by simp [onSelf]; exact grp.oneNeutralLeft _ compat := λ g g' g'' => by simp [onSelf]; exact grp.assoc _ _ _ end variable {X : Type} (elaw : G → X → X) [action : Action G law elaw] local infix:70 " • " => id' elaw @[appUnexpander id'] def unexpandAction : Lean.PrettyPrinter.Unexpander | `(id' elaw $x $y) => `($x • $y) | _ => throw () section def liftToSet : (G → Set X → Set X) := λ (g : G) => Set.img (λ x => g • x) instance actionOnSet : Action G law (liftToSet elaw) where identity' := by intro x simp [liftToSet] funext a exact propext ⟨ (λ h => match h with | ⟨ y, h ⟩ => by rw [h.2]; simp; exact h.1), (λ h => ⟨ a, ⟨ h, by simp ⟩ ⟩) ⟩ compat := by intro g g' x simp [liftToSet] funext a exact propext ⟨ (λ h => match h with | ⟨ y, h ⟩ => ⟨ g' • y, by simp only []; exact (action.compat _ _ _) ▸ ⟨ ⟨ y, ⟨ h.1, rfl ⟩ ⟩, h.2 ⟩ ⟩), (λ h => match h with | ⟨ y₁, ⟨ ⟨ y₂, ⟨ y₂In, (h₁ : y₁ = g' • y₂) ⟩ ⟩, (h₂ : a = g • y₁) ⟩ ⟩ => ⟨ y₂, ⟨ y₂In, by simp only []; exact (action.compat _ _ _).symm ▸ h₁ ▸ h₂ ⟩ ⟩) ⟩ end section variable (Y : Set X) (stable : isStable elaw Y) def restr : G → Y → Y := λ g y => ⟨ g • y.1, stable y.1 y.2 g ⟩ instance restrAction : Action G law (restr elaw Y stable) where identity' := by intro y apply Subtype.eq simp [restr, id', show elaw one y = y from action.identity y] compat := by intro g g' y apply Subtype.eq simp [restr, id', show elaw (law g g') y = elaw g (elaw g' y) from action.compat _ _ _] end section variable (x₀ : X) def onOrbit : G → orbit elaw x₀ → orbit elaw x₀ := restr elaw (orbit elaw x₀) (orbitIsStable law elaw x₀) instance onOrbitTransitive : Transitive (onOrbit law elaw x₀) where singleOrbit := by intro ⟨ x, xIn ⟩ ⟨ y, yIn ⟩ match xIn, yIn with | ⟨ g₁, xIs ⟩, ⟨ g₂, yIs ⟩ => suffices p₂ : y = (g₂ * g₁⁻¹) • x from ⟨ (g₂ * g₁⁻¹), Subtype.eq p₂ ⟩ simp [xIs, yIs, action.reverseCompat] end section def leftTranslation : G → G → G := λ g g' => g * g' instance leftTranslationAction (g : G) : Action G law (leftTranslation law) where identity' := λ x => by simp [id', leftTranslation] exact @oneNeutralLeft G law _ _ compat := λ g g' g'' => by simp [id', leftTranslation] exact @assoc G law _ _ _ _ def conjugation : G → G → G := λ g g' => g * g' * g⁻¹ instance conjugationAction (g : G) : Action G law (conjugation law) where identity' := λ x => by suffices one * x * one⁻¹ = x by exact this simp compat := λ g g' x => by suffices ((g * g') * x * (g * g')⁻¹ = g * (g' * x * g'⁻¹) * g⁻¹) by exact this simp end end Remarkable end Action end Group
73d83643785de2f90bb9257f28c6e640b519498a
6f510b1ed724f95a55b7d26a8dcd13e1264123dd
/src/auto.lean
5ec70e910b9d3b95e91c51e0953ec72f3678340a
[]
no_license
jcommelin/oberharmersbach2019
adaf2e54ba4eff7c178c933978055ff4d6b0593b
d2cdf780a10baa8502a9b0cae01c7efa318649a6
refs/heads/master
1,587,558,516,731
1,550,558,213,000
1,550,558,213,000
170,372,753
0
0
null
null
null
null
UTF-8
Lean
false
false
476
lean
import tactic.interactive tactic.tidy namespace tactic namespace interactive open interactive interactive.types @[tidy] meta def auto_aux : tactic unit := `[solve_by_elim [fact_ne_zero ,nat.dvd_right_of_dvd_add_of_dvd_left ,prime.not_dvd_one ,prime.pos ,nat.min_fac_dvd ,nat.dvd_fact ,le_of_not_ge]] meta def auto : tactic unit := auto_aux <|> tidy end interactive end tactic
54b452db5cf1d47ff9a9cf7001d4b5a687e8eebc
df561f413cfe0a88b1056655515399c546ff32a5
/4-power-world/l4.lean
1b10870c7e5905a4cd678783ae96e3173db24eb9
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
138
lean
lemma one_pow (m : mynat) : (1 : mynat) ^ m = 1 := begin induction m with k Pk, exact pow_zero 1, rw pow_succ, rw Pk, exact one_mul 1, end
82b27f9ff482a2703677b05cf1d3fdf5004c6ab8
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/sheaves/forget.lean
4d1543b4af09e8a4d3b102d88449ae2e6e003a18
[ "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
8,273
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.limits.preserves.shapes.products import topology.sheaves.sheaf_condition.sites /-! # Checking the sheaf condition on the underlying presheaf of types. If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. ## References * https://stacks.math.columbia.edu/tag/0073 -/ noncomputable theory open category_theory open category_theory.limits open topological_space open opposite namespace Top namespace presheaf namespace sheaf_condition open sheaf_condition_equalizer_products universes v u₁ u₂ variables {C : Type u₁} [category.{v} C] [has_limits C] variables {D : Type u₂} [category.{v} D] [has_limits D] variables (G : C ⥤ D) [preserves_limits G] variables {X : Top.{v}} (F : presheaf C X) variables {ι : Type v} (U : ι → opens X) local attribute [reducible] diagram left_res right_res /-- When `G` preserves limits, the sheaf condition diagram for `F` composed with `G` is naturally isomorphic to the sheaf condition diagram for `F ⋙ G`. -/ def diagram_comp_preserves_limits : diagram F U ⋙ G ≅ diagram (F ⋙ G) U := begin fapply nat_iso.of_components, rintro ⟨j⟩, exact (preserves_product.iso _ _), exact (preserves_product.iso _ _), rintros ⟨⟩ ⟨⟩ ⟨⟩, { ext, simp, dsimp, simp, }, -- non-terminal `simp`, but `squeeze_simp` fails { ext, simp only [limit.lift_π, functor.comp_map, map_lift_pi_comparison, fan.mk_π_app, preserves_product.iso_hom, parallel_pair_map_left, functor.map_comp, category.assoc], dsimp, simp, }, { ext, simp only [limit.lift_π, functor.comp_map, parallel_pair_map_right, fan.mk_π_app, preserves_product.iso_hom, map_lift_pi_comparison, functor.map_comp, category.assoc], dsimp, simp, }, { ext, simp, dsimp, simp, }, end local attribute [reducible] res /-- When `G` preserves limits, the image under `G` of the sheaf condition fork for `F` is the sheaf condition fork for `F ⋙ G`, postcomposed with the inverse of the natural isomorphism `diagram_comp_preserves_limits`. -/ def map_cone_fork : G.map_cone (fork F U) ≅ (cones.postcompose (diagram_comp_preserves_limits G F U).inv).obj (fork (F ⋙ G) U) := cones.ext (iso.refl _) (λ j, begin dsimp, simp [diagram_comp_preserves_limits], cases j; dsimp, { rw iso.eq_comp_inv, ext, simp, dsimp, simp, }, { rw iso.eq_comp_inv, ext, simp, -- non-terminal `simp`, but `squeeze_simp` fails dsimp, simp only [limit.lift_π, fan.mk_π_app, ←G.map_comp, limit.lift_π_assoc, fan.mk_π_app] } end) end sheaf_condition universes v u₁ u₂ open sheaf_condition sheaf_condition_equalizer_products variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] variables (G : C ⥤ D) variables [reflects_isomorphisms G] variables [has_limits C] [has_limits D] [preserves_limits G] variables {X : Top.{v}} (F : presheaf C X) /-- If `G : C ⥤ D` is a functor which reflects isomorphisms and preserves limits (we assume all limits exist in both `C` and `D`), then checking the sheaf condition for a presheaf `F : presheaf C X` is equivalent to checking the sheaf condition for `F ⋙ G`. The important special case is when `C` is a concrete category with a forgetful functor that preserves limits and reflects isomorphisms. Then to check the sheaf condition it suffices to check it on the underlying sheaf of types. Another useful example is the forgetful functor `TopCommRing ⥤ Top`. See <https://stacks.math.columbia.edu/tag/0073>. In fact we prove a stronger version with arbitrary complete target category. -/ lemma is_sheaf_iff_is_sheaf_comp : presheaf.is_sheaf F ↔ presheaf.is_sheaf (F ⋙ G) := begin rw [presheaf.is_sheaf_iff_is_sheaf_equalizer_products, presheaf.is_sheaf_iff_is_sheaf_equalizer_products], split, { intros S ι U, -- We have that the sheaf condition fork for `F` is a limit fork, obtain ⟨t₁⟩ := S U, -- and since `G` preserves limits, the image under `G` of this fork is a limit fork too. letI := preserves_smallest_limits_of_preserves_limits G, have t₂ := @preserves_limit.preserves _ _ _ _ _ _ _ G _ _ t₁, -- As we established above, that image is just the sheaf condition fork -- for `F ⋙ G` postcomposed with some natural isomorphism, have t₃ := is_limit.of_iso_limit t₂ (map_cone_fork G F U), -- and as postcomposing by a natural isomorphism preserves limit cones, have t₄ := is_limit.postcompose_inv_equiv _ _ t₃, -- we have our desired conclusion. exact ⟨t₄⟩, }, { intros S ι U, refine ⟨_⟩, -- Let `f` be the universal morphism from `F.obj U` to the equalizer -- of the sheaf condition fork, whatever it is. -- Our goal is to show that this is an isomorphism. let f := equalizer.lift _ (w F U), -- If we can do that, suffices : is_iso (G.map f), { resetI, -- we have that `f` itself is an isomorphism, since `G` reflects isomorphisms haveI : is_iso f := is_iso_of_reflects_iso f G, -- TODO package this up as a result elsewhere: apply is_limit.of_iso_limit (limit.is_limit _), apply iso.symm, fapply cones.ext, exact (as_iso f), rintro ⟨_|_⟩; { dsimp [f], simp, }, }, { -- Returning to the task of shwoing that `G.map f` is an isomorphism, -- we note that `G.map f` is almost but not quite (see below) a morphism -- from the sheaf condition cone for `F ⋙ G` to the -- image under `G` of the equalizer cone for the sheaf condition diagram. let c := fork (F ⋙ G) U, obtain ⟨hc⟩ := S U, let d := G.map_cone (equalizer.fork (left_res F U) (right_res F U)), letI := preserves_smallest_limits_of_preserves_limits G, have hd : is_limit d := preserves_limit.preserves (limit.is_limit _), -- Since both of these are limit cones -- (`c` by our hypothesis `S`, and `d` because `G` preserves limits), -- we hope to be able to conclude that `f` is an isomorphism. -- We say "not quite" above because `c` and `d` don't quite have the same shape: -- we need to postcompose by the natural isomorphism `diagram_comp_preserves_limits` -- introduced above. let d' := (cones.postcompose (diagram_comp_preserves_limits G F U).hom).obj d, have hd' : is_limit d' := (is_limit.postcompose_hom_equiv (diagram_comp_preserves_limits G F U : _) d).symm hd, -- Now everything works: we verify that `f` really is a morphism between these cones: let f' : c ⟶ d' := fork.mk_hom (G.map f) begin dsimp only [c, d, d', f, diagram_comp_preserves_limits, res], dunfold fork.ι, ext1 j, dsimp, simp only [category.assoc, ←functor.map_comp_assoc, equalizer.lift_ι, map_lift_pi_comparison_assoc], dsimp [res], simp, end, -- conclude that it is an isomorphism, -- just because it's a morphism between two limit cones. haveI : is_iso f' := is_limit.hom_is_iso hc hd' f', -- A cone morphism is an isomorphism exactly if the morphism between the cone points is, -- so we're done! exact is_iso.of_iso ((cones.forget _).map_iso (as_iso f')) }, }, end /-! As an example, we now have everything we need to check the sheaf condition for a presheaf of commutative rings, merely by checking the sheaf condition for the underlying sheaf of types. ``` import algebra.category.Ring.limits example (X : Top) (F : presheaf CommRing X) (h : presheaf.is_sheaf (F ⋙ (forget CommRing))) : F.is_sheaf := (is_sheaf_iff_is_sheaf_comp (forget CommRing) F).mpr h ``` -/ end presheaf end Top
a41143798242637ada04a269d301bd13a49365c5
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/number_theory/sum_four_squares.lean
429d200e7fbcf8d3b3076cbc56dd2808d02865c2
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
11,939
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes ## Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. # Implementation Notes The proof used is close to Lagrange's original proof. -/ import data.zmod.basic import field_theory.finite import data.int.parity import data.fintype.card open finset polynomial finite_field equiv namespace int lemma sum_two_squares_of_two_mul_sum_two_squares {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have (x^2 + y^2).even, by simp [h.symm, even_mul], have hxaddy : (x + y).even, by simpa [pow_two] with parity_simps, have hxsuby : (x - y).even, by simpa [pow_two] with parity_simps, have (x^2 + y^2) % 2 = 0, by simp [h.symm], (domain.mul_right_inj (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $ calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring ... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 : by rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy] ... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) : by simp [mul_add, _root_.pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sum_two_squares_add_one_eq_k (p : ℕ) [hp : fact p.prime] : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmod.sum_two_squares p (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (char_p.int_cast_eq_zero_iff (zmod p) p _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab, let ⟨k, hk⟩ := hab' in have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_left (by rw ← hk; exact (add_nonneg (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.pos), ⟨a.val_min_abs, b.val_min_abs, k.nat_abs, by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm], lt_of_mul_lt_mul_left (calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 : by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, nat.pow_two, nat.pow_two, int.nat_abs_mul_self, int.nat_abs_mul_self, ← _root_.pow_two, ← _root_.pow_two, int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0] ... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 : add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (le_refl _) ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, nat.one_pow, mul_one]; exact (lt_add_iff_pos_right _).2 (add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial (nat.div_pos hp.two_le dec_trivial))) ... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring }) (show 0 ≤ p, from nat.zero_le _)⟩ end int namespace nat open int open_locale classical private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m := have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 → ∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0, from dec_trivial, let f : fin 4 → ℤ := vector.nth (a::b::c::d::vector.nil) in let ⟨i, hσ⟩ := this (coe ∘ f) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl, ← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in let σ := swap i 0 in have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa [σ] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa using hσ.2, let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, begin rw [← int.sum_two_squares_of_two_mul_sum_two_squares hx.symm, add_assoc, ← int.sum_two_squares_of_two_mul_sum_two_squares hy.symm, ← domain.mul_right_inj (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : univ.sum (λ x, f (σ x)^2) = univ.sum (λ x, f x^2), { conv_rhs { rw ← finset.sum_equiv σ } }, have fin4univ : (univ : finset (fin 4)).1 = 0::1::2::3::0, from dec_trivial, simpa [finset.sum_eq_multiset_sum, fin4univ, multiset.sum_cons, f] end⟩ private lemma prime_sum_four_squares (p : ℕ) [hp : _root_.fact p.prime] : ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p := have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p, from let ⟨a, b, k, hk⟩ := exists_sum_two_squares_add_one_eq_k p in ⟨k, hk.2, nat.pos_of_ne_zero $ (λ hk0, by rw [hk0, int.coe_nat_zero, zero_mul] at hk; exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_lt_one) hk.1), a, b, 1, 0, by simpa [_root_.pow_two] using hk.1⟩, let m := nat.find hm in let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in by haveI hm0 : _root_.fact (0 < m) := (nat.find_spec hm).snd.1; exact have hmp : m < p, from (nat.find_spec hm).fst, m.mod_two_eq_zero_or_one.elim (λ hm2 : m % 2 = 0, let ⟨k, hk⟩ := (nat.dvd_iff_mod_eq_zero _ _).2 hm2 in have hk0 : 0 < k, from nat.pos_of_ne_zero $ λ _, by { simp [*, lt_irrefl] at *, exact hm0 }, have hkm : k < m, by rw [hk, two_mul]; exact (lt_add_iff_pos_left _).2 hk0, false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0, sum_four_squares_of_two_mul_sum_four_squares (show a^2 + b^2 + c^2 + d^2 = 2 * (k * p), by rw [habcd, hk, int.coe_nat_mul, mul_assoc]; simp)⟩) (λ hm2 : m % 2 = 1, if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩ else --have hm1 : 1 < m, from lt_of_le_of_ne hm0 (ne.symm hm1), let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs, y := (c : zmod m).val_min_abs, z := (d : zmod m).val_min_abs in have hnat_abs : w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ), by simp [_root_.pow_two], have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2, from calc w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs ... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) : int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) ... = 4 * (m / 2 : ℕ) ^ 2 : by simp [_root_.pow_two, bit0, bit1, mul_add, add_mul] ... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) : (lt_add_iff_pos_right _).2 (by rw [hm2, int.coe_nat_one, _root_.one_pow, mul_one]; exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one) ... = m ^ 2 : by conv_rhs {rw [← nat.mod_add_div m 2]}; simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add, add_comm, add_left_comm], have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m), by simp [w, x, y, z, pow_two], have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.cast_self, zero_mul], let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).1 hwxyz0) in have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0, have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0, by { rw [← int.coe_nat_eq_zero, ← hnat_abs], rwa [hn0, mul_zero] at hn }, have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d, by simpa [add_eq_zero_iff_eq_zero_of_nonneg (pow_two_nonneg _) (pow_two_nonneg _), nat.pow_two, w, x, y, z, (char_p.int_cast_eq_zero_iff _ m _)] using hwxyz0, let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1, ⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in have hmdvdp : m ∣ p, from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2, (domain.mul_right_inj (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0)).1 $ by rw [← habcd, hma, hmb, hmc, hmd]; ring⟩, (hp.2 _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by rw [← hwxyz0]; simp; ring, have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by simp [sub_eq_add_neg]; ring, have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by simp [sub_eq_add_neg]; ring, have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by simp [sub_eq_add_neg]; ring, let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in have hn_nonneg : 0 ≤ n, from nonneg_of_mul_nonneg_left (by erw [← hn]; repeat {try {refine add_nonneg _ _}, try {exact pow_two_nonneg _}}) (int.coe_nat_pos.2 hm0), have hnm : n.nat_abs < m, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← _root_.pow_two]; exact hwxyzlt) (int.coe_nat_nonneg m)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (domain.mul_right_inj (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero_iff_pos.2 hm0))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 + ((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 : by simp; ring ... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) : by simp only [hs.symm, ht.symm, hu.symm, hv.symm]; ring ... = _ : by rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg]; dsimp [m]; ring, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : _root_.fact (min_fac (k+2)).prime := min_fac_prime dec_trivial, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n, by exactI prime_sum_four_squares (min_fac (k+2)) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * x - b * w - c * z + d * y).nat_abs, (a * y + b * z - c * w - d * x).nat_abs, (a * z - b * y + c * x - d * w).nat_abs, (a * w + b * x + c * y + d * z).nat_abs, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp [nat.pow_two, int.coe_nat_add, int.nat_abs_mul_self'], ring, end⟩ end nat
aa7fdf7004d9a2f8db84e3df1f66d487041184ee
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/whenIO.lean
9e36074a4e0cbc8260b8026c0f65750b5d467bd4
[ "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
177
lean
import system.io definition when (b : bool) (a : io unit) : io unit := if b = tt then a else return () vm_eval when tt (put_str "hello\n") vm_eval when ff (put_str "error\n")
7329b538cae31a9f996d77e11458e8d0f6a9fed0
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/conv/apply_congr.lean
7d218a566936caafb49167916bdcf5142ea8286f
[ "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
3,166
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import algebra.big_operators.basic import data.finsupp.basic import tactic.converter.apply_congr import tactic.interactive example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := begin conv_lhs { -- If we just call `congr` here, in the second goal we're helpless, -- because we are only given the opportunity to rewrite `f`. -- However `apply_congr` uses the appropriate `@[congr]` lemma, -- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis. apply_congr, skip, simp [h, H], } end -- Again, with some `guard` statements. example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := begin conv_lhs { apply_congr finset.sum_congr, -- (See the note about get_goals/set_goals inside apply_congr) (do ng ← tactic.num_goals, guard $ ng = 2), guard_target S, skip, guard_target f x, simp [h, H] } end -- Verify we can `rw` as well as `simp`. example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := by conv_lhs { apply_congr, skip, rw h x H, } -- Check that the appropriate `@[congr]` lemma is automatically selected. example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.prod S f = finset.prod S g := by conv_lhs { apply_congr, skip, simp [h, H], } example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.fold (+) 0 f S = finset.fold (+) 0 g S := begin -- This time, the automatically selected congruence lemma is "too good"! -- `finset.sum_congr` matches, and so the `conv` block actually -- rewrites the left hand side into a `finset.sum`. conv_lhs { apply_congr, skip, simp [h, H], }, -- So we need a `refl` to identify that we're done. refl, end -- This can be avoided by selecting the congruence lemma by hand. example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.fold (+) 0 f S = finset.fold (+) 0 g S := begin conv_lhs { apply_congr finset.fold_congr, simp [h, H], }, end example (f : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = 0) : finset.sum S f = 0 := begin conv_lhs { apply_congr, skip, simp [h, H], }, simp, end -- An example using `finsupp.sum` open_locale classical example {k G : Type} [semiring k] [group G] (g : G →₀ k) (a₁ x : G) (b₁ : k) (t : ∀ (a₂ : G), a₁ * a₂ = x ↔ a₁⁻¹ * x = a₂) : g.sum (λ (a₂ : G) (b₂ : k), ite (a₁ * a₂ = x) (b₁ * b₂) 0) = b₁ * g (a₁⁻¹ * x) := begin -- In fact, `congr` works fine here, because our rewrite works globally. conv_lhs { apply_congr, skip, dsimp, rw t, }, rw finset.sum_ite_eq g.support, -- it's a pity we can't just use `simp` here. split_ifs, { refl, }, { simp [finsupp.not_mem_support_iff.1 h], }, end example : true := begin success_if_fail { conv { apply_congr, }, }, trivial end
4858702ddb7c796a11f557a4c9c0e6f4e0279700
af6139dd14451ab8f69cf181cf3a20f22bd699be
/library/init/meta/converter.lean
ceba133b0907058377f4bae891cf3ed5c7827df5
[ "Apache-2.0" ]
permissive
gitter-badger/lean-1
1cca01252d3113faa45681b6a00e1b5e3a0f6203
5c7ade4ee4f1cdf5028eabc5db949479d6737c85
refs/heads/master
1,611,425,383,521
1,487,871,140,000
1,487,871,140,000
82,995,612
0
0
null
1,487,905,618,000
1,487,905,618,000
null
UTF-8
Lean
false
false
8,940
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 Converter monad for building simplifiers. -/ prelude import init.meta.tactic init.meta.simp_tactic import init.meta.congr_lemma init.meta.match_tactic open tactic meta structure conv_result (α : Type) := (val : α) (rhs : expr) (proof : option expr) meta def conv (α : Type) : Type := name → expr → tactic (conv_result α) namespace conv meta def lhs : conv expr := λ r e, return ⟨e, e, none⟩ meta def change (new_p : pexpr) : conv unit := λ r e, do new_e ← to_expr new_p, unify e new_e, return ⟨(), new_e, none⟩ protected meta def pure {α : Type} : α → conv α := λ a r e, return ⟨a, e, none⟩ private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) := match o₁, o₂ with | none, _ := return o₂ | _, none := return o₁ | some p₁, some p₂ := do env ← get_env, match env^.trans_for r with | some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr | none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not transitive" end end protected meta def seq {α β : Type} (c₁ : conv (α → β)) (c₂ : conv α) : conv β := λ r e, do ⟨fn, e₁, pr₁⟩ ← c₁ r e, ⟨a, e₂, pr₂⟩ ← c₂ r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨fn a, e₂, pr⟩ protected meta def fail {α : Type} : conv α := λ r e, failed protected meta def orelse {α : Type} (c₁ : conv α) (c₂ : conv α) : conv α := λ r e, c₁ r e <|> c₂ r e protected meta def map {α β : Type} (f : α → β) (c : conv α) : conv β := λ r e, do ⟨a, e₁, pr⟩ ← c r e, return ⟨f a, e₁, pr⟩ protected meta def bind {α β : Type} (c₁ : conv α) (c₂ : α → conv β) : conv β := λ r e, do ⟨a, e₁, pr₁⟩ ← c₁ r e, ⟨b, e₂, pr₂⟩ ← c₂ a r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨b, e₂, pr⟩ meta instance : monad conv := { map := @conv.map, ret := @conv.pure, bind := @conv.bind } meta instance : alternative conv := { map := @conv.map, pure := @conv.pure, seq := @conv.seq, failure := @conv.fail, orelse := @conv.orelse } meta def whnf (md : transparency := reducible) : conv unit := λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩ meta def dsimp : conv unit := λ r e, do s ← simp_lemmas.mk_default, n ← s^.dsimplify e, return ⟨(), n, none⟩ meta def try (c : conv unit) : conv unit := c <|> return () meta def tryb (c : conv unit) : conv bool := (c >> return tt) <|> return ff meta def trace {α : Type} [has_to_tactic_format α] (a : α) : conv unit := λ r e, tactic.trace a >> return ⟨(), e, none⟩ meta def trace_lhs : conv unit := lhs >>= trace meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit := λ r e, do (new_e, pr) ← s^.rewrite prove r e, return ⟨(), new_e, some pr⟩ meta def apply_lemmas (s : simp_lemmas) : conv unit := apply_lemmas_core s failed /- αdapter for using iff-lemmas as eq-lemmas -/ meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit := λ r e, do guard (r = `eq), (new_e, pr) ← s^.rewrite prove `iff e, new_pr ← mk_app `propext [pr], return ⟨(), new_e, some new_pr⟩ meta def apply_propext_lemmas (s : simp_lemmas) : conv unit := apply_propext_lemmas_core s failed private meta def mk_refl_proof (r : name) (e : expr) : tactic expr := do env ← get_env, match (environment.refl_for env r) with | (some refl) := do pr ← mk_app refl [e], return pr | none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not reflexive" end meta def to_tactic (c : conv unit) : name → expr → tactic (expr × expr) := λ r e, do ⟨u, e₁, o⟩ ← c r e, match o with | none := do p ← mk_refl_proof r e, return (e₁, p) | some p := return (e₁, p) end meta def lift_tactic {α : Type} (t : tactic α) : conv α := λ r e, do a ← t, return ⟨a, e, none⟩ meta def apply_simp_set (attr_name : name) : conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas meta def apply_propext_simp_set (attr_name : name) : conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas meta def skip : conv unit := return () meta def repeat : conv unit → conv unit | c r lhs := (do ⟨_, rhs₁, pr₁⟩ ← c r lhs, guard (¬ lhs =ₐ rhs₁), ⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁, pr ← join_proofs r pr₁ pr₂, return ⟨(), rhs₂, pr⟩) <|> return ⟨(), lhs, none⟩ meta def first {α : Type} : list (conv α) → conv α | [] := conv.fail | (c::cs) := c <|> first cs meta def match_pattern (p : pattern) : conv unit := λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩ meta def mk_match_expr (p : pexpr) : tactic (conv unit) := do new_p ← pexpr_to_pattern p, return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩) meta def match_expr (p : pexpr) : conv unit := λ r e, do new_p ← pexpr_to_pattern p, tactic.match_pattern new_p e >> return ⟨(), e, none⟩ meta def funext (c : conv unit) : conv unit := λ r lhs, do guard (r = `eq), (expr.lam n bi d b) ← return lhs, aux_type ← return $ (expr.pi n bi d (expr.const `true [])), (result, _) ← solve_aux aux_type $ do { x ← intro1, c_result ← c r (b^.instantiate_var x), rhs ← return $ expr.lam n bi d (c_result^.rhs^.abstract x), match c_result^.proof : _ → tactic (conv_result unit) with | some pr := do aux_pr ← return $ expr.lam n bi d (pr^.abstract x), new_pr ← mk_app `funext [lhs, rhs, aux_pr], return ⟨(), rhs, some new_pr⟩ | none := return ⟨(), rhs, none⟩ end }, return result meta def congr_core (c_f c_a : conv unit) : conv unit := λ r lhs, do guard (r = `eq), (expr.app f a) ← return lhs, f_type ← infer_type f >>= tactic.whnf, guard (f_type^.is_arrow), ⟨(), new_f, of⟩ ← try c_f r f, ⟨(), new_a, oa⟩ ← try c_a r a, rhs ← return $ new_f new_a, match of, oa with | none, none := return ⟨(), rhs, none⟩ | none, some pr_a := do pr ← mk_app `congr_arg [a, new_a, f, pr_a], return ⟨(), new_f new_a, some pr⟩ | some pr_f, none := do pr ← mk_app `congr_fun [f, new_f, pr_f, a], return ⟨(), rhs, some pr⟩ | some pr_f, some pr_a := do pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a], return ⟨(), rhs, some pr⟩ end meta def congr (c : conv unit) : conv unit := congr_core c c meta def bottom_up (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, failed) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) r e, return ⟨(), new_e, some pr⟩ meta def top_down (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, (do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)) <|> return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find_pattern (pat : pattern) (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, if matched then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff) else return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def findp : pexpr → conv unit → conv unit := λ p c r e, do pat ← pexpr_to_pattern p, find_pattern pat c r e meta def conversion (c : conv unit) : tactic unit := do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"), (new_lhs, pr) ← to_tactic c r lhs, (unify new_lhs rhs <|> do new_lhs_fmt ← pp new_lhs, rhs_fmt ← pp rhs, fail (to_fmt "conversion failed, expected" ++ rhs_fmt^.indent 4 ++ format.line ++ "provided" ++ new_lhs_fmt^.indent 4)), exact pr end conv
c5b8ebfbaeb1f15c418284323058e2e2b02b3558
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/cyclotomic/rat.lean
d02a490ee2967b20eebea6052c8bc5cc7a4b5569
[ "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,927
lean
/- Copyright (c) 2022 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import number_theory.cyclotomic.discriminant import ring_theory.polynomial.eisenstein /-! # Ring of integers of `p ^ n`-th cyclotomic fields We compute the ring of integers of a `p ^ n`-th cyclotomic extension of `ℚ`. ## Main results * `is_cyclotomic_extension.rat.is_integral_closure_adjoing_singleton_of_prime_pow`: if `K` is a `p ^ k`-th cyclotomic extension of `ℚ`, then `(adjoin ℤ {ζ})` is the integral closure of `ℤ` in `K`. * `is_cyclotomic_extension.rat.cyclotomic_ring_is_integral_closure_of_prime_pow`: the integral closure of `ℤ` inside `cyclotomic_field (p ^ k) ℚ` is `cyclotomic_ring (p ^ k) ℤ ℚ`. -/ universes u open algebra is_cyclotomic_extension polynomial open_locale cyclotomic namespace is_cyclotomic_extension.rat variables {p : ℕ+} {k : ℕ} {K : Type u} [field K] [char_zero K] {ζ : K} [hp : fact (p : ℕ).prime] include hp /-- The discriminant of the power basis given by `ζ - 1`. -/ lemma discr_prime_pow_ne_two' [is_cyclotomic_extension {p ^ (k + 1)} ℚ K] (hζ : is_primitive_root ζ ↑(p ^ (k + 1))) (hk : p ^ (k + 1) ≠ 2) : discr ℚ (hζ.sub_one_power_basis ℚ).basis = (-1) ^ (((p ^ (k + 1) : ℕ).totient) / 2) * p ^ ((p : ℕ) ^ k * ((p - 1) * (k + 1) - 1)) := begin rw [← discr_prime_pow_ne_two hζ (cyclotomic.irreducible_rat (p ^ (k + 1)).pos) hk], exact hζ.discr_zeta_eq_discr_zeta_sub_one.symm end lemma discr_odd_prime' [is_cyclotomic_extension {p} ℚ K] (hζ : is_primitive_root ζ p) (hodd : p ≠ 2) : discr ℚ (hζ.sub_one_power_basis ℚ).basis = (-1) ^ (((p : ℕ) - 1) / 2) * p ^ ((p : ℕ) - 2) := begin rw [← discr_odd_prime hζ (cyclotomic.irreducible_rat hp.out.pos) hodd], exact hζ.discr_zeta_eq_discr_zeta_sub_one.symm end /-- The discriminant of the power basis given by `ζ - 1`. Beware that in the cases `p ^ k = 1` and `p ^ k = 2` the formula uses `1 / 2 = 0` and `0 - 1 = 0`. It is useful only to have a uniform result. See also `is_cyclotomic_extension.rat.discr_prime_pow_eq_unit_mul_pow'`. -/ lemma discr_prime_pow' [is_cyclotomic_extension {p ^ k} ℚ K] (hζ : is_primitive_root ζ ↑(p ^ k)) : discr ℚ (hζ.sub_one_power_basis ℚ).basis = (-1) ^ (((p ^ k : ℕ).totient) / 2) * p ^ ((p : ℕ) ^ (k - 1) * ((p - 1) * k - 1)) := begin rw [← discr_prime_pow hζ (cyclotomic.irreducible_rat (p ^ k).pos)], exact hζ.discr_zeta_eq_discr_zeta_sub_one.symm end /-- If `p` is a prime and `is_cyclotomic_extension {p ^ k} K L`, then there are `u : ℤˣ` and `n : ℕ` such that the discriminant of the power basis given by `ζ - 1` is `u * p ^ n`. Often this is enough and less cumbersome to use than `is_cyclotomic_extension.rat.discr_prime_pow'`. -/ lemma discr_prime_pow_eq_unit_mul_pow' [is_cyclotomic_extension {p ^ k} ℚ K] (hζ : is_primitive_root ζ ↑(p ^ k)) : ∃ (u : ℤˣ) (n : ℕ), discr ℚ (hζ.sub_one_power_basis ℚ).basis = u * p ^ n := begin rw [hζ.discr_zeta_eq_discr_zeta_sub_one.symm], exact discr_prime_pow_eq_unit_mul_pow hζ (cyclotomic.irreducible_rat (p ^ k).pos) end /-- If `K` is a `p ^ k`-th cyclotomic extension of `ℚ`, then `(adjoin ℤ {ζ})` is the integral closure of `ℤ` in `K`. -/ lemma is_integral_closure_adjoing_singleton_of_prime_pow [hcycl : is_cyclotomic_extension {p ^ k} ℚ K] (hζ : is_primitive_root ζ ↑(p ^ k)) : is_integral_closure (adjoin ℤ ({ζ} : set K)) ℤ K := begin refine ⟨subtype.val_injective, λ x, ⟨λ h, ⟨⟨x, _⟩, rfl⟩, _⟩⟩, swap, { rintro ⟨y, rfl⟩, exact is_integral.algebra_map (le_integral_closure_iff_is_integral.1 (adjoin_le_integral_closure (hζ.is_integral (p ^ k).pos)) _) }, let B := hζ.sub_one_power_basis ℚ, have hint : is_integral ℤ B.gen := is_integral_sub (hζ.is_integral (p ^ k).pos) is_integral_one, have H := discr_mul_is_integral_mem_adjoin ℚ hint h, obtain ⟨u, n, hun⟩ := discr_prime_pow_eq_unit_mul_pow' hζ, rw [hun] at H, replace H := subalgebra.smul_mem _ H u.inv, rw [← smul_assoc, ← smul_mul_assoc, units.inv_eq_coe_inv, coe_coe, zsmul_eq_mul, ← int.cast_mul, units.inv_mul, int.cast_one, one_mul, show (p : ℚ) ^ n • x = ((p : ℕ) : ℤ) ^ n • x, by simp [smul_def]] at H, unfreezingI { cases k }, { haveI : is_cyclotomic_extension {1} ℚ K := by simpa using hcycl, have : x ∈ (⊥ : subalgebra ℚ K), { rw [singleton_one ℚ K], exact mem_top }, obtain ⟨y, rfl⟩ := mem_bot.1 this, replace h := (is_integral_algebra_map_iff (algebra_map ℚ K).injective).1 h, obtain ⟨z, hz⟩ := is_integrally_closed.is_integral_iff.1 h, rw [← hz, ← is_scalar_tower.algebra_map_apply], exact subalgebra.algebra_map_mem _ _ }, { have hmin : (minpoly ℤ B.gen).is_eisenstein_at (submodule.span ℤ {((p : ℕ) : ℤ)}), { have h₁ := minpoly.gcd_domain_eq_field_fractions ℚ hint, have h₂ := hζ.minpoly_sub_one_eq_cyclotomic_comp (cyclotomic.irreducible_rat (p ^ _).pos), rw [is_primitive_root.sub_one_power_basis_gen] at h₁, rw [h₁, ← map_cyclotomic_int, show int.cast_ring_hom ℚ = algebra_map ℤ ℚ, by refl, show ((X + 1)) = map (algebra_map ℤ ℚ) (X + 1), by simp, ← map_comp] at h₂, rw [is_primitive_root.sub_one_power_basis_gen, map_injective (algebra_map ℤ ℚ) ((algebra_map ℤ ℚ).injective_int) h₂], exact cyclotomic_prime_pow_comp_X_add_one_is_eisenstein_at _ _ }, refine adjoin_le _ (mem_adjoin_of_smul_prime_pow_smul_of_minpoly_is_eiseinstein_at (nat.prime_iff_prime_int.1 hp.out) hint h H hmin), simp only [set.singleton_subset_iff, set_like.mem_coe], exact subalgebra.sub_mem _ (self_mem_adjoin_singleton ℤ _) (subalgebra.one_mem _) } end lemma is_integral_closure_adjoing_singleton_of_prime [hcycl : is_cyclotomic_extension {p} ℚ K] (hζ : is_primitive_root ζ ↑p) : is_integral_closure (adjoin ℤ ({ζ} : set K)) ℤ K := begin rw [← pow_one p] at hζ hcycl, exactI is_integral_closure_adjoing_singleton_of_prime_pow hζ, end local attribute [-instance] cyclotomic_field.algebra local attribute [instance] algebra_rat_subsingleton /-- The integral closure of `ℤ` inside `cyclotomic_field (p ^ k) ℚ` is `cyclotomic_ring (p ^ k) ℤ ℚ`. -/ lemma cyclotomic_ring_is_integral_closure_of_prime_pow : is_integral_closure (cyclotomic_ring (p ^ k) ℤ ℚ) ℤ (cyclotomic_field (p ^ k) ℚ) := begin haveI : is_cyclotomic_extension {p ^ k} ℚ (cyclotomic_field (p ^ k) ℚ), { convert cyclotomic_field.is_cyclotomic_extension (p ^ k) _, { exact subsingleton.elim _ _ }, { exact ne_zero.char_zero } }, have hζ := zeta_primitive_root (p ^ k) ℚ (cyclotomic_field (p ^ k) ℚ), refine ⟨is_fraction_ring.injective _ _, λ x, ⟨λ h, ⟨⟨x, _⟩, rfl⟩, _⟩⟩, { have := (is_integral_closure_adjoing_singleton_of_prime_pow hζ).is_integral_iff, obtain ⟨y, rfl⟩ := this.1 h, convert adjoin_mono _ y.2, { simp only [eq_iff_true_of_subsingleton] }, { simp only [eq_iff_true_of_subsingleton] }, { simp only [pnat.pow_coe, set.singleton_subset_iff, set.mem_set_of_eq], exact hζ.pow_eq_one } }, { haveI : is_cyclotomic_extension {p ^ k} ℤ (cyclotomic_ring (p ^ k) ℤ ℚ), { convert cyclotomic_ring.is_cyclotomic_extension _ ℤ ℚ, { exact subsingleton.elim _ _ }, { exact ne_zero.char_zero } }, rintro ⟨y, rfl⟩, exact is_integral.algebra_map ((is_cyclotomic_extension.integral {p ^ k} ℤ _) _) } end lemma cyclotomic_ring_is_integral_closure_of_prime : is_integral_closure (cyclotomic_ring p ℤ ℚ) ℤ (cyclotomic_field p ℚ) := begin rw [← pow_one p], exact cyclotomic_ring_is_integral_closure_of_prime_pow end end is_cyclotomic_extension.rat
f5718712f47c22adf2c1ca3622bc451521106088
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/limits/terminal.lean
6bd176d60e117f91012a77e7365a562446b74bee
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
3,031
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton, Mario Carneiro import category_theory.limits.shape import category_theory.filtered open category_theory namespace category_theory.limits universes u v w variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 section terminal structure is_terminal (t : C) := (lift : ∀ (s : C), s ⟶ t) (uniq' : ∀ (s : C) (m : s ⟶ t), m = lift s . obviously) restate_axiom is_terminal.uniq' attribute [search,back'] is_terminal.uniq @[extensionality] lemma is_terminal.ext {X : C} (P Q : is_terminal.{u v} X) : P = Q := begin tactic.unfreeze_local_instances, cases P, cases Q, congr, obviously, end instance hom_to_terminal_subsingleton (X' : C) (X : C) (h : is_terminal.{u v} X) : subsingleton (X' ⟶ X) := begin fsplit, intros f g, rw h.uniq X' f, rw h.uniq X' g, end end terminal section initial structure is_initial (t : C) := (desc : ∀ (s : C), t ⟶ s) (uniq' : ∀ (s : C) (m : t ⟶ s), m = desc s . obviously) attribute [class] is_initial restate_axiom is_initial.uniq' attribute [search,back'] is_initial.uniq @[extensionality] lemma is_initial.ext {X : C} (P Q : is_initial.{u v} X) : P = Q := begin tactic.unfreeze_local_instances, cases P, cases Q, congr, obviously, end instance hom_from_initial_subsingleton (X' : C) (X : C) (h : is_initial.{u v} X') : subsingleton (X' ⟶ X) := begin fsplit, intros f g, rw h.uniq X f, rw h.uniq X g, end end initial variable (C) class has_terminal_object := (terminal : C) (is_terminal : is_terminal.{u v} terminal . obviously) class has_initial_object := (initial : C) (is_initial : is_initial.{u v} initial . obviously) def terminal_object [has_terminal_object.{u v} C] : C := has_terminal_object.terminal.{u v} C def initial_object [has_initial_object.{u v} C] : C := has_initial_object.initial.{u v} C variable {C} section variables [has_terminal_object.{u v} C] def terminal_object.universal_property : is_terminal.{u v} (terminal_object.{u v} C) := has_terminal_object.is_terminal.{u v} C def terminal_object.hom (X : C) : (X ⟶ terminal_object.{u v} C) := terminal_object.universal_property.lift.{u v} X @[extensionality] lemma terminal.hom_ext {X' : C} (f g : X' ⟶ terminal_object.{u v} C) : f = g := begin rw (terminal_object.universal_property).uniq _ f, rw (terminal_object.universal_property).uniq _ g, end end section variables [has_initial_object.{u v} C] def initial_object.universal_property : is_initial.{u v} (initial_object.{u v} C) := has_initial_object.is_initial.{u v} C def initial_object.hom (X : C) : (initial_object.{u v} C ⟶ X) := initial_object.universal_property.desc.{u v} X @[extensionality] lemma initial.hom_ext {X' : C} (f g : initial_object.{u v} C ⟶ X') : f = g := begin rw (initial_object.universal_property).uniq _ f, rw (initial_object.universal_property).uniq _ g, end end end category_theory.limits
b892ddf8dad614e04de01b5e1de7517a78a730fd
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/linear_algebra/multilinear.lean
beb9f9970a0b2bd7bf6a1b0ea2002157c9353ecf
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
33,814
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 linear_algebra.basic import tactic.omega import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ v₂ v₃ w u' variables {R : Type u} {ι : Type u'} {n : ℕ} {M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ι] /-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R`. -/ structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (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₂] := (to_fun : (Πi, M₁ i) → M₂) (map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i), to_fun (update m i (c • x)) = c • to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [∀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)] [semimodule R M₂] [semimodule R M₃] [semimodule R M'] (f f' : multilinear_map R M₁ M₂) instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩ @[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := by cases f; cases f'; congr'; exact funext 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 := begin have : (0 : R) • (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := begin obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ M₂) := ⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc], λm i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ M₂) := ⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ := { to_fun := λx, f (update m i x), map_add' := λx y, by simp, map_smul' := λc x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (M₂ × M₃) := { to_fun := λ m, (f m, g m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ noncomputable def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (λ i : fin k, M') M₂ := { to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.mono_equiv_of_fin hk).symm ⟨j, h⟩) else z), map_add' := λ v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of 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 : 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) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of 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 : 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) := by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of 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 snoc_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c • x)) = c • f (snoc m x) := by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last] /- If `R` and `M₂` are implicit in the next definition, Lean is never able to infer them, even given `g` and `f`. Therefore, we make them explicit. -/ variables (R M₂) /-- If `g` is multilinear and `f` is linear, then `g (f m₁, ..., f mₙ)` is again a multilinear function, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R (λ (i : ι), M₂) M₃) (f : M' →ₗ[R] M₂) : multilinear_map R (λ (i : ι), M') M₃ := { to_fun := λ m, g (f ∘ m), map_add' := λ m i x y, by simp [comp_update], map_smul' := λ m i c x, by simp [comp_update] } variables {R M₂} /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite.-/ 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') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (λs hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a 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') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) open_locale classical open fintype finset /-- If `f` is 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. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux {n : ℕ} (h : ∑ i, (A i).card = n) : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : ∃ i, A i = ∅, { rcases Ai_empty with ⟨i, hi⟩, have : ∑ j in A i, g i j = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = ∅, { apply finset.eq_empty_of_forall_not_mem (λ r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : ∀ i, (A i).card ≤ 1, { have Ai_card : ∀ i, (A i).card = 1, { assume i, have : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≤ 1 := Ai_singleton i, omega }, have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : ∀ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, sum_const] }, -- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2. -- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i` -- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ := finset.one_lt_card_iff.1 hi₀, let B := function.update A i₀ (A i₀ \ {j₂}), let C := function.update A i₀ {j₂}, have B_subset_A : ∀ i, B i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : ∀ i, C i ⊆ A i, { assume i, by_cases hi : i = i₀, { rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity. have A_eq_BC : (λ i, ∑ j in A i, g i j) = function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j), { ext i, by_cases hi : i = i₀, { rw [hi], simp only [function.update_same], have : A i₀ = B i₀ ∪ C i₀, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hj₂, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (λ j hj, _), have : j = j₂, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) = (λ i, ∑ j in B i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) = (λ i, ∑ j in C i, g i j), { ext i, by_cases hi : i = i₀, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)), { have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i), { refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i)) ⟨i₀, finset.mem_univ _, _⟩, have : {j₂} ⊆ A i₀, by simp [hj₂], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)), { have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) := finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i)) ⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B i₀) (C i₀), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hri₀ : r i₀ = j₂, { apply finset.mem_union_right, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ C i₀, by simp [C, hri₀], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (λ i, _), by_cases hi : i = i₀, { have : r i₀ ∈ B i₀, by simp [B, hri₀, mem_pi_finset.1 hr i₀], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i)) (pi_finset_subset _ _ (λ i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is 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.map_sum_finset_aux _ _ rfl /-- If `f` is 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.map_sum_finset g (λ i, finset.univ) end apply_sum end semiring section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)] [add_comm_monoid M₂] [∀i, semimodule R (M i)] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f f' : multilinear_map R M₁ M₂) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ι` to be finite. -/ 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 := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) = s.piecewise (λi, c i • m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a 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 := by simpa using map_piecewise_smul f c m finset.univ instance : has_scalar R (multilinear_map R M₁ M₂) := ⟨λ c f, ⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl variables (R ι) /-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ := { to_fun := λm, (∏ i, m i) • z, map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul, add_smul], map_smul' := λ m i c x, by { rw [smul_eq_mul], simp [finset.prod_update_of_mem, smul_smul, mul_assoc] } } variables {R ι} @[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) : (multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) : multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f := begin ext m, have : m = (λi, m i • 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] (f : 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) := by { simp only [map_add, add_left_inj, sub_eq_add_neg, (neg_one_smul R y).symm, map_smul], simp } instance : has_neg (multilinear_map R M₁ M₂) := ⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : add_comm_group (multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] end ring section comm_ring variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, semimodule R (M₁ i)] [semimodule R M₂] variables (R ι M₁ M₂) /-- The space of multilinear maps is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance semimodule : semimodule R (multilinear_map R M₁ M₂) := semimodule.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] -- This instance should not be needed! instance semimodule_ring : semimodule R (multilinear_map R (λ (i : ι), R) M₂) := multilinear_map.semimodule _ _ (λ (i : ι), R) _ /-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) := { to_fun := λ z, multilinear_map.mk_pi_ring R ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_ring_apply_one_eq_self } end comm_ring end multilinear_map namespace 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₃] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) : multilinear_map R M₁ M₃ := { to_fun := λ m, g (f m), map_add' := λ m i x y, by simp, map_smul' := λ m i c x, by simp } end linear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M M₂} [comm_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₂] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : multilinear_map R M M₂ := { to_fun := λm, f (m 0) (tail m), map_add' := λm i x y, begin by_cases h : i = 0, { revert x y, rw h, assume x y, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := λm i c x, begin by_cases h : i = 0, { revert x, rw h, assume x, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M M₂) : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) := { to_fun := λx, { to_fun := λm, f (cons x m), map_add' := λm i y y', by simp, map_smul' := λm i y c, by simp }, map_add' := λx y, by { ext m, exact cons_add f m x y }, map_smul' := λc x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M M₂) : f.curry_left.uncurry_left = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M M₂} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) : multilinear_map R M M₂ := { to_fun := λm, f (init m) (m (last n)), map_add' := λm i x y, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := λm i c x, begin by_cases h : i.val < n, { have : last n ≠ i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M M₂) : multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) := { to_fun := λm, { to_fun := λx, f (snoc m x), map_add' := λx y, by rw f.snoc_add, map_smul' := λc x, by rw f.snoc_smul }, map_add' := λm i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := λm i c x, begin ext z, change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M M₂) /-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂)) ≃ₗ[R] (multilinear_map R M M₂) := { to_fun := multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } end currying
9b60307381bedea9d5960fdd18e41f4b0c3a7053
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/topology/algebra/uniform_ring.lean
799c3a73ffe61039d5743a00d816d0a2978bf242
[ "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
7,612
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Theory of topological rings with uniform structure. -/ import topology.algebra.group_completion import topology.algebra.ring open classical set filter topological_space add_comm_group open_locale classical noncomputable theory namespace uniform_space.completion open dense_inducing uniform_space function variables (α : Type*) [ring α] [uniform_space α] instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry (*))⟩ @[norm_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl variables {α} [topological_ring α] @[norm_cast] lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := ((dense_inducing_coe.prod dense_inducing_coe).extend_eq ((continuous_coe α).comp (@continuous_mul α _ _ _)) (a, b)).symm variables [uniform_add_group α] lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) := begin let m := (add_monoid_hom.mul : α →+ α →+ α).compr₂ to_compl, have : continuous (λ p : α × α, m p.1 p.2), from (continuous_coe α).comp continuous_mul, have di : dense_inducing (to_compl : α → completion α), from dense_inducing_coe, convert di.extend_Z_bilin di this, ext ⟨x, y⟩, refl end lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := continuous_mul.comp (hf.prod_mk hg : _) instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.mul continuous_fst (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul continuous_fst (continuous.add (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))) (continuous.add (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.add continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.add (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } /-- The map from a uniform ring to its completion, as a ring homomorphism. -/ def coe_ring_hom : α →+* completion α := ⟨coe, coe_one α, assume a b, coe_mul a b, coe_zero, assume a b, coe_add a b⟩ lemma continuous_coe_ring_hom : continuous (coe_ring_hom : α → completion α) := continuous_coe α universes u variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] (f : α →+* β) (hf : continuous f) /-- The completion extension as a ring morphism. -/ def extension_hom [complete_space β] [separated_space β] : completion α →+* β := have hf' : continuous (f : α →+ β), from hf, -- helping the elaborator have hf : uniform_continuous f, from uniform_continuous_of_continuous hf', { to_fun := completion.extension f, map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero], map_add' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, f.map_add]), map_one' := by rw [← coe_one, extension_coe hf, f.map_one], map_mul' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_mul) ((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, f.map_mul]) } instance top_ring_compl : topological_ring (completion α) := { continuous_add := continuous_add, continuous_mul := continuous_mul } /-- The completion map as a ring morphism. -/ def map_ring_hom (hf : continuous f) : completion α →+* completion β := extension_hom (coe_ring_hom.comp f) (continuous_coe_ring_hom.comp hf) variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R] instance : comm_ring (completion R) := { mul_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_fst.mul continuous_snd) (continuous_snd.mul continuous_fst)) (assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]), ..completion.ring } end uniform_space.completion namespace uniform_space variables {α : Type*} lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext $ assume x y, group_separation_rel x y lemma ring_sep_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (⊥ : ideal α).closure.quotient := by rw [@ring_sep_rel α r]; refl /-- Given a topological ring `α` equipped with a uniform structure that makes subtraction uniformly continuous, get an equivalence between the separated quotient of `α` and the quotient ring corresponding to the closure of zero. -/ def sep_quot_equiv_ring_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ (⊥ : ideal α).closure.quotient := quotient.congr_right $ assume x y, group_separation_rel x y /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ instance comm_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := by rw ring_sep_quot α; apply_instance instance topological_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := begin convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel}, simp [uniform_space.comm_ring] end end uniform_space
0ce343bd92b0e318700312275eab10392d95ef1a
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/formal/cofibrations/arrow.lean
3965a18b07b986b64c1fb0c0c741f78ace1f800c
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
4,172
lean
import .precofibration_category universes v u namespace homotopy_theory.cofibrations open category_theory category_theory.category open precofibration_category variables {C : Type u} [category.{v} C] [precofibration_category.{v} C] -- These are the cofibrations in the arrow category of C with the "projective" structure. structure cof_square {a₁ a₂ b₁ b₂ : C} (a : a₁ ⟶ a₂) (b : b₁ ⟶ b₂) : Type (max u v) := (f₁ : a₁ ⟶ b₁) (f₂ : a₂ ⟶ b₂) (hs : f₁ ≫ b = a ≫ f₂) (hf₁ : is_cof f₁) (hf₂ : is_cof ((pushout_by_cof f₁ a hf₁).is_pushout.induced b f₂ hs)) def cof_square.id {a₁ a₂ : C} (a : a₁ ⟶ a₂) : cof_square a a := ⟨𝟙 a₁, 𝟙 a₂, by simp, cof_id _, /- a₁ = a₁ ↓ ↓ a₂ = a₂ -/ begin let := pushout.unique (pushout_by_cof (𝟙 a₁) a (cof_id _)).is_pushout (Is_pushout.refl a).transpose, exact cof_iso this end⟩ def cof_square.comp {a₁ a₂ b₁ b₂ c₁ c₂ : C} {a : a₁ ⟶ a₂} {b : b₁ ⟶ b₂} {c : c₁ ⟶ c₂} (f : cof_square a b) (g : cof_square b c) : cof_square a c := ⟨f.f₁ ≫ g.f₁, f.f₂ ≫ g.f₂, by rw [assoc, g.hs, ←assoc, f.hs, assoc], cof_comp f.hf₁ g.hf₁, begin /- a₁ → b₁ → c₁ All these pushouts are "transposed" from the usual layout, ↓ 1 ↓ 2 ↓ that is, the first map is horizontal and the second vertical. a₂ → ⬝ → ⬝ ↓ 3 ↓ b₂ → ⬝ ↓ c₂ -/ let po₁ := pushout_by_cof f.f₁ a f.hf₁, let po₁₂ := pushout_by_cof (f.f₁ ≫ g.f₁) a (cof_comp f.hf₁ g.hf₁), let k := pushout_of_maps po₁.is_pushout po₁₂.is_pushout (𝟙 a₁) g.f₁ (𝟙 a₂) (by simp) (by simp), have po₂ : Is_pushout g.f₁ po₁.map₀ po₁₂.map₀ k := Is_pushout_of_Is_pushout_of_Is_pushout_vert' po₁.is_pushout (by convert po₁₂.is_pushout; simp [k, pushout_of_maps]) (by simp [k, pushout_of_maps]), let fc := _, have : is_cof fc := f.hf₂, let po₂₃ := pushout_by_cof g.f₁ b g.hf₁, let l := pushout_of_maps po₁₂.is_pushout po₂₃.is_pushout f.f₁ (𝟙 c₁) f.f₂ (by simp) f.hs.symm, have po₃ : Is_pushout k fc l po₂₃.map₁ := Is_pushout_of_Is_pushout_of_Is_pushout' po₂ (by convert po₂₃.is_pushout; simp [l, pushout_of_maps]) begin apply po₁.is_pushout.uniqueness; dsimp [k, fc, pushout_of_maps]; conv { to_lhs, rw ←assoc }; conv { to_rhs, rw ←assoc }; simp [l, pushout_of_maps, po₂₃.is_pushout.commutes] end, let gc := _, have : is_cof gc := g.hf₂, convert cof_comp (pushout_is_cof po₃.transpose f.hf₂) g.hf₂, simp [l, induced_pushout_of_maps] end⟩ section is_cof_square /- This "flatter" representation is helpful when trying to prove that a square's corner map is a cofibration by expressing it as (non-definitionally equal to) a composition of two such squares. -/ variables {a₁ a₂ b₁ b₂ c₁ c₂ : C} (a : a₁ ⟶ a₂) (b : b₁ ⟶ b₂) {c : c₁ ⟶ c₂} variables (f₁ : a₁ ⟶ b₁) (f₂ : a₂ ⟶ b₂) {g₁ : b₁ ⟶ c₁} {g₂ : b₂ ⟶ c₂} variables {h₁ : a₁ ⟶ c₁} {h₂ : a₂ ⟶ c₂} def is_cof_square : Prop := ∃ s : cof_square a b, s.f₁ = f₁ ∧ s.f₂ = f₂ variables {a b f₁ f₂} lemma is_cof_square.corner_cof (H : is_cof_square a b f₁ f₂) : ∃ (hf₁ : is_cof f₁) (hs : f₁ ≫ b = a ≫ f₂), is_cof ((pushout_by_cof f₁ a hf₁).is_pushout.induced b f₂ hs) := begin rcases H with ⟨c, hc₁, hc₂⟩, subst f₁, subst f₂, exact ⟨c.hf₁, c.hs, c.hf₂⟩ end lemma is_cof_square_comp (Hf : is_cof_square a b f₁ f₂) (Hg : is_cof_square b c g₁ g₂) (Hh₁ : h₁ = f₁ ≫ g₁) (Hh₂ : h₂ = f₂ ≫ g₂) : is_cof_square a c h₁ h₂ := begin rcases Hf with ⟨cf, hcf₁, hcf₂⟩, rcases Hg with ⟨cg, hcg₁, hcg₂⟩, subst f₁, subst f₂, subst g₁, subst g₂, subst h₁, subst h₂, exact ⟨cf.comp cg, rfl, rfl⟩ end end is_cof_square end homotopy_theory.cofibrations
b9a8fbc409fd27d086491b19ce062bc57ef5d81c
c3e8fac5ab7ca328e55bccf82a0207a97f96678c
/lean/src/ast.lean
78694345d070a77bede9b6dbb00d4975e33a4a72
[ "Unlicense" ]
permissive
Rotsor/brainfuck
941bb33862ce3e9d61f0454db5ca02942f4b5775
3e6f30f298b8ba76d0bc71b8b5a47cedaf2f0b97
refs/heads/master
1,619,718,778,100
1,532,913,653,000
1,532,913,653,000
121,682,141
0
0
null
null
null
null
UTF-8
Lean
false
false
397
lean
namespace brainfuck namespace ast -- AST inductive instruction : Type | left : instruction | right : instruction | plus : instruction | minus : instruction | print : instruction | ask : instruction | loop : list instruction -> instruction def program := list instruction instance : has_append(program) := ⟨ list.append ⟩ end ast end brainfuck
26da693c562f63734c1822e505f6ce544a57772b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/group.lean
028db113de07603fede833c5438a904e03b4c214
[ "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
19,285
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, Patrick Massot -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map end continuous_mul_group section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G : Prop := (continuous_neg : continuous (λa:G, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G : Prop := (continuous_inv : continuous (has_inv.inv : G → G)) variables [topological_space G] [group G] [topological_group G] export topological_group (continuous_inv) export topological_add_group (continuous_neg) @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg -- TODO @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } variable (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := begin have lim : tendsto has_inv.inv (𝓝 (1 : G)) (𝓝 1), { simpa only [one_inv] using tendsto_inv (1 : G) }, exact comap_eq_of_inverse _ inv_involutive.comp_self lim lim, end variable {G} @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v * w⁻¹ ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λ y : G, y * x) _ _ _, { funext x, simp }, { rw ← mul_right_inv x, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λ y : G, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → quotient N) := begin intros s s_op, change is_open ((coe : G → quotient N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, is_open_map_mul_right n s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : G → quotient N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : G → quotient N) ∘ (λ (a : G), a⁻¹)), exact continuous_quot_mk.comp continuous_inv end } attribute [instance] topological_add_group_quotient end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) @[priority 100] -- see Note [lower instance priority] instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := ⟨continuous_fst.add continuous_snd.neg⟩ export has_continuous_sub (continuous_sub) section has_continuous_sub variables [topological_space G] [has_sub G] [has_continuous_sub G] lemma filter.tendsto.sub {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λx, f x - g x) l (𝓝 (a - b)) := (continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) : continuous (λ x, f x - g x) := continuous_sub.comp $ hf.prod_mk hg lemma continuous_within_at.sub (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x - g x) s x := hf.sub hg lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := λ x hx, (hf x hx).sub (hg x hx) end has_continuous_sub lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) : comap (λy:G, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (G) [add_group_with_zero_nhd G] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space G := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z G) variables {G} lemma neg_Z : tendsto (λa:G, - a) (Z G) (Z G) := have tendsto (λa, (0:G)) (Z G) (Z G), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:G, 0 - a) (Z G) (Z G), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:G×G, p.1 + p.2) (Z G ×ᶠ Z G) (Z G) := suffices tendsto (λp:G×G, p.1 - -p.2) (Z G ×ᶠ Z G) (Z G), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set G} (hs : s ∈ Z G) : ∃ V ∈ Z G, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:G×G, a.1 + a.2) ⁻¹' s) ∈ Z G ×ᶠ Z G := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : G) : 𝓝 a = map (λx, x + a) (Z G) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:G) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:G, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z G).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z G := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add G := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, (a + b) + x) ∘ (λp:G×G,p.1 + p.2)) (Z G ×ᶠ Z G) (map (λx:G, (a + b) + x) (Z G)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group G := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, x - a) ∘ (λx:G, -x)) (Z G) (map (λx:G, x - a) (Z G)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma is_open.mul_left {s t : set G} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : G), a * x) '' t) := assume a, is_open_map_mul_left a t ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open.mul_right {s t : set G} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : G), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (G) lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space G] : regular_space G := ⟨assume s a hs ha, let f := λ p : G × G, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_fst.mul continuous_snd.inv, -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:G) (by simpa [f]) in begin use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩], apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set G, is_open V ∧ (1 : G) ∈ V ∧ K * V ⊆ U := begin let W : G → set G := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, continuous_mul_left x U hU, have h2W : ∀ x ∈ K, (1 : G) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, exists_open_nhds_one_mul_subset (mem_nhds_sets (h1W x) (h2W x.1 x.2)), let X : K → set G := λ x, (λ y, (x : G)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, continuous_mul_left x⁻¹ (V x) (hV x).1) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : G)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : G, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:G, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
e4ae4541bfd3d2f578b9dfd984876f8aadb6b367
0c0281448f624a53333195786d9730b1592ee3ac
/Automation.lean
c686933cde5aa76f28c7fb0ffc439b79b0232d91
[]
no_license
kindaro/lean_study
ce788f8dd1adaef2e12d6f94ab88685da34b0877
8219865eb9f068f132fe4ce0ae4a2fb76b1f5865
refs/heads/master
1,693,155,825,536
1,634,312,849,000
1,634,312,849,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,274
lean
open tactic meta def map: (expr → tactic unit) → list expr → tactic unit | f [] := failed | f (x :: xs) := f x <|> map f xs meta def size : expr → nat | (expr.app f a) := size f + size a | _ := 1 meta def sort_of_identifier: expr → string | (expr.var nat) := "var" | (expr.sort level) := "sort" | (expr.const name list_level) := "const" | (expr.mvar unique pretty type) := "mvar" | (expr.local_const unique pretty info type) := "local_const" | (expr.app expr₁ expr₂) := ("apply (" ++ (sort_of_identifier expr₁ ++ " (" ++ to_string expr₁ ++ ")) to " ++ sort_of_identifier expr₂)) | (expr.lam name info type body) := "lam" | (expr.pi var_name info var_type body) := "pi" | (expr.elet var_name type assignment body) := "elet" | (expr.macro macro_def list_expr) := "macro" meta def sort_of_goal: tactic unit := target >>= λ expression, trace (sort_of_identifier expression) meta def normalize_once: tactic unit := do context ← local_context, map (λ hypothesis, do cases hypothesis, return ()) context meta def normalize := repeat normalize_once meta def split_once: tactic unit := do intros, split, return () meta def split_all := repeat split_once meta def triviality := repeat (assumption <|> reflexivity) meta def existence := do context ← local_context, map (λ hypothesis, do existsi hypothesis) context meta def is_exists: expr → tactic bool := λ target, do match target with | expr.app (expr.const `Exists _) _ := return tt | expr.app recurse _ := is_exists recurse | _ := return ff end meta def is_target_exists: tactic bool := do target ← target, is_exists target meta def slice_and_dice := do target ← target, is_exists_target ← is_exists target, match is_exists_target with | tt := existence | ff := split >> intros >> return () end meta def crush_once: tactic unit := do intros, normalize, try (interactive.simp none none tt [ ] [ ] (interactive.loc.ns [none])), repeat (do slice_and_dice >> intros >> return ()), triviality meta def repeat_safely (operate: tactic unit): tactic unit := do current_target ← target, operate, next_target ← target, (unify current_target next_target >> return ()) <|> operate meta def crush := repeat crush_once
2e7fd1ce85a698c3d235b2d9e11e458486a10a53
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/topology/algebra/uniform_ring.lean
0837d618262f344a04cb12dc65dbab665b93f438
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
6,584
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Theory of topological rings with uniform structure. -/ import topology.algebra.group_completion topology.algebra.ring open classical set lattice filter topological_space add_comm_group local attribute [instance] classical.prop_decidable noncomputable theory namespace uniform_space.completion open dense_embedding uniform_space variables (α : Type*) [ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] [separated α] instance is_Z_bilin_mul : is_Z_bilin (λp:α×α, p.1 * p.2) := ⟨assume a a' b, add_mul a a' b, assume a b b', mul_add a b b'⟩ instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨λa b, extend (dense_embedding_coe.prod dense_embedding_coe) ((coe : α → completion α) ∘ (λp:α×α, p.1 * p.2)) (a, b)⟩ lemma coe_one : ((1 : α) : completion α) = 1 := rfl lemma continuous_mul' : continuous (λp:completion α×completion α, p.1 * p.2) := suffices continuous $ extend (dense_embedding_coe.prod dense_embedding_coe) $ ((coe : α → completion α) ∘ (λp:α×α, p.1 * p.2)), { convert this, ext ⟨a, b⟩, refl }, extend_Z_bilin dense_embedding_coe dense_embedding_coe (continuous.comp continuous_mul' (continuous_coe α)) section rules variables {α} lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := eq.symm (extend_e_eq (dense_embedding_coe.prod dense_embedding_coe) (a, b)) lemma continuous_mul {β : Type*} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := (continuous.prod_mk hf hg).comp (continuous_mul' α) end rules instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous_mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous_mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_mul (continuous_mul continuous_fst (continuous_snd.comp continuous_fst)) (continuous_snd.comp continuous_snd)) (continuous_mul continuous_fst (continuous_mul (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_mul continuous_fst (continuous_add (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd))) (continuous_add (continuous_mul continuous_fst (continuous_snd.comp continuous_fst)) (continuous_mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_mul (continuous_add continuous_fst (continuous_snd.comp continuous_fst)) (continuous_snd.comp continuous_snd)) (continuous_add (continuous_mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous_mul (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } instance is_ring_hom_coe : is_ring_hom (coe : α → completion α) := ⟨coe_one α, assume a b, coe_mul a b, assume a b, coe_add a b⟩ universe u instance is_ring_hom_extension {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] [complete_space β] [separated β] {f : α → β} [is_ring_hom f] (hf : continuous f) : is_ring_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { map_one := by rw [← coe_one, extension_coe hf, is_ring_hom.map_one f], map_add := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_add'.comp continuous_extension) (continuous_add (continuous_fst.comp continuous_extension) (continuous_snd.comp continuous_extension))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, is_add_group_hom.add f]), map_mul := assume a b, completion.induction_on₂ a b (is_closed_eq ((continuous_mul' α).comp continuous_extension) (_root_.continuous_mul (continuous_fst.comp continuous_extension) (continuous_snd.comp continuous_extension))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, is_ring_hom.map_mul f]) } end uniform_space.completion namespace uniform_space variables {α : Type*} lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext $ assume x y, group_separation_rel x y lemma ring_sep_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (⊥ : ideal α).closure.quotient := by rw [@ring_sep_rel α r]; refl def sep_quot_equiv_ring_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ (⊥ : ideal α).closure.quotient := quotient.congr $ assume x y, group_separation_rel x y /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ instance [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := by rw ring_sep_quot α; apply_instance instance [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := begin convert topological_ring_quotient (⊥ : ideal α).closure, { apply ring_sep_rel }, { dsimp [topological_ring_quotient_topology, quotient.topological_space, to_topological_space], congr, apply ring_sep_rel, apply ring_sep_rel }, { apply ring_sep_rel }, { simp [uniform_space.comm_ring] }, end end uniform_space
a066511cd5acd9237d906a210f8c2b3e46a05183
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Meta/DiscrTree.lean
53d67e819990400965d1ef1c0be38a5706654728
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
23,389
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.Meta.WHNF import Lean.Meta.DiscrTreeTypes namespace Lean.Meta.DiscrTree /-! (Imperfect) discrimination trees. We use a hybrid representation. - A `PersistentHashMap` for the root node which usually contains many children. - A sorted array of key/node pairs for inner nodes. The edges are labeled by keys: - Constant names (and arity). Universe levels are ignored. - Free variables (and arity). Thus, an entry in the discrimination tree may reference hypotheses from the local context. - Literals - Star/Wildcard. We use them to represent metavariables and terms we want to ignore. We ignore implicit arguments and proofs. - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc). We reduce terms using `TransparencyMode.reducible`. Thus, all reducible definitions in an expression `e` are unfolded before we insert it into the discrimination tree. Recall that projections from classes are **NOT** reducible. For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x` and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys respctively ``` ⟨Add.add, 4⟩, *, *, *, * ⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩ ``` That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`. We say the `Add.add` applications are the de-facto canonical forms in the metaprogramming framework. Moreover, it is the metaprogrammer's responsibility to re-pack applications such as `Nat.add a b` into `Add.add Nat inst a b`. Remark: we store the arity in the keys 1- To be able to implement the "skip" operation when retrieving "candidate" unifiers. 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`. -/ def Key.ctorIdx : Key s → Nat | .star => 0 | .other => 1 | .lit .. => 2 | .fvar .. => 3 | .const .. => 4 | .arrow => 5 | .proj .. => 6 def Key.lt : Key s → Key s → Bool | .lit v₁, .lit v₂ => v₁ < v₂ | .fvar n₁ a₁, .fvar n₂ a₂ => Name.quickLt n₁.name n₂.name || (n₁ == n₂ && a₁ < a₂) | .const n₁ a₁, .const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | .proj s₁ i₁, .proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂) | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx instance : LT (Key s) := ⟨fun a b => Key.lt a b⟩ instance (a b : Key s) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b)) def Key.format : Key s → Format | .star => "*" | .other => "◾" | .lit (Literal.natVal v) => Std.format v | .lit (Literal.strVal v) => repr v | .const k _ => Std.format k | .proj s i => Std.format s ++ "." ++ Std.format i | .fvar k _ => Std.format k.name | .arrow => "→" instance : ToFormat (Key s) := ⟨Key.format⟩ def Key.arity : (Key s) → Nat | .const _ a => a | .fvar _ a => a | .arrow => 2 | .proj .. => 1 | _ => 0 instance : Inhabited (Trie α s) := ⟨.node #[] #[]⟩ def empty : DiscrTree α s := { root := {} } partial def Trie.format [ToFormat α] : Trie α s → Format | .node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ Std.format vs) ++ Format.join (cs.toList.map fun ⟨k, c⟩ => Format.line ++ Format.paren (Std.format k ++ " => " ++ format c)) instance [ToFormat α] : ToFormat (Trie α s) := ⟨Trie.format⟩ partial def format [ToFormat α] (d : DiscrTree α s) : Format := let (_, r) := d.root.foldl (fun (p : Bool × Format) k c => (false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (Std.format k ++ " => " ++ Std.format c))) (true, Format.nil) Format.group r instance [ToFormat α] : ToFormat (DiscrTree α s) := ⟨format⟩ /-- The discrimination tree ignores implicit arguments and proofs. We use the following auxiliary id as a "mark". -/ private def tmpMVarId : MVarId := { name := `_discr_tree_tmp } private def tmpStar := mkMVar tmpMVarId instance : Inhabited (DiscrTree α s) where default := {} /-- Return true iff the argument should be treated as a "wildcard" by the discrimination tree. - We ignore proofs because of proof irrelevance. It doesn't make sense to try to index their structure. - We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical. Moreover, we may have many definitionally equal terms floating around. Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`. - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them, and may not even understand why some simplification rule is not firing. However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`, where `Nat` is an implicit argument. Thus, we would add the path ``` Decidable -> Eq -> * -> * -> * -> [Nat.decEq] ``` to the discrimination tree IF we ignored the implict `Nat` argument. This would be BAD since **ALL** decidable equality instances would be in the same path. So, we index implicit arguments if they are types. This setting seems sensible for simplification theorems such as: ``` forall (x y : Unit), (@Eq Unit x y) = true ``` If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate simplification theorem for any equality in our goal. Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation, and `ignoreArg` would return true for any term of the form `noIndexing t`. -/ private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do if h : i < infos.size then let info := infos.get ⟨i, h⟩ if info.isInstImplicit then return true else if info.isImplicit || info.isStrictImplicit then return not (← isType a) else isProof a else isProof a private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr) | i, .app f a, todo => do if (← ignoreArg a i infos) then pushArgsAux infos (i-1) f (todo.push tmpStar) else pushArgsAux infos (i-1) f (todo.push a) | _, _, todo => return todo /-- Return true if `e` is one of the following - A nat literal (numeral) - `Nat.zero` - `Nat.succ x` where `isNumeral x` - `OfNat.ofNat _ x _` where `isNumeral x` -/ private partial def isNumeral (e : Expr) : Bool := if e.isNatLit then true else let f := e.getAppFn if !f.isConst then false else let fName := f.constName! if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg! else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1) else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true else false private def isNatType (e : Expr) : MetaM Bool := return (← whnf e).isConstOf ``Nat /-- Return true if `e` is one of the following - `Nat.add _ k` where `isNumeral k` - `Add.add Nat _ _ k` where `isNumeral k` - `HAdd.hAdd _ Nat _ _ k` where `isNumeral k` - `Nat.succ _` This function assumes `e.isAppOf fName` -/ private def isOffset (fName : Name) (e : Expr) : MetaM Bool := do if fName == ``Nat.add && e.getAppNumArgs == 2 then return isNumeral e.appArg! else if fName == ``Add.add && e.getAppNumArgs == 4 then if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false else return fName == ``Nat.succ && e.getAppNumArgs == 1 /-- TODO: add hook for users adding their own functions for controlling `shouldAddAsStar` Different `DiscrTree` users may populate this set using, for example, attributes. Remark: we currently tag `Nat.zero` and "offset" terms to avoid having to add special support for `Expr.lit` and offset terms. Example, suppose the discrimination tree contains the entry `Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`. In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/ private def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do if fName == ``Nat.zero then return true else isOffset fName e def mkNoindexAnnotation (e : Expr) : Expr := mkAnnotation `noindex e def hasNoindexAnnotation (e : Expr) : Bool := annotation? `noindex e |>.isSome /-- Reduction procedure for the discrimination tree indexing. The parameter `simpleReduce` controls how aggressive the term is reduced. The parameter at type `DiscrTree` controls this value. See comment at `DiscrTree`. -/ partial def reduce (e : Expr) (simpleReduce : Bool) : MetaM Expr := do let e ← whnfCore e (simpleReduceOnly := simpleReduce) match (← unfoldDefinition? e) with | some e => reduce e simpleReduce | none => match e.etaExpandedStrict? with | some e => reduce e simpleReduce | none => return e /-- Return `true` if `fn` is a "bad" key. That is, `pushArgs` would add `Key.other` or `Key.star`. We use this function when processing "root terms, and will avoid unfolding terms. Note that without this trick the pattern `List.map f ∘ List.map g` would be mapped into the key `Key.other` since the function composition `∘` would be unfolded and we would get `fun x => List.map g (List.map f x)` -/ private def isBadKey (fn : Expr) : Bool := match fn with | .lit .. => false | .const .. => false | .fvar .. => false | .proj .. => false | .forallE _ _ b _ => b.hasLooseBVars | _ => true /-- Reduce `e` until we get an irreducible term (modulo current reducibility setting) or the resulting term is a bad key (see comment at `isBadKey`). We use this method instead of `reduce` for root terms at `pushArgs`. -/ private partial def reduceUntilBadKey (e : Expr) (simpleReduce : Bool) : MetaM Expr := do let e ← step e match e.etaExpandedStrict? with | some e => reduceUntilBadKey e simpleReduce | none => return e where step (e : Expr) := do let e ← whnfCore e (simpleReduceOnly := simpleReduce) match (← unfoldDefinition? e) with | some e' => if isBadKey e'.getAppFn then return e else step e' | none => return e /-- whnf for the discrimination tree module -/ def reduceDT (e : Expr) (root : Bool) (simpleReduce : Bool) : MetaM Expr := if root then reduceUntilBadKey e simpleReduce else reduce e simpleReduce /- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/ private def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key s × Array Expr) := do if hasNoindexAnnotation e then return (.star, todo) else let e ← reduceDT e root (simpleReduce := s) let fn := e.getAppFn let push (k : Key s) (nargs : Nat) : MetaM (Key s × Array Expr) := do let info ← getFunInfoNArgs fn nargs let todo ← pushArgsAux info.paramInfo (nargs-1) e todo return (k, todo) match fn with | .lit v => return (.lit v, todo) | .const c _ => unless root do if (← shouldAddAsStar c e) then return (.star, todo) let nargs := e.getAppNumArgs push (.const c nargs) nargs | .proj s i a .. => return (.proj s i, todo.push a) | .fvar fvarId => let nargs := e.getAppNumArgs push (.fvar fvarId nargs) nargs | .mvar mvarId => if mvarId == tmpMVarId then -- We use `tmp to mark implicit arguments and proofs return (.star, todo) else if (← mvarId.isReadOnlyOrSyntheticOpaque) then return (.other, todo) else return (.star, todo) | .forallE _ d b _ => if b.hasLooseBVars then return (.other, todo) else return (.arrow, todo.push d |>.push b) | _ => return (.other, todo) partial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array (Key s)) : MetaM (Array (Key s)) := do if todo.isEmpty then return keys else let e := todo.back let todo := todo.pop let (k, todo) ← pushArgs root todo e mkPathAux false todo (keys.push k) private def initCapacity := 8 def mkPath (e : Expr) : MetaM (Array (Key s)) := do withReducible do let todo : Array Expr := .mkEmpty initCapacity let keys : Array (Key s) := .mkEmpty initCapacity mkPathAux (root := true) (todo.push e) keys private partial def createNodes (keys : Array (Key s)) (v : α) (i : Nat) : Trie α s := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := createNodes keys v (i+1) .node #[] #[(k, c)] else .node #[v] #[] private def insertVal [BEq α] (vs : Array α) (v : α) : Array α := if vs.contains v then vs else vs.push v private partial def insertAux [BEq α] (keys : Array (Key s)) (v : α) : Nat → Trie α s → Trie α s | i, .node vs cs => if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing (fun _ => let c := createNodes keys v (i+1); (k, c)) (k, default) .node vs c else .node (insertVal vs v) cs def insertCore [BEq α] (d : DiscrTree α s) (keys : Array (Key s)) (v : α) : DiscrTree α s := if keys.isEmpty then panic! "invalid key sequence" else let k := keys[0]! match d.root.find? k with | none => let c := createNodes keys v 1 { root := d.root.insert k c } | some c => let c := insertAux keys v 1 c { root := d.root.insert k c } def insert [BEq α] (d : DiscrTree α s) (e : Expr) (v : α) : MetaM (DiscrTree α s) := do let keys ← mkPath e return d.insertCore keys v private def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key s × Array Expr) := do let e ← reduceDT e root (simpleReduce := s) match e.getAppFn with | .lit v => return (.lit v, #[]) | .const c _ => if (← getConfig).isDefEqStuckEx && e.hasExprMVar then if (← isReducible c) then /- `e` is a term `c ...` s.t. `c` is reducible and `e` has metavariables, but it was not unfolded. This can happen if the metavariables in `e` are "blocking" smart unfolding. If `isDefEqStuckEx` is enabled, then we must throw the `isDefEqStuck` exception to postpone TC resolution. Here is an example. Suppose we have ``` inductive Ty where | bool | fn (a ty : Ty) @[reducible] def Ty.interp : Ty → Type | bool => Bool | fn a b => a.interp → b.interp ``` and we are trying to synthesize `BEq (Ty.interp ?m)` -/ Meta.throwIsDefEqStuck else if let some matcherInfo := isMatcherAppCore? (← getEnv) e then -- A matcher application is stuck is one of the discriminants has a metavariable let args := e.getAppArgs for arg in args[matcherInfo.getFirstDiscrPos: matcherInfo.getFirstDiscrPos + matcherInfo.numDiscrs] do if arg.hasExprMVar then Meta.throwIsDefEqStuck else if (← isRec c) then /- Similar to the previous case, but for `match` and recursor applications. It may be stuck (i.e., did not reduce) because of metavariables. -/ Meta.throwIsDefEqStuck let nargs := e.getAppNumArgs return (.const c nargs, e.getAppRevArgs) | .fvar fvarId => let nargs := e.getAppNumArgs return (.fvar fvarId nargs, e.getAppRevArgs) | .mvar mvarId => if isMatch then return (.other, #[]) else do let ctx ← read if ctx.config.isDefEqStuckEx then /- When the configuration flag `isDefEqStuckEx` is set to true, we want `isDefEq` to throw an exception whenever it tries to assign a read-only metavariable. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`. That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)` where `?m` is a read-only metavariable, and the discrimination tree contains the keys `HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as a regular metavariable here, otherwise we return the empty set of candidates. This is incorrect because it is equivalent to saying that there is no solution even if the caller assigns `?m` and try again. -/ return (.star, #[]) else if (← mvarId.isReadOnlyOrSyntheticOpaque) then return (.other, #[]) else return (.star, #[]) | .proj s i a .. => return (.proj s i, #[a]) | .forallE _ d b _ => if b.hasLooseBVars then return (.other, #[]) else return (.arrow, #[d, b]) | _ => return (.other, #[]) private abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key s × Array Expr) := getKeyArgs e (isMatch := true) (root := root) private abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key s × Array Expr) := getKeyArgs e (isMatch := false) (root := root) private def getStarResult (d : DiscrTree α s) : Array α := let result : Array α := .mkEmpty initCapacity match d.root.find? .star with | none => result | some (.node vs _) => result ++ vs private abbrev findKey (cs : Array (Key s × Trie α s)) (k : Key s) : Option (Key s × Trie α s) := cs.binSearch (k, default) (fun a b => a.1 < b.1) private partial def getMatchLoop (todo : Array Expr) (c : Trie α s) (result : Array α) : MetaM (Array α) := do match c with | .node vs cs => if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let first := cs[0]! /- Recall that `Key.star` is the minimal key -/ let (k, args) ← getMatchKeyArgs e (root := false) /- We must always visit `Key.star` edges since they are wildcards. Thus, `todo` is not used linearly when there is `Key.star` edge and there is an edge for `k` and `k != Key.star`. -/ let visitStar (result : Array α) : MetaM (Array α) := if first.1 == .star then getMatchLoop todo first.2 result else return result let visitNonStar (k : Key s) (args : Array Expr) (result : Array α) : MetaM (Array α) := match findKey cs k with | none => return result | some c => getMatchLoop (todo ++ args) c.2 result let result ← visitStar result match k with | .star => return result /- Note: dep-arrow vs arrow Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`. A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child. -/ | .arrow => visitNonStar .other #[] (← visitNonStar k args result) | _ => visitNonStar k args result private def getMatchRoot (d : DiscrTree α s) (k : Key s) (args : Array Expr) (result : Array α) : MetaM (Array α) := match d.root.find? k with | none => return result | some c => getMatchLoop args c result private def getMatchCore (d : DiscrTree α s) (e : Expr) : MetaM (Key s × Array α) := withReducible do let result := getStarResult d let (k, args) ← getMatchKeyArgs e (root := true) match k with | .star => return (k, result) /- See note about "dep-arrow vs arrow" at `getMatchLoop` -/ | .arrow => return (k, (← getMatchRoot d k args (← getMatchRoot d .other #[] result))) | _ => return (k, (← getMatchRoot d k args result)) /-- Find values that match `e` in `d`. -/ def getMatch (d : DiscrTree α s) (e : Expr) : MetaM (Array α) := return (← getMatchCore d e).2 /-- Similar to `getMatch`, but returns solutions that are prefixes of `e`. We store the number of ignored arguments in the result.-/ partial def getMatchWithExtra (d : DiscrTree α s) (e : Expr) : MetaM (Array (α × Nat)) := do let (k, result) ← getMatchCore d e let result := result.map (·, 0) if !e.isApp then return result else if !(← mayMatchPrefix k) then return result else go e.appFn! 1 result where mayMatchPrefix (k : Key s) : MetaM Bool := let cont (k : Key s) : MetaM Bool := if d.root.find? k |>.isSome then return true else mayMatchPrefix k match k with | .const f (n+1) => cont (.const f n) | .fvar f (n+1) => cont (.fvar f n) | _ => return false go (e : Expr) (numExtra : Nat) (result : Array (α × Nat)) : MetaM (Array (α × Nat)) := do let result := result ++ (← getMatch d e).map (., numExtra) if e.isApp then go e.appFn! (numExtra + 1) result else return result partial def getUnify (d : DiscrTree α s) (e : Expr) : MetaM (Array α) := withReducible do let (k, args) ← getUnifyKeyArgs e (root := true) match k with | .star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result | _ => let result := getStarResult d match d.root.find? k with | none => return result | some c => process 0 args c result where process (skip : Nat) (todo : Array Expr) (c : Trie α s) (result : Array α) : MetaM (Array α) := do match skip, c with | skip+1, .node _ cs => if cs.isEmpty then return result else cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result | 0, .node vs cs => do if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let (k, args) ← getUnifyKeyArgs e (root := false) let visitStar (result : Array α) : MetaM (Array α) := let first := cs[0]! if first.1 == .star then process 0 todo first.2 result else return result let visitNonStar (k : Key s) (args : Array Expr) (result : Array α) : MetaM (Array α) := match findKey cs k with | none => return result | some c => process 0 (todo ++ args) c.2 result match k with | .star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows | .arrow => visitNonStar .other #[] (← visitNonStar k args (← visitStar result)) | _ => visitNonStar k args (← visitStar result) end Lean.Meta.DiscrTree
862248aedf43eb2184963ce0b39b8677117c5a2d
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Meta/Tactic/Clear.lean
d0b5f966cab07dd2b5a22dfc7a994e01be4faf51
[ "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
1,459
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Util namespace Lean namespace Meta def clear (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId := withMVarContext mvarId $ do checkNotAssigned mvarId `clear; lctx ← getLCtx; unless (lctx.contains fvarId) $ throwTacticEx `clear mvarId ("unknown variable '" ++ mkFVar fvarId ++ "'"); tag ← getMVarTag mvarId; mctx ← getMCtx; lctx.forM $ fun localDecl => unless (localDecl.fvarId == fvarId) $ when (mctx.localDeclDependsOn localDecl fvarId) $ throwTacticEx `clear mvarId ("variable '" ++ localDecl.toExpr ++ "' depends on '" ++ mkFVar fvarId ++ "'"); mvarDecl ← getMVarDecl mvarId; when (mctx.exprDependsOn mvarDecl.type fvarId) $ throwTacticEx `clear mvarId ("taget depends on '" ++ mkFVar fvarId ++ "'"); let lctx := lctx.erase fvarId; localInsts ← getLocalInstances; let localInsts := match localInsts.findIdx? $ fun localInst => localInst.fvar.fvarId! == fvarId with | none => localInsts | some idx => localInsts.eraseIdx idx; newMVar ← mkFreshExprMVarAt lctx localInsts mvarDecl.type MetavarKind.syntheticOpaque tag; assignExprMVar mvarId newMVar; pure newMVar.mvarId! def tryClear (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId := clear mvarId fvarId <|> pure mvarId end Meta end Lean
262b8dce8cb4289aa3c0825da4f6c3606f7c40cf
315b4184091c669ce8e5e07f9b24473c4bcfbaaf
/library/init/meta/tactic.lean
08db2d815ecf8a3a24c4a3b05f7768325914d2c8
[ "Apache-2.0" ]
permissive
haraldschilly/lean
78404910ad4c258cdf84e0509e4348c1525e57a9
d01e2d7ae8250e8f69139d8cb37950079e76ca9d
refs/heads/master
1,619,977,395,095
1,517,501,044,000
1,517,940,670,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,648
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state /-- Create a tactic state with an empty local context and a dummy goal. -/ meta constant mk_empty : environment → options → tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, iterate_at_most n t) <|> skip /-- (iterate_exactly n t) : execute t n times -/ meta def iterate_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, iterate_exactly n t meta def iterate : tactic unit → tactic unit := iterate_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨has_map.map to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /-- zeta reduction -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (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 meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name (n : name) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool meta constant mk_fresh_name : tactic name /-- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /-- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- Goals can be tagged using a list of names. -/ def tag : Type := list name /-- Enable/disable goal tagging -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing is goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change meta def unsafe_change (e : expr) : tactic unit := change e ff meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) : tactic unit := do c ← mk_const c, apply c, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list name) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ t, t.1) else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (do r ← cases_core h ids md, all_goals (intron n), return $ r.map (λ t, t.1)) meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def unsafe_monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
53aab682472b2621f8bfe96511472fc166c26fb9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/padics/padic_numbers.lean
c11594bed6308881be932742cf97ae955e48e093
[ "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
40,177
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 -/ import analysis.normed_space.basic import number_theory.padics.padic_norm /-! # p-adic numbers This file defines the p-adic numbers (rationals) `ℚ_p` as the completion of `ℚ` with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to `ℚ_p`, that `ℚ` is embedded in `ℚ_p`, and that `ℚ_p` is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on `ℚ_p` * `padic.add_valuation` : the additive `p`-adic valuation on `ℚ_p`, with values in `with_top ℤ`. ## Notation We introduce the notation `ℚ_[p]` for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. `ℚ_p` inherits a field structure from this construction. The extension of the norm on ℚ to `ℚ_p` is *not* analogous to extending the absolute value to ℝ, and hence the proof that `ℚ_p` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on `ℚ_p`. To instantiate `ℚ_p` as a normed field, we must cast this into a ℝ-valued norm. The `ℝ`-valued norm, using notation `∥ ∥` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `∥ ∥` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouvêa, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ (max_le_iff.1 hn).2 _ (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ← padic_norm.neg (f m) at hne, have hnam := add_eq_max_of_ne hne, rw [padic_norm.neg, max_comm] at hnam, rw [← hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf le_rfl hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : 0 ≤ f.norm := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := begin apply stationary_point_spec hf, { apply le_max_left }, { exact le_rfl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { exact le_rfl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { exact le_rfl } end end embedding section valuation open cau_seq variables {p : ℕ} [fact p.prime] /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation (f : padic_seq p) : ℤ := if hf : f ≈ 0 then 0 else padic_val_rat p (f (stationary_point hf)) lemma norm_eq_pow_val {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm = p^(-f.valuation : ℤ) := begin rw [norm, valuation, dif_neg hf, dif_neg hf, padic_norm, if_neg], intro H, apply cau_seq.not_lim_zero_of_not_congr_zero hf, intros ε hε, use (stationary_point hf), intros n hn, rw stationary_point_spec hf le_rfl hn, simpa [H] using hε end lemma val_eq_iff_norm_eq {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : f.valuation = g.valuation ↔ f.norm = g.norm := begin rw [norm_eq_pow_val hf, norm_eq_pow_val hg, ← neg_inj, zpow_inj], { exact_mod_cast (fact.out p.prime).pos }, { exact_mod_cast (fact.out p.prime).ne_one } end end valuation end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl >> tactic.skip), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp only [hf, hg, norm, dif_pos, zero_mul] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp only [hf, hg, norm, dif_pos, mul_zero] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_values_discrete (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (z : ℤ), a.norm = ↑p ^ (-z)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.values_discrete hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.1.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hlt : padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf))) : false := begin have hpn : 0 < padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)), from sub_pos_of_lt hlt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : N ≤ i, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hlt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [← padic_norm.neg (g i)] at h, let hpnem := add_eq_max_of_ne hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hlt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf)))) with hlt hnlt, { exact norm_eq_of_equiv_aux hf hg hfg h hlt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hnlt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_of_le_left (norm_nonneg _), by simpa only [hfg, norm, ne.def, le_max_iff, cau_seq.add_apply, not_true, dif_pos] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa only [sub_zero, add_sub_cancel] using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa only [add_sub_cancel', sub_zero] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp only [hf, hg, norm, dif_pos] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp only [h, forall_const, eq_self_iff_true]) hg, begin simp only [hg, hf, norm, dif_neg, not_false_iff], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, exact le_rfl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, exact le_rfl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa only [sub_zero, sub_neg_eq_add], have f.norm = (-g).norm, from norm_equiv this, by simpa only [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa only [sub_zero, add_sub_cancel], have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa only [sub_zero], have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, exact padic_norm.add_eq_max_of_ne hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] instance : field (ℚ_[p]) := Cauchy.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : comm_ring (ℚ_[p]) := Cauchy.comm_ring instance : ring (ℚ_[p]) := Cauchy.ring instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk variables (p) lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq, eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := rat.cast_add @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := rat.cast_neg @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := rat.cast_mul @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := rat.cast_sub @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := rat.cast_div @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl end completion end padic /-- The rational-valued p-adic norm on `ℚ_p` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contra' h, cases cauchy₂ f hε with N hN, rcases h N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases em (N ≤ stationary_point hne) with hgen hngen, { apply hN _ hgen _ hi }, { have := stationary_point_spec hne le_rfl (le_of_not_le hngen), rw ← this, exact hN _ le_rfl _ hi } end protected lemma nonneg (q : ℚ_[p]) : 0 ≤ padic_norm_e q := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (q : ℚ_[p]) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_values_discrete f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [fact p.prime] (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (stationary_point hne' ≤ N) with hle hle, { have := eq.symm (this le_rfl hle), simp only [const_apply, sub_apply, padic_norm.zero, sub_self] at this, simpa only [this] }, { exact hN _ (lt_of_not_ge hle).le _ le_rfl } } end⟩ variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : 0 < (1 / ((n + 1): ℚ)) := div_pos zero_lt_one (by exact_mod_cast succ_pos _) /-- `lim_seq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the same limit point as `f`. -/ def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - (lim_seq f i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h ((div_le_iff' $ by exact_mod_cast succ_pos _).mpr _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact (div_le_iff hε).mp (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : 0 < ε / 3, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((lim_seq f j - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring_nf at this ⊢, rw [← padic_norm_e.eq_padic_norm'], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp only [bit0, bit1, mul_add, mul_one] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa only [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { exact hN2 _ (le_of_max_le_right hj) _ (le_max_right _ _) } } }, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show 0 < ε / 2, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show 0 < ε / 2, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring_nf at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist := dist, dist_comm := λ x y, by unfold dist; rw ← padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'], norm := norm, .. padic.field, .. padic.metric_space p } instance is_absolute_value : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : fact p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt_trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm'] end @[simp] lemma norm_p : ∥(p : ℚ_[p])∥ = p⁻¹ := begin have p₀ : p ≠ 0 := hp.1.ne_zero, have p₁ : p ≠ 1 := hp.1.ne_one, rw ← @rat.cast_coe_nat ℝ _ p, rw ← @rat.cast_coe_nat (ℚ_[p]) _ p, simp [p₀, p₁, norm, padic_norm, padic_val_rat, padic_val_int, zpow_neg, -rat.cast_coe_nat], end lemma norm_p_lt_one : ∥(p : ℚ_[p])∥ < 1 := begin rw norm_p, apply inv_lt_one, exact_mod_cast hp.1.one_lt end @[simp] lemma norm_p_pow (n : ℤ) : ∥(p^n : ℚ_[p])∥ = p^-n := by rw [norm_zpow, norm_p]; field_simp instance : nontrivially_normed_field ℚ_[p] := { non_trivial := ⟨p⁻¹, begin rw [norm_inv, norm_p, inv_inv], exact_mod_cast hp.1.one_lt end⟩, .. padic.normed_field p } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_values_discrete f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ /--`rat_norm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number. The lemma `padic_norm_e.eq_rat_norm` asserts `∥q∥ = rat_norm q`. -/ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : { rat . num := n, denom := d, pos := hn, cop := hd } ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_zpow_of_nonzero hnz', padic_val_rat, neg_sub, padic_val_nat.eq_zero_of_not_dvd hq], norm_cast, rw [zero_sub, zpow_neg, zpow_coe_nat], apply inv_le_one, { norm_cast, apply one_le_pow, exact hp.1.pos } end theorem norm_int_le_one (z : ℤ) : ∥(z : ℚ_[p])∥ ≤ 1 := suffices ∥((z : ℚ) : ℚ_[p])∥ ≤ 1, by simpa, norm_rat_le_one $ by simp [hp.1.ne_one] lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k := begin split, { intro h, contrapose! h, apply le_of_eq, rw eq_comm, calc ∥(k : ℚ_[p])∥ = ∥((k : ℚ) : ℚ_[p])∥ : by { norm_cast } ... = padic_norm p k : padic_norm_e.eq_padic_norm _ ... = 1 : _, rw padic_norm, split_ifs with H, { exfalso, apply h, norm_cast at H, rw H, apply dvd_zero }, { norm_cast at H ⊢, convert zpow_zero _, rw [neg_eq_zero, padic_val_rat.of_int], norm_cast, apply padic_val_int.eq_zero_of_not_dvd h } }, { rintro ⟨x, rfl⟩, push_cast, rw padic_norm_e.mul, calc _ ≤ ∥(p : ℚ_[p])∥ * 1 : mul_le_mul le_rfl (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_e.norm_p], apply inv_lt_one, exact_mod_cast hp.1.one_lt } } end lemma norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) : ∥(k : ℚ_[p])∥ ≤ (↑p)^(-n : ℤ) ↔ ↑(p^n) ∣ k := begin have : (p : ℝ) ^ (-n : ℤ) = ↑((p ^ (-n : ℤ) : ℚ)), {simp}, rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]), by norm_cast, eq_padic_norm, this], norm_cast, rw ← padic_norm.dvd_iff_norm_le end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [hp : fact p.prime] include hp set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt_trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ le_rfl)) (hf _) open filter set instance : complete_space ℚ_[p] := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℚ_[p] norm := ⟨u, metric.cauchy_seq_iff'.mp hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], exact this.imp (λ N hN n hn, hε (hN n hn)) end /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the p-adic valuation on rationals to `ℚ_[p]`. -/ def valuation : ℚ_[p] → ℤ := quotient.lift (@padic_seq.valuation p _) (λ f g h, begin by_cases hf : f ≈ 0, { have hg : g ≈ 0, from setoid.trans (setoid.symm h) hf, simp [hf, hg, padic_seq.valuation] }, { have hg : ¬ g ≈ 0, from (λ hg, hf (setoid.trans h hg)), rw padic_seq.val_eq_iff_norm_eq hf hg, exact padic_seq.norm_equiv h } end) @[simp] lemma valuation_zero : valuation (0 : ℚ_[p]) = 0 := dif_pos ((const_equiv p).2 rfl) @[simp] lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := begin change dite (cau_seq.const (padic_norm p) 1 ≈ _) _ _ = _, have h : ¬ cau_seq.const (padic_norm p) 1 ≈ 0, { assume H, erw const_equiv p at H, exact one_ne_zero H }, rw dif_neg h, simp end lemma norm_eq_pow_val {x : ℚ_[p]} : x ≠ 0 → ∥x∥ = p^(-x.valuation) := begin apply quotient.induction_on' x, clear x, intros f hf, change (padic_seq.norm _ : ℝ) = (p : ℝ) ^ -padic_seq.valuation _, rw padic_seq.norm_eq_pow_val, change ↑((p : ℚ) ^ -padic_seq.valuation f) = (p : ℝ) ^ -padic_seq.valuation f, { rw [rat.cast_zpow, rat.cast_coe_nat] }, { apply cau_seq.not_lim_zero_of_not_congr_zero, contrapose! hf, apply quotient.sound, simpa using hf } end @[simp] lemma valuation_p : valuation (p : ℚ_[p]) = 1 := begin have h : (1 : ℝ) < p := by exact_mod_cast (fact.out p.prime).one_lt, refine neg_injective ((zpow_strict_mono h).injective $ (norm_eq_pow_val _).symm.trans _), { exact_mod_cast (fact.out p.prime).ne_zero }, { simp } end lemma valuation_map_add {x y : ℚ_[p]} (hxy : x + y ≠ 0) : min (valuation x) (valuation y) ≤ valuation (x + y) := begin by_cases hx : x = 0, { rw [hx, zero_add], exact min_le_right _ _ }, { by_cases hy : y = 0, { rw [hy, add_zero], exact min_le_left _ _ }, { have h_norm : ∥x + y∥ ≤ (max ∥x∥ ∥y∥) := padic_norm_e.nonarchimedean x y, have hp_one : (1 : ℝ) < p, { rw [← nat.cast_one, nat.cast_lt], exact nat.prime.one_lt hp.elim }, rwa [norm_eq_pow_val hx, norm_eq_pow_val hy, norm_eq_pow_val hxy, zpow_le_max_iff_min_le hp_one] at h_norm } } end @[simp] lemma valuation_map_mul {x y : ℚ_[p]} (hx : x ≠ 0) (hy : y ≠ 0) : valuation (x * y) = valuation x + valuation y := begin have h_norm : ∥x * y∥ = ∥x∥ * ∥y∥ := norm_mul x y, have hp_ne_one : (p : ℝ) ≠ 1, { rw [← nat.cast_one, ne.def, nat.cast_inj], exact nat.prime.ne_one hp.elim }, have hp_pos : (0 : ℝ) < p, { rw [← nat.cast_zero, nat.cast_lt], exact nat.prime.pos hp.elim }, rw [norm_eq_pow_val hx, norm_eq_pow_val hy, norm_eq_pow_val (mul_ne_zero hx hy), ← zpow_add₀ (ne_of_gt hp_pos), zpow_inj hp_pos hp_ne_one, ← neg_add, neg_inj] at h_norm, exact h_norm end /-- The additive p-adic valuation on `ℚ_p`, with values in `with_top ℤ`. -/ def add_valuation_def : ℚ_[p] → (with_top ℤ) := λ x, if x = 0 then ⊤ else x.valuation @[simp] lemma add_valuation.map_zero : add_valuation_def (0 : ℚ_[p]) = ⊤ := by simp only [add_valuation_def, if_pos (eq.refl _)] @[simp] lemma add_valuation.map_one : add_valuation_def (1 : ℚ_[p]) = 0 := by simp only [add_valuation_def, if_neg one_ne_zero, valuation_one, with_top.coe_zero] lemma add_valuation.map_mul (x y : ℚ_[p]) : add_valuation_def (x * y) = add_valuation_def x + add_valuation_def y := begin simp only [add_valuation_def], by_cases hx : x = 0, { rw [hx, if_pos (eq.refl _), zero_mul, if_pos (eq.refl _), with_top.top_add] }, { by_cases hy : y = 0, { rw [hy, if_pos (eq.refl _), mul_zero, if_pos (eq.refl _), with_top.add_top] }, { rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_top.coe_add, with_top.coe_eq_coe, valuation_map_mul hx hy] }} end lemma add_valuation.map_add (x y : ℚ_[p]) : min (add_valuation_def x) (add_valuation_def y) ≤ add_valuation_def (x + y) := begin simp only [add_valuation_def], by_cases hxy : x + y = 0, { rw [hxy, if_pos (eq.refl _)], exact le_top }, { by_cases hx : x = 0, { simp only [hx, if_pos (eq.refl _), min_eq_right, le_top, zero_add, le_refl] }, { by_cases hy : y = 0, { simp only [hy, if_pos (eq.refl _), min_eq_left, le_top, add_zero, le_refl] }, { rw [if_neg hx, if_neg hy, if_neg hxy, ← with_top.coe_min, with_top.coe_le_coe], exact valuation_map_add hxy }}} end /-- The additive `p`-adic valuation on `ℚ_p`, as an `add_valuation`. -/ def add_valuation : add_valuation ℚ_[p] (with_top ℤ) := add_valuation.of add_valuation_def add_valuation.map_zero add_valuation.map_one add_valuation.map_add add_valuation.map_mul @[simp] lemma add_valuation.apply {x : ℚ_[p]} (hx : x ≠ 0) : x.add_valuation = x.valuation := by simp only [add_valuation, add_valuation.of_apply, add_valuation_def, if_neg hx] section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℚ_[p]) (n : ℤ) : ∥x∥ ≤ p ^ n ↔ ∥x∥ < p ^ (n + 1) := begin have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ), { apply nat.zpow_pos_of_pos, exact hp.1.pos }, by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)] }, rw norm_eq_pow_val hx0, have h1p : 1 < (p : ℝ), { exact_mod_cast hp.1.one_lt }, have H := zpow_strict_mono h1p, rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff] end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℚ_[p]) (n : ℤ) : ∥x∥ < p ^ n ↔ ∥x∥ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] end norm_le_iff end padic
6694d12b8ae7337359d44f77a40616e33dffaa54
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/typeMismatch.lean
e5c53a1fd2ef505af49a935e82b8f12908e667fb
[ "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
197
lean
import Lean new_frontend -- Test type mismatch error messages for "liftable" methods def test (x : Nat) : IO Nat := IO.println "" open Lean def test (x : Expr) : MetaM Unit := Meta.isDefEq x x
bf68b82d735f89cf6e846181270b876633464760
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/not_in_use/classical_acceleration.lean
be57c488d29746fc24c811aef2766e51bbe13fe7
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
493
lean
import ...phys.src.classical_acceleration import .classical_velocity import .classical_time namespace lang.classicalAcceleration structure var : Type := mk :: (num : ℕ) def varEq : var → var → bool | v1 v2 := v1.num=v2.num def env := (var → classicalAcceleration) inductive expr : Type | lit (v : classicalAcceleration) | var (v : var) | div (v : lang.classicalVelocity.expr) (t : lang.classicalTime.expr) def init := λ v : var, worldAcceleration end lang.classicalAcceleration
c4f9deebbda04ac7b6ef616ad4524e2d9d0e3359
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Init/Logic.lean
31fc739dc4df71ecb27a6021eac35fb76b779296
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
22,965
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ import Mathlib.Tactic.Basic import Mathlib.Tactic.Ext -- Workaround for not being able to add ext lemmas from other modules. @[ext] private def funext' := @funext @[ext] private def propext' := @propext @[ext] protected lemma Unit.ext (x y : Unit) : x = y := Subsingleton.allEq _ _ @[ext] protected lemma PUnit.ext (x y : Unit) : x = y := Subsingleton.allEq _ _ @[simp] theorem opt_param_eq (α : Sort u) (default : α) : optParam α default = α := optParam_eq α default theorem Not.intro {a : Prop} (h : a → False) : ¬ a := h /- not -/ def non_contradictory (a : Prop) : Prop := ¬¬a theorem non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := λ hna : ¬a => absurd ha hna /- eq -/ -- proof irrelevance is built in def proof_irrel := @proofIrrel def congr_fun := @congrFun def congr_arg := @congrArg lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma not_of_eq_false {p : Prop} (h : p = False) : ¬p := fun hp => h ▸ hp lemma cast_proof_irrel (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl /- ne -/ @[simp] lemma Ne.def {α : Sort u} (a b : α) : (a ≠ b) = ¬ (a = b) := rfl def eq_rec_heq := @eqRec_heq lemma heq_of_eq_rec_left {φ : α → Sort v} {a a' : α} {p₁ : φ a} {p₂ : φ a'} : (e : a = a') → (h₂ : Eq.rec (motive := fun a _ => φ a) p₁ e = p₂) → HEq p₁ p₂ | rfl, rfl => HEq.rfl lemma heq_of_eq_rec_right {φ : α → Sort v} {a a' : α} {p₁ : φ a} {p₂ : φ a'} : (e : a' = a) → (h₂ : p₁ = Eq.rec (motive := fun a _ => φ a) p₂ e) → HEq p₁ p₂ | rfl, rfl => HEq.rfl lemma of_heq_true (h : HEq a True) : a := of_eq_true (eq_of_heq h) -- TODO eq_rec_compose /- and -/ variable {a b c d : Prop} def And.elim (f : a → b → α) (h : a ∧ b) : α := f h.1 h.2 lemma and.swap : a ∧ b → b ∧ a := λ ⟨ha, hb⟩ => ⟨hb, ha⟩ lemma And.symm : a ∧ b → b ∧ a | ⟨ha, hb⟩ => ⟨hb, ha⟩ /- or -/ lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := λ not_em : ¬(a ∨ ¬a) => have neg_a : ¬a := λ pos_a : a => absurd (Or.inl pos_a) not_em absurd (Or.inr neg_a) not_em lemma Or.swap : a ∨ b → b ∨ a := Or.rec Or.inr Or.inl lemma Or.symm : a ∨ b → b ∨ a | Or.inl h => Or.inr h | Or.inr h => Or.inl h /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ def Iff.elim (f : (a → b) → (b → a) → c) (h : a ↔ b) : c := f h.1 h.2 def Iff.elim_left : (a ↔ b) → a → b := Iff.mp def Iff.elim_right : (a ↔ b) → b → a := Iff.mpr lemma Eq.to_iff : a = b → (a ↔ b) | rfl => Iff.rfl lemma neq_of_not_iff : ¬(a ↔ b) → a ≠ b := mt Eq.to_iff lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬ a ↔ ¬ b := Iff.intro (λ (hna : ¬ a) (hb : b) => hna (Iff.elim_right h₁ hb)) (λ (hnb : ¬ b) (ha : a) => hnb (Iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ True) : a := h.2 ⟨⟩ lemma not_of_iff_false : (a ↔ False) → ¬a := Iff.mp lemma iff_true_intro (h : a) : a ↔ True := ⟨fun _ => ⟨⟩, fun _ => h⟩ lemma iff_false_intro (h : ¬a) : a ↔ False := ⟨h, fun h => h.elim⟩ lemma not_iff_false_intro (h : a) : ¬a ↔ False := iff_false_intro (not_not_intro h) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := ⟨mt not_not_intro, not_not_intro⟩ lemma imp_congr_left (h : a ↔ b) : (a → c) ↔ (b → c) := ⟨fun hac ha => hac (h.2 ha), fun hbc ha => hbc (h.1 ha)⟩ lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ⟨fun hab ha => (h ha).1 (hab ha), fun hcd ha => (h ha).2 (hcd ha)⟩ lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := (imp_congr_left h₁).trans (imp_congr_right h₂) lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := imp_congr_ctx h₁ fun _ => h₂ lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha => absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ True) ↔ False := iff_false_intro (not_not_intro trivial) @[simp] lemma not_false_iff : (¬ False) ↔ True := iff_true_intro not_false lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := ⟨mt h.2, mt h.1⟩ lemma ne_self_iff_false (a : α) : a ≠ a ↔ False := not_iff_false_intro rfl @[simp] lemma eq_self_iff_true (a : α) : a = a ↔ True := iff_true_intro rfl lemma heq_self_iff_true (a : α) : HEq a a ↔ True := iff_true_intro HEq.rfl lemma iff_not_self : ¬(a ↔ ¬a) | H => let f h := H.1 h h; f (H.2 f) @[simp] lemma not_iff_self : ¬(¬a ↔ a) | H => iff_not_self H.symm lemma true_iff_false : (True ↔ False) ↔ False := iff_false_intro (λ h => Iff.mp h trivial) lemma false_iff_true : (False ↔ True) ↔ False := iff_false_intro (λ h => Iff.mpr h trivial) lemma false_of_true_iff_false : (True ↔ False) → False := λ h => Iff.mp h trivial lemma false_of_true_eq_false : (True = False) → False := λ h => h ▸ trivial lemma true_eq_false_of_false : False → (True = False) := False.elim lemma eq_comm {a b : α} : a = b ↔ b = a := ⟨Eq.symm, Eq.symm⟩ /- and simp rules -/ lemma And.imp (f : a → c) (g : b → d) (h : a ∧ b) : c ∧ d := ⟨f h.1, g h.2⟩ lemma and_implies (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := And.imp hac hbd lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : a ∧ b ↔ c ∧ d := ⟨And.imp h₁.1 h₂.1, And.imp h₁.2 h₂.2⟩ lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := ⟨fun ⟨ha, hb⟩ => ⟨ha, (h ha).1 hb⟩, fun ⟨ha, hb⟩ => ⟨ha, (h ha).2 hb⟩⟩ lemma And.comm : a ∧ b ↔ b ∧ a := ⟨And.symm, And.symm⟩ lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := And.comm lemma And.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := ⟨fun ⟨⟨ha, hb⟩, hc⟩ => ⟨ha, hb, hc⟩, fun ⟨ha, hb, hc⟩ => ⟨⟨ha, hb⟩, hc⟩⟩ lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := And.assoc lemma And.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := by rw [← and_assoc, ← and_assoc, @And.comm a b] lemma and_iff_left (hb : b) : a ∧ b ↔ a := ⟨And.left, fun ha => ⟨ha, hb⟩⟩ lemma and_iff_right (ha : a) : a ∧ b ↔ b := ⟨And.right, fun hb => ⟨ha, hb⟩⟩ @[simp] lemma and_not_self : ¬(a ∧ ¬a) | ⟨ha, hn⟩ => hn ha @[simp] lemma not_and_self : ¬(¬a ∧ a) | ⟨hn, ha⟩ => hn ha /- or simp rules -/ lemma Or.imp (f : a → c) (g : b → d) (h : a ∨ b) : c ∨ d := h.elim (inl ∘ f) (inr ∘ g) lemma Or.imp_left (f : a → b) : a ∨ c → b ∨ c := Or.imp f id lemma Or.imp_right (f : b → c) : a ∨ b → a ∨ c := Or.imp id f lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := ⟨Or.imp h₁.1 h₂.1, Or.imp h₁.2 h₂.2⟩ lemma Or.comm : a ∨ b ↔ b ∨ a := ⟨Or.symm, Or.symm⟩ lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := Or.comm lemma Or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := Iff.intro (Or.rec (Or.imp_right Or.inl) (λ h => Or.inr (Or.inr h))) (Or.rec (λ h => Or.inl (Or.inl h)) (Or.imp_left Or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := Or.assoc lemma Or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := Iff.trans (Iff.symm Or.assoc) (Iff.trans (or_congr Or.comm (Iff.refl c)) Or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := Iff.intro (Or.rec ha id) Or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := Iff.intro (Or.rec id hb) Or.inl -- Port note: in mathlib3, this is not_or lemma not_or_intro {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna, hnb, (Or.inl ha) => absurd ha hna | hna, hnb, (Or.inr hb) => absurd hb hnb lemma not_or (p q) : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := ⟨fun H => ⟨mt Or.inl H, mt Or.inr H⟩, fun ⟨hp, hq⟩ pq => pq.elim hp hq⟩ /- or resolution rules -/ lemma Or.resolve_left {a b : Prop} (h: a ∨ b) (na : ¬ a) : b := Or.elim h (λ ha => absurd ha na) id lemma Or.neg_resolve_left (h : ¬a ∨ b) (ha : a) : b := h.elim (absurd ha) id lemma Or.resolve_right {a b : Prop} (h: a ∨ b) (nb : ¬ b) : a := Or.elim h id (λ hb => absurd hb nb) lemma Or.neg_resolve_right (h : a ∨ ¬b) (nb : b) : a := h.elim id (absurd nb) lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := ⟨fun h => h₁.symm.trans $ h.trans h₂, fun h => h₁.trans $ h.trans h₂.symm⟩ /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → True) ↔ True := Iff.intro (λ h => trivial) (λ ha h => trivial) lemma false_implies_iff (a : Prop) : (False → a) ↔ True := Iff.intro (λ h => trivial) (λ ha h => False.elim h) theorem true_implies_iff (α : Prop) : (True → α) ↔ α := Iff.intro (λ h => h trivial) (λ h h' => h) /- exists unique -/ def ExistsUnique (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x open Lean in macro "∃! " xs:explicitBinders ", " b:term : term => expandExplicitBinders ``ExistsUnique xs b lemma ExistsUnique.intro {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := ⟨w, h₁, h₂⟩ lemma ExistsUnique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := Exists.elim h₂ (λ w hw => h₁ w (And.left hw) (And.right hw)) lemma exists_unique_of_exists_of_unique {α : Sort u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := Exists.elim hex (λ x px => ExistsUnique.intro x px (λ y (h : p y) => hunique y x h px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := Exists.elim h (λ x hx => ⟨x, And.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := let ⟨x, hx, hy⟩ := h; (hy _ py₁).trans (hy _ py₂).symm /- exists, forall, exists unique congruences -/ -- Port note: this is `forall_congr` from Lean 3. In Lean 4, there is already something -- with that name and a slightly different type. lemma forall_congr' {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∀ a, p a) ↔ ∀ a, q a := ⟨fun H a => (h a).1 (H a), fun H a => (h a).2 (H a)⟩ lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := Exists.elim p (λ a hp => ⟨a, h a hp⟩) lemma exists_congr {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∃ a, p a) ↔ ∃ a, q a := ⟨exists_imp_exists fun x => (h x).1, exists_imp_exists fun x => (h x).2⟩ lemma exists_unique_congr {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∃! a, p a) ↔ ∃! a, q a := exists_congr fun x => and_congr (h _) $ forall_congr' fun y => imp_congr_left (h _) lemma forall_not_of_not_exists {p : α → Prop} (hne : ¬∃ x, p x) (x) : ¬p x | hp => hne ⟨x, hp⟩ /- decidable -/ namespace Decidable variable {p q : Prop} -- TODO: rec_on_true and rec_on_false def by_cases {q : Sort u} [φ : Decidable p] : (p → q) → (¬p → q) → q := byCases lemma by_contradiction [φ : Decidable p] (h : ¬ p → False) : p := @byContradiction p φ h lemma not_not_iff (p) [Decidable p] : (¬ ¬ p) ↔ p := Iff.intro of_not_not not_not_intro lemma not_or_iff_and_not (p q) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := Iff.intro (λ h => match d₁ with | isTrue h₁ => False.elim $ h (Or.inl h₁) | isFalse h₁ => match d₂ with | isTrue h₂ => False.elim $ h (Or.inr h₂) | isFalse h₂ => ⟨h₁, h₂⟩) (λ ⟨np, nq⟩ h => Or.elim h np nq) end Decidable section variable {p q : Prop} def decidable_of_decidable_of_iff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse (Iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : Decidable p) (h : p = q) : Decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def Or.by_cases [Decidable p] [Decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else False.elim (Or.elim h hp hq) end section variable {p q : Prop} instance [Decidable p] [Decidable q] : Decidable (xor p q) := if hp : p then if hq : q then isFalse (Or.rec (λ ⟨_, h⟩ => h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩ => h hp : ¬(q ∧ ¬ p))) else isTrue $ Or.inl ⟨hp, hq⟩ else if hq : q then isTrue $ Or.inr ⟨hq, hp⟩ else isFalse (Or.rec (λ ⟨h, _⟩ => hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩ => hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : Decidable p] [DP : ∀ h, Decidable (P h)] : Decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 => ⟨h, h2⟩, λ⟨h', h2⟩ => h2⟩ else isFalse (mt (λ⟨h, _⟩ => h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : Decidable p] [DP : ∀ h, Decidable (P h)] : Decidable (∀ h, P h) := if h : p then decidableOfDecidableOfIff (DP h) ⟨λ h2 _ => h2, λ al => al h⟩ else isTrue (λ h2 => absurd h2 h) end lemma Bool.ff_ne_tt : false = true → False := Bool.noConfusion def is_dec_eq {α : Sort u} (p : α → α → Bool) : Prop := ∀ ⦃x y : α⦄, p x y = true → x = y def is_dec_refl {α : Sort u} (p : α → α → Bool) : Prop := ∀ x, p x x = true def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → Bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : DecidableEq α := λ (x y : α) => if hp : p x y = true then isTrue (h₁ hp) else isFalse (λ hxy : x = y => absurd (h₂ y) (by rwa [hxy] at hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : DecidableEq α] (a : α) : h a a = isTrue (Eq.refl a) := match (h a a) with | (isTrue e) => rfl | (isFalse n) => absurd rfl n lemma decidable_eq_inr_neg {α : Sort u} [h : DecidableEq α] {a b : α} : ∀ n : a ≠ b, h a b = isFalse n := λ n => match (h a b) with | (isTrue e) => absurd e n | (isFalse n₁) => proof_irrel n n₁ ▸ Eq.refl (isFalse n) /- subsingleton -/ -- TODO: rec_subsingleton @[simp] lemma if_t_t (c : Prop) [h : Decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (isTrue hc) => rfl | (isFalse hnc) => rfl lemma implies_of_if_pos {c t e : Prop} [Decidable c] (h : ite c t e) : c → t := by intro hc have hp : ite c t e = t := if_pos hc rwa [hp] at h lemma implies_of_if_neg {c t e : Prop} [Decidable c] (h : ite c t e) : ¬c → e := by intro hnc have hn : ite c t e = e := if_neg hnc rwa [hn] at h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (isFalse h₁), (isFalse h₂) => h_e h₂ | (isTrue h₁), (isTrue h₂) => h_t h₂ | (isFalse h₁), (isTrue h₂) => absurd h₂ (Iff.mp (not_iff_not_of_iff h_c) h₁) | (isTrue h₁), (isFalse h₂) => absurd h₁ (Iff.mpr (not_iff_not_of_iff h_c) h₂) lemma if_congr {α : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h => h_t) (λ h => h_e) @[simp] lemma if_true {h : Decidable True} (t e : α) : (@ite α True h t e) = t := if_pos trivial @[simp] lemma if_false {h : Decidable False} (t e : α) : (@ite α False h t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : Decidable b] [dec_c : Decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (isFalse h₁), (isFalse h₂) => h_e h₂ | (isTrue h₁), (isTrue h₂) => h_t h₂ | (isFalse h₁), (isTrue h₂) => absurd h₂ (Iff.mp (not_iff_not_of_iff h_c) h₁) | (isTrue h₁), (isFalse h₂) => absurd h₁ (Iff.mpr (not_iff_not_of_iff h_c) h₂) lemma if_congr_prop {b c x y u v : Prop} [dec_b : Decidable b] [dec_c : Decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h => h_t) (λ h => h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : Decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite Prop c (decidable_of_decidable_of_iff dec_b h_c) u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : Decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite Prop c (decidable_of_decidable_of_iff dec_b h_c) u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h => h_t) (λ h => h_e) lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (Iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (Iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite α b dec_b x y) = (@dite α c dec_c u v) := match dec_b, dec_c with | (isFalse h₁), (isFalse h₂) => h_e h₂ | (isTrue h₁), (isTrue h₂) => h_t h₂ | (isFalse h₁), (isTrue h₂) => absurd h₂ (Iff.mp (not_iff_not_of_iff h_c) h₁) | (isTrue h₁), (isFalse h₂) => absurd h₁ (Iff.mpr (not_iff_not_of_iff h_c) h₂) lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : Decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (Iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (Iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite α b dec_b x y) = (@dite α c (decidable_of_decidable_of_iff dec_b h_c) u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e def as_true (c : Prop) [Decidable c] : Prop := if c then True else False def as_false (c : Prop) [Decidable c] : Prop := if c then False else True lemma of_as_true {c : Prop} [h₁ : Decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (isTrue h_c), h₂ => h_c | (isFalse h_c), h₂ => False.elim h₂ /-- Universe lifting operation -/ structure ulift.{r, s} (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | up a => rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down : ∀ (b : plift α), up (down b) = b | (up a) => rfl lemma down_up (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁; b x) = (let x : α := a₂; b x) := λ h => Eq.recOn (motive := (λ a _ => (let x : α := a₁; b x) = (let x : α := a; b x))) h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : ∀ x : α, β x) : a₁ = a₂ → HEq (let x : α := a₁; b x) (let x : α := a₂; b x) := by intro h; rw [h] lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : ∀ x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a; b₁ x) = (let x : α := a; b₂ x) := by intro h; rw [h] lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁; b₁ x) = (let x : α := a₂; b₂ x) := λ h₁ h₂ => Eq.recOn (motive := λ a _ => (let x := a₁; b₁ x) = (let x := a; b₂ x)) h₁ (h₂ a₁) -- TODO: `section relation` section binary variable {α : Type u} {β : Type v} variable (f : α → α → α) variable (inv : α → α) variable (one : α) variable (g : α → α → α) def commutative := ∀ a b, f a b = f b a def associative := ∀ a b c, f (f a b) c = f a (f b c) def left_identity := ∀ a, f one a = a def right_identity := ∀ a, f a one = a def right_inverse := ∀ a, f a (inv a) = one def left_cancelative := ∀ a b c, f a b = f a c → b = c def right_cancelative := ∀ a b c, f a b = f c b → a = c def left_distributive := ∀ a b c, f a (g b c) = g (f a b) (f a c) def right_distributive := ∀ a b c, f (g a b) c = g (f a c) (f b c) def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := by intros hcomm hassoc a b c have h1 : f a (f b c) = f (f a b) c := Eq.symm (hassoc a b c) have h2 : f (f a b) c = f (f b a) c := hcomm a b ▸ rfl have h3 : f (f b a) c = f b (f a c) := hassoc b a c rw [←h3, ←h2, ←h1] lemma right_comm : commutative f → associative f → right_commutative f := by intros hcomm hassoc a b c have h1 : f (f a b) c = f a (f b c) := hassoc a b c have h2 : f a (f b c) = f a (f c b) := hcomm b c ▸ rfl have h3 : f a (f c b) = f (f a c) b := Eq.symm (hassoc a c b) rw [←h3, ←h2, ←h1] end binary -- We define a fix' function here because the fix function in the Lean 4 prelude has -- `set_option codegen false`. namespace WellFounded variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop} unsafe def fix'.impl (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := F x fun y _ => impl hwf F y set_option codegen false in @[implementedBy fix'.impl] def fix' (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := hwf.fix F x end WellFounded
2e287c5094a035f63db0c93d9ca5f9d25cb73abf
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/Tactic/Subst.lean
1ea91d40aa010bb9229481ceaa095f68270ba9c5
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
8,173
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean.Meta def substCore (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) (tryToSkip := false) : MetaM (FVarSubst × MVarId) := withMVarContext mvarId do let tag ← getMVarTag mvarId checkNotAssigned mvarId `subst let hFVarIdOriginal := hFVarId let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => throwTacticEx `subst mvarId "argument must be an equality proof" | some (α, lhs, rhs) => do let a ← instantiateMVars <| if symm then rhs else lhs let b ← instantiateMVars <| if symm then lhs else rhs match a with | Expr.fvar aFVarId _ => do let aFVarIdOriginal := aFVarId trace[Meta.Tactic.subst] "substituting {a} (id: {aFVarId}) with {b}" let mctx ← getMCtx if mctx.exprDependsOn b aFVarId then throwTacticEx `subst mvarId m!"'{a}' occurs at{indentExpr b}" let aLocalDecl ← getLocalDecl aFVarId let (vars, mvarId) ← revert mvarId #[aFVarId, hFVarId] true trace[Meta.Tactic.subst] "after revert {MessageData.ofGoal mvarId}" let (twoVars, mvarId) ← introNP mvarId 2 trace[Meta.Tactic.subst] "after intro2 {MessageData.ofGoal mvarId}" trace[Meta.Tactic.subst] "reverted variables {vars}" let aFVarId := twoVars[0] let a := mkFVar aFVarId let hFVarId := twoVars[1] let h := mkFVar hFVarId /- Set skip to true if there is no local variable nor the target depend on the equality -/ let skip ← if !tryToSkip || vars.size != 2 then pure false else let mvarType ← getMVarType mvarId let mctx ← getMCtx pure (!mctx.exprDependsOn mvarType aFVarId && !mctx.exprDependsOn mvarType hFVarId) if skip then if clearH then let mvarId ← clear mvarId hFVarId let mvarId ← clear mvarId aFVarId pure ({}, mvarId) else pure ({}, mvarId) else withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId let type := mvarDecl.type let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => unreachable! | some (α, lhs, rhs) => do let b ← instantiateMVars <| if symm then lhs else rhs let mctx ← getMCtx let depElim := mctx.exprDependsOn mvarDecl.type hFVarId let cont (motive : Expr) (newType : Expr) : MetaM (FVarSubst × MVarId) := do let major ← if symm then pure h else mkEqSymm h let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let minor := newMVar let newVal ← if depElim then mkEqRec motive minor major else mkEqNDRec motive minor major assignExprMVar mvarId newVal let mvarId := newMVar.mvarId! let mvarId ← if clearH then let mvarId ← clear mvarId hFVarId clear mvarId aFVarId else pure mvarId let (newFVars, mvarId) ← introNP mvarId (vars.size - 2) trace[Meta.Tactic.subst] "after intro rest {vars.size - 2} {MessageData.ofGoal mvarId}" let fvarSubst ← newFVars.size.foldM (init := fvarSubst) fun i (fvarSubst : FVarSubst) => let var := vars[i+2] let newFVar := newFVars[i] pure $ fvarSubst.insert var (mkFVar newFVar) let fvarSubst := fvarSubst.insert aFVarIdOriginal (if clearH then b else mkFVar aFVarId) let fvarSubst := fvarSubst.insert hFVarIdOriginal (mkFVar hFVarId) pure (fvarSubst, mvarId) if depElim then do let newType := type.replaceFVar a b let reflB ← mkEqRefl b let newType := newType.replaceFVar h reflB if symm then let motive ← mkLambdaFVars #[a, h] type cont motive newType else /- `type` depends on (h : a = b). So, we use the following trick to avoid a type incorrect motive. 1- Create a new local (hAux : b = a) 2- Create newType := type [hAux.symm / h] `newType` is type correct because `h` and `hAux.symm` are definitionally equal by proof irrelevance. 3- Create motive by abstracting `a` and `hAux` in `newType`. -/ let hAuxType ← mkEq b a let motive ← withLocalDeclD `_h hAuxType fun hAux => do let hAuxSymm ← mkEqSymm hAux /- replace h in type with hAuxSymm -/ let newType := type.replaceFVar h hAuxSymm mkLambdaFVars #[a, hAux] newType cont motive newType else let motive ← mkLambdaFVars #[a] type let newType := type.replaceFVar a b cont motive newType | _ => let eqMsg := if symm then "(t = x)" else "(x = t)" throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form {eqMsg}{indentExpr hLocalDecl.type}\nafter WHNF, variable expected, but obtained{indentExpr a}" def subst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := withMVarContext mvarId do let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | some (α, lhs, rhs) => let substReduced (newType : Expr) (symm : Bool) : MetaM MVarId := do let mvarId ← assert mvarId hLocalDecl.userName newType (mkFVar hFVarId) let (hFVarId', mvarId) ← intro1P mvarId let mvarId ← clear mvarId hFVarId return (← substCore mvarId hFVarId' (symm := symm) (tryToSkip := true)).2 let rhs' ← whnf rhs if rhs'.isFVar then if rhs != rhs' then substReduced (← mkEq lhs rhs') true else return (← substCore mvarId hFVarId (symm := true) (tryToSkip := true)).2 else do let lhs' ← whnf lhs if lhs'.isFVar then if lhs != lhs' then substReduced (← mkEq lhs' rhs) false else return (← substCore mvarId hFVarId (symm := false) (tryToSkip := true)).2 else do throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form (x = t) or (t = x){indentExpr hLocalDecl.type}" | none => if hLocalDecl.isLet then throwTacticEx `subst mvarId m!"variable '{mkFVar hFVarId}' is a let-declaration" let mctx ← getMCtx let lctx ← getLCtx let some (fvarId, symm) ← lctx.findDeclM? fun localDecl => do if localDecl.isAuxDecl then return none else match (← matchEq? localDecl.type) with | some (α, lhs, rhs) => if rhs.isFVar && rhs.fvarId! == hFVarId && !mctx.exprDependsOn lhs hFVarId then return some (localDecl.fvarId, true) else if lhs.isFVar && lhs.fvarId! == hFVarId && !mctx.exprDependsOn rhs hFVarId then return some (localDecl.fvarId, false) else return none | _ => return none | throwTacticEx `subst mvarId m!"did not find equation for eliminating '{mkFVar hFVarId}'" return (← substCore mvarId fvarId (symm := symm) (tryToSkip := true)).2 builtin_initialize registerTraceClass `Meta.Tactic.subst end Meta end Lean
91d3ffa4a0d7f60f4aebbff259ff1226a1fec9ce
ac49064e8a9a038e07cf5574b4fccd8a70d115c8
/hott/algebra/group_theory.hlean
87aae6fa3cef69f87e5472b71bc31ab5b1982cd5
[ "Apache-2.0" ]
permissive
Bolt64/lean2
7c75016729569e04a3f403c7a4fc7c1de4377c9d
75fd8162488214a959dbe3303a185cbbb83f60f9
refs/heads/master
1,611,290,445,156
1,493,763,922,000
1,493,763,922,000
81,566,307
0
0
null
1,486,732,167,000
1,486,732,167,000
null
UTF-8
Lean
false
false
19,284
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Basic group theory -/ import algebra.category.category algebra.bundled .homomorphism open eq algebra pointed function is_trunc pi equiv is_equiv set_option class.force_new true namespace group definition pointed_Group [instance] [constructor] (G : Group) : pointed G := pointed.mk 1 definition Group.struct' [instance] [reducible] (G : Group) : group G := Group.struct G definition ab_group_Group_of_AbGroup [instance] [constructor] [priority 900] (G : AbGroup) : ab_group (Group_of_AbGroup G) := begin esimp, exact _ end definition ab_group_pSet_of_Group [instance] (G : AbGroup) : ab_group (pSet_of_Group G) := AbGroup.struct G definition group_pSet_of_Group [instance] [priority 900] (G : Group) : group (pSet_of_Group G) := Group.struct G /- group homomorphisms -/ /- definition is_homomorphism [class] [reducible] {G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂) : Type := Π(g h : G₁), φ (g * h) = φ g * φ h section variables {G G₁ G₂ G₃ : Type} {g h : G₁} (ψ : G₂ → G₃) {φ₁ φ₂ : G₁ → G₂} (φ : G₁ → G₂) [group G] [group G₁] [group G₂] [group G₃] [is_homomorphism ψ] [is_homomorphism φ₁] [is_homomorphism φ₂] [is_homomorphism φ] definition respect_mul {G₁ G₂ : Type} [has_mul G₁] [has_mul G₂] (φ : G₁ → G₂) [is_homomorphism φ] : Π(g h : G₁), φ (g * h) = φ g * φ h := by assumption theorem respect_one /- φ -/ : φ 1 = 1 := mul.right_cancel (calc φ 1 * φ 1 = φ (1 * 1) : respect_mul φ ... = φ 1 : ap φ !one_mul ... = 1 * φ 1 : one_mul) theorem respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ := eq_inv_of_mul_eq_one (!respect_mul⁻¹ ⬝ ap φ !mul.left_inv ⬝ !respect_one) definition is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ := begin apply function.is_embedding_of_is_injective, intro g g' p, apply eq_of_mul_inv_eq_one, apply H, refine !respect_mul ⬝ _, rewrite [respect_inv φ, p], apply mul.right_inv end definition is_homomorphism_compose {ψ : G₂ → G₃} {φ : G₁ → G₂} (H1 : is_homomorphism ψ) (H2 : is_homomorphism φ) : is_homomorphism (ψ ∘ φ) := λg h, ap ψ !respect_mul ⬝ !respect_mul definition is_homomorphism_id (G : Type) [group G] : is_homomorphism (@id G) := λg h, idp end section additive definition is_add_homomorphism [class] [reducible] {G₁ G₂ : Type} [has_add G₁] [has_add G₂] (φ : G₁ → G₂) : Type := Π(g h : G₁), φ (g + h) = φ g + φ h variables {G₁ G₂ : Type} (φ : G₁ → G₂) [add_group G₁] [add_group G₂] [is_add_homomorphism φ] definition respect_add /- φ -/ : Π(g h : G₁), φ (g + h) = φ g + φ h := by assumption theorem respect_zero /- φ -/ : φ 0 = 0 := add.right_cancel (calc φ 0 + φ 0 = φ (0 + 0) : respect_add φ ... = φ 0 : ap φ !zero_add ... = 0 + φ 0 : zero_add) theorem respect_neg /- φ -/ (g : G₁) : φ (-g) = -(φ g) := eq_neg_of_add_eq_zero (!respect_add⁻¹ ⬝ ap φ !add.left_inv ⬝ !respect_zero) end additive -/ structure homomorphism (G₁ G₂ : Group) : Type := (φ : G₁ → G₂) (p : is_mul_hom φ) infix ` →g `:55 := homomorphism definition group_fun [unfold 3] [coercion] := @homomorphism.φ definition homomorphism.struct [unfold 3] [instance] [priority 900] {G₁ G₂ : Group} (φ : G₁ →g G₂) : is_mul_hom φ := homomorphism.p φ definition homomorphism.mulstruct [instance] [priority 2000] {G₁ G₂ : Group} (φ : G₁ →g G₂) : is_mul_hom φ := homomorphism.p φ definition homomorphism.addstruct [instance] [priority 2000] {G₁ G₂ : AddGroup} (φ : G₁ →g G₂) : is_add_hom φ := homomorphism.p φ variables {G G₁ G₂ G₃ : Group} {g h : G₁} {ψ : G₂ →g G₃} {φ₁ φ₂ : G₁ →g G₂} (φ : G₁ →g G₂) definition to_respect_mul /- φ -/ (g h : G₁) : φ (g * h) = φ g * φ h := respect_mul φ g h theorem to_respect_one /- φ -/ : φ 1 = 1 := respect_one φ theorem to_respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ := respect_inv φ g definition to_is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ := is_embedding_of_is_mul_hom φ @H variables (G₁ G₂) definition is_set_homomorphism [instance] : is_set (G₁ →g G₂) := begin have H : G₁ →g G₂ ≃ Σ(f : G₁ → G₂), Π(g₁ g₂ : G₁), f (g₁ * g₂) = f g₁ * f g₂, begin fapply equiv.MK, { intro φ, induction φ, constructor, exact (respect_mul φ)}, { intro v, induction v with f H, constructor, exact H}, { intro v, induction v, reflexivity}, { intro φ, induction φ, reflexivity} end, apply is_trunc_equiv_closed_rev, exact H end variables {G₁ G₂} definition pmap_of_homomorphism [constructor] /- φ -/ : G₁ →* G₂ := pmap.mk φ begin esimp, exact respect_one φ end definition homomorphism_change_fun [constructor] {G₁ G₂ : Group} (φ : G₁ →g G₂) (f : G₁ → G₂) (p : φ ~ f) : G₁ →g G₂ := homomorphism.mk f (λg h, (p (g * h))⁻¹ ⬝ to_respect_mul φ g h ⬝ ap011 mul (p g) (p h)) definition homomorphism_eq (p : group_fun φ₁ ~ group_fun φ₂) : φ₁ = φ₂ := begin induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p, exact ap (homomorphism.mk φ₁) !is_prop.elim end section additive variables {H₁ H₂ : AddGroup} (χ : H₁ →g H₂) definition to_respect_add /- χ -/ (g h : H₁) : χ (g + h) = χ g + χ h := respect_add χ g h theorem to_respect_zero /- χ -/ : χ 0 = 0 := respect_zero χ theorem to_respect_neg /- χ -/ (g : H₁) : χ (-g) = -(χ g) := respect_neg χ g end additive section add_mul variables {H₁ : AddGroup} {H₂ : Group} (χ : H₁ →g H₂) definition to_respect_add_mul /- χ -/ (g h : H₁) : χ (g + h) = χ g * χ h := to_respect_mul χ g h theorem to_respect_zero_one /- χ -/ : χ 0 = 1 := to_respect_one χ theorem to_respect_neg_inv /- χ -/ (g : H₁) : χ (-g) = (χ g)⁻¹ := to_respect_inv χ g end add_mul section mul_add variables {H₁ : Group} {H₂ : AddGroup} (χ : H₁ →g H₂) definition to_respect_mul_add /- χ -/ (g h : H₁) : χ (g * h) = χ g + χ h := to_respect_mul χ g h theorem to_respect_one_zero /- χ -/ : χ 1 = 0 := to_respect_one χ theorem to_respect_inv_neg /- χ -/ (g : H₁) : χ g⁻¹ = -(χ g) := to_respect_inv χ g end mul_add /- categorical structure of groups + homomorphisms -/ definition homomorphism_compose [constructor] [trans] (ψ : G₂ →g G₃) (φ : G₁ →g G₂) : G₁ →g G₃ := homomorphism.mk (ψ ∘ φ) (is_mul_hom_compose _ _) variable (G) definition homomorphism_id [constructor] [refl] : G →g G := homomorphism.mk (@id G) (is_mul_hom_id G) variable {G} abbreviation gid [constructor] := @homomorphism_id infixr ` ∘g `:75 := homomorphism_compose notation 1 := homomorphism_id _ structure isomorphism (A B : Group) := (to_hom : A →g B) (is_equiv_to_hom : is_equiv to_hom) infix ` ≃g `:25 := isomorphism attribute isomorphism.to_hom [coercion] attribute isomorphism.is_equiv_to_hom [instance] attribute isomorphism._trans_of_to_hom [unfold 3] definition equiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃ G₂ := equiv.mk φ _ definition pequiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃* G₂ := pequiv.mk φ begin esimp, exact _ end begin esimp, exact respect_one φ end definition isomorphism_of_equiv [constructor] (φ : G₁ ≃ G₂) (p : Πg₁ g₂, φ (g₁ * g₂) = φ g₁ * φ g₂) : G₁ ≃g G₂ := isomorphism.mk (homomorphism.mk φ p) !to_is_equiv definition isomorphism_of_eq [constructor] {G₁ G₂ : Group} (φ : G₁ = G₂) : G₁ ≃g G₂ := isomorphism_of_equiv (equiv_of_eq (ap Group.carrier φ)) begin intros, induction φ, reflexivity end definition pequiv_of_isomorphism_of_eq {G₁ G₂ : Group} (p : G₁ = G₂) : pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_Group p) := begin induction p, apply pequiv_eq, fapply pmap_eq, { intro g, reflexivity}, { apply is_prop.elim} end definition to_ginv [constructor] (φ : G₁ ≃g G₂) : G₂ →g G₁ := homomorphism.mk φ⁻¹ abstract begin intro g₁ g₂, apply eq_of_fn_eq_fn' φ, rewrite [respect_mul φ, +right_inv φ] end end variable (G) definition isomorphism.refl [refl] [constructor] : G ≃g G := isomorphism.mk 1 !is_equiv_id variable {G} definition isomorphism.symm [symm] [constructor] (φ : G₁ ≃g G₂) : G₂ ≃g G₁ := isomorphism.mk (to_ginv φ) !is_equiv_inv definition isomorphism.trans [trans] [constructor] (φ : G₁ ≃g G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ := isomorphism.mk (ψ ∘g φ) !is_equiv_compose definition isomorphism.eq_trans [trans] [constructor] {G₁ G₂ : Group} {G₃ : Group} (φ : G₁ = G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ := proof isomorphism.trans (isomorphism_of_eq φ) ψ qed definition isomorphism.trans_eq [trans] [constructor] {G₁ : Group} {G₂ G₃ : Group} (φ : G₁ ≃g G₂) (ψ : G₂ = G₃) : G₁ ≃g G₃ := isomorphism.trans φ (isomorphism_of_eq ψ) postfix `⁻¹ᵍ`:(max + 1) := isomorphism.symm infixl ` ⬝g `:75 := isomorphism.trans infixl ` ⬝gp `:75 := isomorphism.trans_eq infixl ` ⬝pg `:75 := isomorphism.eq_trans definition pmap_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ →* G₂ := pequiv_of_isomorphism φ /- category of groups -/ section open category definition precategory_group [constructor] : precategory Group := precategory.mk homomorphism @homomorphism_compose @homomorphism_id (λG₁ G₂ G₃ G₄ φ₃ φ₂ φ₁, homomorphism_eq (λg, idp)) (λG₁ G₂ φ, homomorphism_eq (λg, idp)) (λG₁ G₂ φ, homomorphism_eq (λg, idp)) end -- TODO -- definition category_group : category Group := -- category.mk precategory_group -- begin -- intro G₁ G₂, -- fapply adjointify, -- { intro φ, fapply Group_eq, }, -- { }, -- { } -- end /- given an equivalence A ≃ B we can transport a group structure on A to a group structure on B -/ section parameters {A B : Type} (f : A ≃ B) [group A] definition group_equiv_mul (b b' : B) : B := f (f⁻¹ᶠ b * f⁻¹ᶠ b') definition group_equiv_one : B := f one definition group_equiv_inv (b : B) : B := f (f⁻¹ᶠ b)⁻¹ local infix * := group_equiv_mul local postfix ^ := group_equiv_inv local notation 1 := group_equiv_one theorem group_equiv_mul_assoc (b₁ b₂ b₃ : B) : (b₁ * b₂) * b₃ = b₁ * (b₂ * b₃) := by rewrite [↑group_equiv_mul, +left_inv f, mul.assoc] theorem group_equiv_one_mul (b : B) : 1 * b = b := by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, one_mul, right_inv f] theorem group_equiv_mul_one (b : B) : b * 1 = b := by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, mul_one, right_inv f] theorem group_equiv_mul_left_inv (b : B) : b^ * b = 1 := by rewrite [↑group_equiv_mul, ↑group_equiv_one, ↑group_equiv_inv, +left_inv f, mul.left_inv] definition group_equiv_closed : group B := ⦃group, mul := group_equiv_mul, mul_assoc := group_equiv_mul_assoc, one := group_equiv_one, one_mul := group_equiv_one_mul, mul_one := group_equiv_mul_one, inv := group_equiv_inv, mul_left_inv := group_equiv_mul_left_inv, is_set_carrier := is_trunc_equiv_closed 0 f⦄ end variable (G) /- the trivial group -/ open unit definition trivial_group [constructor] : group unit := group.mk _ (λx y, star) (λx y z, idp) star (unit.rec idp) (unit.rec idp) (λx, star) (λx, idp) definition Trivial_group [constructor] : Group := Group.mk _ trivial_group abbreviation G0 := Trivial_group definition trivial_group_of_is_contr [H : is_contr G] : G ≃g G0 := begin fapply isomorphism_of_equiv, { apply equiv_unit_of_is_contr}, { intros, reflexivity} end /- A group where the point in the pointed type corresponds with 1 in the group. We need this structure when we are given a pointed type, and want to say that there is a group structure on it which is compatible with the point. This is used in chain complexes. -/ structure pgroup [class] (X : Type*) extends semigroup X, has_inv X := (pt_mul : Πa, mul pt a = a) (mul_pt : Πa, mul a pt = a) (mul_left_inv_pt : Πa, mul (inv a) a = pt) definition group_of_pgroup [reducible] [instance] (X : Type*) [H : pgroup X] : group X := ⦃group, H, one := pt, one_mul := pgroup.pt_mul , mul_one := pgroup.mul_pt, mul_left_inv := pgroup.mul_left_inv_pt⦄ definition pgroup_of_group (X : Type*) [H : group X] (p : one = pt :> X) : pgroup X := begin cases X with X x, esimp at *, induction p, exact ⦃pgroup, H, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv⦄ end definition Group_of_pgroup (G : Type*) [pgroup G] : Group := Group.mk G _ definition pgroup_Group [instance] (G : Group) : pgroup G := ⦃ pgroup, Group.struct G, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv ⦄ -- infinity pgroups structure inf_pgroup [class] (X : Type*) extends inf_semigroup X, has_inv X := (pt_mul : Πa, mul pt a = a) (mul_pt : Πa, mul a pt = a) (mul_left_inv_pt : Πa, mul (inv a) a = pt) definition inf_group_of_inf_pgroup [reducible] [instance] (X : Type*) [H : inf_pgroup X] : inf_group X := ⦃inf_group, H, one := pt, one_mul := inf_pgroup.pt_mul , mul_one := inf_pgroup.mul_pt, mul_left_inv := inf_pgroup.mul_left_inv_pt⦄ definition inf_pgroup_of_inf_group (X : Type*) [H : inf_group X] (p : one = pt :> X) : inf_pgroup X := begin cases X with X x, esimp at *, induction p, exact ⦃inf_pgroup, H, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv⦄ end definition inf_Group_of_inf_pgroup (G : Type*) [inf_pgroup G] : InfGroup := InfGroup.mk G _ definition inf_pgroup_InfGroup [instance] (G : InfGroup) : inf_pgroup G := ⦃ inf_pgroup, InfGroup.struct G, pt_mul := one_mul, mul_pt := mul_one, mul_left_inv_pt := mul.left_inv ⦄ /- equality of groups and abelian groups -/ definition group.to_has_mul {A : Type} (H : group A) : has_mul A := _ definition group.to_has_inv {A : Type} (H : group A) : has_inv A := _ definition group.to_has_one {A : Type} (H : group A) : has_one A := _ local attribute group.to_has_mul group.to_has_inv [coercion] universe variable l variables {A B : Type.{l}} definition group_eq {G H : group A} (same_mul' : Π(g h : A), @mul A G g h = @mul A H g h) : G = H := begin have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g, from λg, !mul_inv_cancel_right⁻¹, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4, have same_mul : Gm = Hm, from eq_of_homotopy2 same_mul', cases same_mul, have same_one : G1 = H1, from calc G1 = Hm G1 H1 : Hh3 ... = H1 : Gh2, have same_inv : Gi = Hi, from eq_of_homotopy (take g, calc Gi g = Hm (Hm (Gi g) g) (Hi g) : foo ... = Hm G1 (Hi g) : by rewrite Gh4 ... = Hi g : Gh2), cases same_one, cases same_inv, have ps : Gs = Hs, from !is_prop.elim, have ph1 : Gh1 = Hh1, from !is_prop.elim, have ph2 : Gh2 = Hh2, from !is_prop.elim, have ph3 : Gh3 = Hh3, from !is_prop.elim, have ph4 : Gh4 = Hh4, from !is_prop.elim, cases ps, cases ph1, cases ph2, cases ph3, cases ph4, reflexivity end definition group_pathover {G : group A} {H : group B} {p : A = B} (resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H := begin induction p, apply pathover_idp_of_eq, exact group_eq (resp_mul) end definition Group_eq_of_eq {G H : Group} (p : Group.carrier G = Group.carrier H) (resp_mul : Π(g h : G), cast p (g * h) = cast p g * cast p h) : G = H := begin cases G with Gc G, cases H with Hc H, apply (apd011 Group.mk p), exact group_pathover resp_mul end definition Group_eq {G H : Group} (f : Group.carrier G ≃ Group.carrier H) (resp_mul : Π(g h : G), f (g * h) = f g * f h) : G = H := Group_eq_of_eq (ua f) (λg h, !cast_ua ⬝ resp_mul g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹) definition eq_of_isomorphism {G₁ G₂ : Group} (φ : G₁ ≃g G₂) : G₁ = G₂ := Group_eq (equiv_of_isomorphism φ) (respect_mul φ) definition ab_group.to_has_mul {A : Type} (H : ab_group A) : has_mul A := _ local attribute ab_group.to_has_mul [coercion] definition ab_group_eq {A : Type} {G H : ab_group A} (same_mul : Π(g h : A), @mul A G g h = @mul A H g h) : G = H := begin have g_eq : @ab_group.to_group A G = @ab_group.to_group A H, from group_eq same_mul, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4 Gh5, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4 Hh5, have pm : Gm = Hm, from ap (@mul _ ∘ group.to_has_mul) g_eq, have pi : Gi = Hi, from ap (@inv _ ∘ group.to_has_inv) g_eq, have p1 : G1 = H1, from ap (@one _ ∘ group.to_has_one) g_eq, induction pm, induction pi, induction p1, have ps : Gs = Hs, from !is_prop.elim, have ph1 : Gh1 = Hh1, from !is_prop.elim, have ph2 : Gh2 = Hh2, from !is_prop.elim, have ph3 : Gh3 = Hh3, from !is_prop.elim, have ph4 : Gh4 = Hh4, from !is_prop.elim, have ph5 : Gh5 = Hh5, from !is_prop.elim, induction ps, induction ph1, induction ph2, induction ph3, induction ph4, induction ph5, reflexivity end definition ab_group_pathover {A B : Type} {G : ab_group A} {H : ab_group B} {p : A = B} (resp_mul : Π(g h : A), cast p (g * h) = cast p g * cast p h) : G =[p] H := begin induction p, apply pathover_idp_of_eq, exact ab_group_eq (resp_mul) end definition AbGroup_eq_of_isomorphism {G₁ G₂ : AbGroup} (φ : G₁ ≃g G₂) : G₁ = G₂ := begin induction G₁, induction G₂, apply apd011 AbGroup.mk (ua (equiv_of_isomorphism φ)), apply ab_group_pathover, intro g h, exact !cast_ua ⬝ respect_mul φ g h ⬝ ap011 mul !cast_ua⁻¹ !cast_ua⁻¹ end definition trivial_group_of_is_contr' (G : Group) [H : is_contr G] : G = G0 := eq_of_isomorphism (trivial_group_of_is_contr G) end group
3e318620f40beb2feb8e08912cdc24cdf50e5b90
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Deriving/SizeOf.lean
c60f7c43fc0171603190f47312c37c410530bf1e
[ "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
817
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.SizeOf import Lean.Elab.Deriving.Basic /- Remark: `SizeOf` instances are automatically generated. We add support for `deriving instance` for `SizeOf` just to be able to use them to define instances for types defined at `Prelude.lean` -/ namespace Lean.Elab.Deriving.SizeOf open Command def mkSizeOfHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) && declNames.size > 0 then liftTermElabM none <| Meta.mkSizeOfInstances declNames[0] return true else return false builtin_initialize registerBuiltinDerivingHandler `SizeOf mkSizeOfHandler end Lean.Elab.Deriving.SizeOf
bec6a04d487216585759567d18f61653e5e9d781
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/ring_theory/principal_ideal_domain.lean
ae80d1dd96009adc61bacbcc106552321456146e
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
6,723
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes, Morenikeji Neri -/ import algebra.euclidean_domain import ring_theory.ideals ring_theory.noetherian ring_theory.unique_factorization_domain variables {α : Type*} open set function ideal local attribute [instance] classical.prop_decidable class ideal.is_principal [comm_ring α] (S : ideal α) : Prop := (principal : ∃ a, S = span {a}) class principal_ideal_domain (α : Type*) extends integral_domain α := (principal : ∀ (S : ideal α), S.is_principal) attribute [instance] principal_ideal_domain.principal namespace ideal.is_principal variable [comm_ring α] noncomputable def generator (S : ideal α) [S.is_principal] : α := classical.some (principal S) lemma span_singleton_generator (S : ideal α) [S.is_principal] : span {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : ideal α) [S.is_principal] : generator S ∈ S := by conv {to_rhs, rw ← span_singleton_generator S}; exact subset_span (mem_singleton _) lemma mem_iff_generator_dvd (S : ideal α) [S.is_principal] {x : α} : x ∈ S ↔ generator S ∣ x := by rw [← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : ideal α) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← span_singleton_eq_bot, span_singleton_generator] end ideal.is_principal namespace is_prime open ideal.is_principal ideal lemma to_maximal_ideal [principal_ideal_domain α] {S : ideal α} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, haveI := principal_ideal_domain.principal S, haveI := principal_ideal_domain.principal T, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.2 (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, domain.mul_left_inj this] at hz, exact hz.symm ▸ ideal.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain α] lemma mod_mem_iff {S : ideal α} {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ ideal.add_mem S (mul_mem_right S hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ ideal.sub_mem S hx (ideal.mul_mem_right S hy)⟩ instance euclidean_domain.to_principal_ideal_domain : principal_ideal_domain α := { principal := λ S, by exactI ⟨if h : {x : α | x ∈ S ∧ x ≠ 0} = ∅ then ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe α α _ _ ring.to_module, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, eq_empty_iff_forall_not_mem.1 h a ⟨haS, ha0⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩ else have wf : well_founded euclidean_domain.r := euclidean_domain.r_well_founded α, have hmin : well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : α | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ▸ (mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ∉ {x : α | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := mem_span_singleton.1 hx in hy.symm ▸ ideal.mul_mem_right _ hmin.1⟩⟩⟩ } end namespace principal_ideal_domain variables [principal_ideal_domain α] instance is_noetherian_ring : is_noetherian_ring α := ⟨assume s : ideal α, begin cases (principal s).principal with a hs, refine ⟨finset.singleton a, submodule.ext' _⟩, rw hs, refl end⟩ section local attribute [instance] classical.prop_decidable open submodule lemma factors_decreasing (b₁ b₂ : α) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : submodule.span α ({b₁ * b₂} : set α) < submodule.span α {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] end lemma is_maximal_of_irreducible {p : α} (hp : irreducible p) : is_maximal (span ({p} : set α)) := ⟨mt span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, rw span_singleton_eq_top, unfreezeI, rcases span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), rw [span_singleton_le_span_singleton, mul_dvd_of_is_unit_right hb] end⟩ lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨λ hp, (span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, irreducible_of_prime⟩ lemma associates_irreducible_iff_prime : ∀{p : associates α}, irreducible p ↔ p.prime := associates.forall_associated.2 $ assume a, by rw [associates.irreducible_mk_iff, associates.prime_mk, irreducible_iff_prime] section local attribute [instance] classical.prop_decidable noncomputable def factors (a : α) : multiset α := if h : a = 0 then ∅ else classical.some (is_noetherian_ring.exists_factors a h) lemma factors_spec (a : α) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated a (factors a).prod := begin unfold factors, rw [dif_neg h], exact classical.some_spec (is_noetherian_ring.exists_factors a h) end /-- The unique factorization domain structure given by the principal ideal domain. This is not added as type class instance, since the `factors` might be computed in a different way. E.g. factors could return normalized values. -/ noncomputable def to_unique_factorization_domain : unique_factorization_domain α := { factors := factors, factors_prod := assume a ha, associated.symm (factors_spec a ha).2, prime_factors := assume a ha, by simpa [irreducible_iff_prime] using (factors_spec a ha).1 } end end principal_ideal_domain
7cee543bf68d7dbfc5878ef611770a3e8930c9a5
ac49064e8a9a038e07cf5574b4fccd8a70d115c8
/hott/init/path.hlean
333e381cbcda4386804df2d7a3bcd987ed2cb8a6
[ "Apache-2.0" ]
permissive
Bolt64/lean2
7c75016729569e04a3f403c7a4fc7c1de4377c9d
75fd8162488214a959dbe3303a185cbbb83f60f9
refs/heads/master
1,611,290,445,156
1,493,763,922,000
1,493,763,922,000
81,566,307
0
0
null
1,486,732,167,000
1,486,732,167,000
null
UTF-8
Lean
false
false
30,531
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {a a' x y z t : A} {b b' : B} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec' [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on' [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := by induction q; exact p definition inverse [symm] [unfold 4] (p : x = y) : y = x := by induction p; reflexivity infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold_full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a left unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := by induction p; reflexivity -- Concatenation is associative. definition con.assoc' [unfold 8] (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := by induction r; reflexivity definition con.assoc [unfold 8] (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := by induction r; reflexivity definition con.assoc5 {a₁ a₂ a₃ a₄ a₅ a₆ : A} (p₁ : a₁ = a₂) (p₂ : a₂ = a₃) (p₃ : a₃ = a₄) (p₄ : a₄ = a₅) (p₅ : a₅ = a₆) : p₁ ⬝ (p₂ ⬝ p₃ ⬝ p₄) ⬝ p₅ = (p₁ ⬝ p₂) ⬝ p₃ ⬝ (p₄ ⬝ p₅) := by induction p₅; induction p₄; induction p₃; reflexivity -- The left inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := by induction p; reflexivity -- The right inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := by induction p; reflexivity /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := by induction q; reflexivity definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := by induction q; reflexivity -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := by induction q; induction p; reflexivity definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := by induction q; induction p; reflexivity -- Inverse is an involution. definition inv_inv [unfold 4] (p : x = y) : p⁻¹⁻¹ = p := by induction p; reflexivity -- auxiliary definition used by 'cases' tactic definition elim_inv_inv [unfold 5] {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := begin induction r, intro h, exact !idp_con ⬝ h ⬝ !idp_con end definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := by induction p; exact id definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := by induction r; intro h; exact !idp_con ⬝ h ⬝ !idp_con definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := by induction p; exact id definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := by induction p; exact id definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := by induction p; exact id definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := by induction q; exact id definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := by induction q; exact id definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := by induction p; intro h; exact h ⬝ !idp_con definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := by induction p; exact id definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := by induction p; exact id definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := by induction p; intro h; exact h ⬝ !idp_con definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r; apply con.right_inv definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r; apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q; exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r; exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r; exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p; exact r definition eq_idp_of_con_right {p : x = x} {q : x = y} (r : p ⬝ q = q) : p = idp := by cases q; exact r definition eq_idp_of_con_left {p : x = x} {q : y = x} (r : q ⬝ p = q) : p = idp := by cases q; exact (idp_con p)⁻¹ ⬝ r definition idp_eq_of_con_right {p : x = x} {q : x = y} (r : q = p ⬝ q) : idp = p := by cases q; exact r definition idp_eq_of_con_left {p : x = x} {q : y = x} (r : q = q ⬝ p) : idp = p := by cases q; exact r ⬝ idp_con p /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := by induction p; exact u -- This idiom makes the operation right associative. infixr ` ▸ ` := transport _ definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition cast_def [reducible] [unfold_full] {A B : Type} (p : A = B) (a : A) : cast p a = p ▸ a := idp definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := by induction p; reflexivity abbreviation ap01 [parsing_only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] [unfold_full] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.symm [symm] [reducible] [unfold_full] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] [unfold_full] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x definition hwhisker_left [unfold_full] (g : B → C) {f f' : A → B} (H : f ~ f') : g ∘ f ~ g ∘ f' := λa, ap g (H a) definition hwhisker_right [unfold_full] (f : A → B) {g g' : B → C} (H : g ~ g') : g ∘ f ~ g' ∘ f := λa, H (f a) definition homotopy_of_eq {f g : Πx, P x} (H1 : f = g) : f ~ g := H1 ▸ homotopy.refl f definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, by induction H; reflexivity --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := by induction H; reflexivity --apd10 is also ap evaluation definition apd10_eq_ap_eval {f g : Πx, P x} (H : f = g) (a : A) : apd10 H a = ap (λs : Πx, P x, s a) H := by induction H; reflexivity definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := by induction H; exact ap f p -- [apd] is defined in init.pathover using pathover instead of an equality with transport. definition apdt [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := by induction p; reflexivity definition ap011 [unfold 9] (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := by cases Ha; exact ap (f a) Hb definition ap_eq_ap011_left (f : A → B → C) (Ha : a = a') (b : B) : ap (λa, f a b) Ha = ap011 f Ha idp := by induction Ha; reflexivity definition ap_eq_ap011_right (f : A → B → C) (a : A) (Hb : b = b') : ap (f a) Hb = ap011 f idp Hb := by reflexivity /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := by induction p; exact id definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := by induction p; exact id definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := by induction p; exact id definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := by induction p; exact id /- Transporting along the diagonal of a type family -/ definition tr_diag_eq_tr_tr {A : Type} (P : A → A → Type) {x y : A} (p : x = y) (a : P x x) : transport (λ x, P x x) p a = transport (λ x, P _ x) p (transport (λ x, P x _) p a) := by induction p; reflexivity /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp [unfold_full] (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con [unfold 8] (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := by induction q; reflexivity definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := by induction q; induction p; reflexivity definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := by induction q; induction p; apply con.assoc -- Functions commute with path inverses. definition ap_inv' [unfold 6] (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := by induction p; reflexivity definition ap_inv [unfold 6] (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := by induction p; reflexivity -- [ap] itself is functorial in the first argument. definition ap_id [unfold 4] (p : x = y) : ap id p = p := by induction p; reflexivity definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := by induction p; reflexivity -- Sometimes we don't have the actual function [compose]. definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := by induction p; reflexivity -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := by induction p; reflexivity -- Naturality of [ap]. -- see also natural_square in cubical.square definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := by induction q; apply idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := by induction q; apply idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := by induction q; exact !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := by induction q; apply idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := by induction q; reflexivity -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := begin induction s, induction q, apply idp_con end definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := by induction s; induction q; reflexivity definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := by induction q; reflexivity definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := by induction s; induction q; apply idp_con definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := by induction s; induction q; exact !idp_con⁻¹ /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := by induction h; induction h'; reflexivity definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := by induction h; reflexivity definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= by induction p; reflexivity /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := by induction q; reflexivity definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition cast_cast_inv {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P y) : cast (ap P p) (cast (ap P p⁻¹) z) = z := by induction p; reflexivity definition cast_inv_cast {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P x) : cast (ap P p⁻¹) (cast (ap P p) z) = z := by induction p; reflexivity definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = p ▸ f x z := by induction p; reflexivity definition fn_cast_eq_cast_fn {A : Type} {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (cast (ap P p) z) = cast (ap Q p) (f x z) := by induction p; reflexivity definition con_con_tr {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := by induction r; induction q; induction p; reflexivity -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := by induction p; reflexivity /- some properties for apdt -/ definition apdt_idp (x : A) (f : Πx, P x) : apdt f idp = idp :> (f x = f x) := idp definition apdt_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apdt f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apdt f p) ⬝ apdt f q := by cases p; cases q; apply idp definition apdt_inv (f : Πx, P x) {x y : A} (p : x = y) : apdt f p⁻¹ = (eq_inv_tr_of_tr_eq (apdt f p))⁻¹ := by cases p; apply idp -- Dependent transport in a doubly dependent type. -- This is a special case of transporto in init.pathover definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := by induction p; exact z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p ` ▸D `:65 x:64 := transportD _ p _ x -- transporting over 2 one-dimensional paths -- This is a special case of transporto in init.pathover definition transport11 {A B : Type} (P : A → B → Type) {a a' : A} {b b' : B} (p : a = a') (q : b = b') (z : P a b) : P a' b' := transport (P a') q (p ▸ z) -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p ` ▸2 `:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := by induction r; reflexivity definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := by induction r1; induction r2; reflexivity definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := by induction r; reflexivity definition transportD2 [unfold 7] {B C : A → Type} (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := by induction p; exact w notation p ` ▸D2 `:65 x:64 := transportD2 _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := by induction r; exact !idp_con⁻¹ /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := by induction p; reflexivity definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := by induction r; exact !idp_con⁻¹ -- Transporting in a pulled back fibration. definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := by induction p; reflexivity definition tr_ap (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport P (ap f p) z = transport (P ∘ f) p z := (tr_compose P f p z)⁻¹ definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := by induction p; reflexivity definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : apd10 (ap (λh : B → C, h ∘ f) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_precompose_dependent {C : B → Type} (f : A → B) {g g' : Πb : B, C b} (p : g = g') : apd10 (ap (λ(h : (Πb : B, C b))(a : A), h (f a)) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') : apd10 (ap (λh : A → B, f ∘ h) p) = λa, ap f (apd10 p a) := by induction p; reflexivity -- A special case of [tr_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := by induction p; reflexivity definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := by induction p; reflexivity /- The behavior of [ap] and [apdt] -/ -- In a constant fibration, [apdt] reduces to [ap], modulo [transport_const]. definition apdt_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apdt f p = tr_constant p (f x) ⬝ ap f p := by induction p; reflexivity /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := ap011 concat h h' -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := ap inverse h infixl ` ◾ `:80 := concat2 postfix [parsing_only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right [unfold 8] {p q : x = y} (r : y = z) (h : p = q) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} (p : x = y) {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} (r : y = z) : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right r⁻¹ s ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp {p q : x = y} (h : p = q) : whisker_right idp h = h := by induction h; induction p; reflexivity definition whisker_right_idp_left [unfold_full] (p : x = y) (q : y = z) : whisker_right q idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp_right [unfold_full] (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp {p q : x = y} (h : p = q) : (idp_con p)⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := by induction h; induction p; reflexivity definition whisker_left_idp2 {A : Type} {a : A} (p : idp = idp :> a = a) : whisker_left idp p = p := begin refine _ ⬝ whisker_left_idp p, exact !idp_con⁻¹ end definition con2_idp [unfold_full] {p q : x = y} (h : p = q) : h ◾ idp = whisker_right idp h :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 [unfold_full] {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp definition inv2_con2 {p p' : x = y} (h : p = p') : h⁻² ◾ h = con.left_inv p ⬝ (con.left_inv p')⁻¹ := by induction h; induction p; reflexivity -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : a ◾ c ⬝ b ◾ d = (a ⬝ b) ◾ (c ⬝ d) := by induction d; induction c; induction b;induction a; reflexivity definition con2_eq_rl {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_right q a ⬝ whisker_left p' b := by induction b; induction a; reflexivity definition con2_eq_lf {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_left p b ⬝ whisker_right q' a := by induction b; induction a; reflexivity definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right q a) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right q' a) := by induction b; induction a; reflexivity -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right s (con.assoc' p q r) = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right q (con_idp p) = whisker_left p (idp_con q) := by induction q; induction p; reflexivity definition eckmann_hilton (p q : idp = idp :> a = a) : p ⬝ q = q ⬝ p := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, refine !whisker_right_con_whisker_left ⬝ _, refine !whisker_left_idp2 ◾ !whisker_right_idp end definition con_eq_con2 (p q : idp = idp :> a = a) : p ⬝ q = p ◾ q := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, exact !con2_eq_rl⁻¹ end definition inv_eq_inv2 (p : idp = idp :> a = a) : p⁻¹ = p⁻² := begin apply eq.cancel_right p, refine !con.left_inv ⬝ _, refine _ ⬝ !con_eq_con2⁻¹, exact !inv2_con2⁻¹, end -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := by induction r; induction r'; reflexivity definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := by induction r; induction s; induction q; induction p; reflexivity definition apdt02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apdt f p = transport2 P r (f x) ⬝ apdt f q := by induction r; exact !idp_con⁻¹ end eq /- an auxillary namespace for concatenation and inversion for homotopies. We put this is a separate namespace because ⁻¹ʰ is also used as the inverse of a homomorphism -/ open eq namespace homotopy infix ` ⬝h `:75 := homotopy.trans postfix `⁻¹ʰ`:(max+1) := homotopy.symm end homotopy
e29ef65b0c01e610e85d446d2a0b9ec93b4d372b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/omega_complete_partial_order.lean
38b71e8c1dc8e3cb2615aa7c155e3d127b745841
[ "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
27,756
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.monad.basic import data.part import order.hom.order import data.nat.order.basic import tactic.wlog /-! # Omega Complete Partial Orders > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. The concept of an omega-complete partial order (ωCPO) is useful for the formalization of the semantics of programming languages. Its notion of supremum helps define the meaning of recursive procedures. ## Main definitions * class `omega_complete_partial_order` * `ite`, `map`, `bind`, `seq` as continuous morphisms ## Instances of `omega_complete_partial_order` * `part` * every `complete_lattice` * pi-types * product types * `monotone_hom` * `continuous_hom` (with notation →𝒄) * an instance of `omega_complete_partial_order (α →𝒄 β)` * `continuous_hom.of_fun` * `continuous_hom.of_mono` * continuous functions: * `id` * `ite` * `const` * `part.bind` * `part.map` * `part.seq` ## References * [Chain-complete posets and directed sets with applications][markowsky1976] * [Recursive definitions of partial functions and their computations][cadiou1972] * [Semantics of Programming Languages: Structures and Techniques][gunter1992] -/ universes u v local attribute [-simp] part.bind_eq_bind part.map_eq_map open_locale classical namespace order_hom variables (α : Type*) (β : Type*) {γ : Type*} {φ : Type*} variables [preorder α] [preorder β] [preorder γ] [preorder φ] variables {β γ} variables {α} {α' : Type*} {β' : Type*} [preorder α'] [preorder β'] /-- `part.bind` as a monotone function -/ @[simps] def bind {β γ} (f : α →o part β) (g : α →o β → part γ) : α →o part γ := { to_fun := λ x, f x >>= g x, monotone' := begin intros x y h a, simp only [and_imp, exists_prop, part.bind_eq_bind, part.mem_bind_iff, exists_imp_distrib], intros b hb ha, refine ⟨b, f.monotone h _ hb, g.monotone h _ _ ha⟩, end } end order_hom namespace omega_complete_partial_order /-- A chain is a monotone sequence. See the definition on page 114 of [gunter1992]. -/ def chain (α : Type u) [preorder α] := ℕ →o α namespace chain variables {α : Type u} {β : Type v} {γ : Type*} variables [preorder α] [preorder β] [preorder γ] instance : has_coe_to_fun (chain α) (λ _, ℕ → α) := order_hom.has_coe_to_fun instance [inhabited α] : inhabited (chain α) := ⟨⟨default, λ _ _ _, le_rfl⟩⟩ instance : has_mem α (chain α) := ⟨λ a (c : ℕ →o α), ∃ i, a = c i⟩ variables (c c' : chain α) variables (f : α →o β) variables (g : β →o γ) instance : has_le (chain α) := { le := λ x y, ∀ i, ∃ j, x i ≤ y j } /-- `map` function for `chain` -/ @[simps {fully_applied := ff}] def map : chain β := f.comp c variables {f} lemma mem_map (x : α) : x ∈ c → f x ∈ chain.map c f := λ ⟨i,h⟩, ⟨i, h.symm ▸ rfl⟩ lemma exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b := λ ⟨i,h⟩, ⟨c i, ⟨i, rfl⟩, h.symm⟩ lemma mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b := ⟨ exists_of_mem_map _, λ h, by { rcases h with ⟨w,h,h'⟩, subst b, apply mem_map c _ h, } ⟩ @[simp] lemma map_id : c.map order_hom.id = c := order_hom.comp_id _ lemma map_comp : (c.map f).map g = c.map (g.comp f) := rfl @[mono] lemma map_le_map {g : α →o β} (h : f ≤ g) : c.map f ≤ c.map g := λ i, by simp [mem_map_iff]; intros; existsi i; apply h /-- `chain.zip` pairs up the elements of two chains that have the same index -/ @[simps] def zip (c₀ : chain α) (c₁ : chain β) : chain (α × β) := order_hom.prod c₀ c₁ end chain end omega_complete_partial_order open omega_complete_partial_order section prio set_option extends_priority 50 /-- An omega-complete partial order is a partial order with a supremum operation on increasing sequences indexed by natural numbers (which we call `ωSup`). In this sense, it is strictly weaker than join complete semi-lattices as only ω-sized totally ordered sets have a supremum. See the definition on page 114 of [gunter1992]. -/ class omega_complete_partial_order (α : Type*) extends partial_order α := (ωSup : chain α → α) (le_ωSup : ∀(c:chain α), ∀ i, c i ≤ ωSup c) (ωSup_le : ∀(c:chain α) x, (∀ i, c i ≤ x) → ωSup c ≤ x) end prio namespace omega_complete_partial_order variables {α : Type u} {β : Type v} {γ : Type*} variables [omega_complete_partial_order α] /-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α` using a strictly monotone function `f : β →o α`, a definition of ωSup and a proof that `f` is continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/ @[reducible] protected def lift [partial_order β] (f : β →o α) (ωSup₀ : chain β → β) (h : ∀ x y, f x ≤ f y → x ≤ y) (h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : omega_complete_partial_order β := { ωSup := ωSup₀, ωSup_le := λ c x hx, h _ _ (by rw h'; apply ωSup_le; intro; apply f.monotone (hx i)), le_ωSup := λ c i, h _ _ (by rw h'; apply le_ωSup (c.map f)) } lemma le_ωSup_of_le {c : chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c := le_trans h (le_ωSup c _) lemma ωSup_total {c : chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c := classical.by_cases (assume : ∀ i, c i ≤ x, or.inl (ωSup_le _ _ this)) (assume : ¬ ∀ i, c i ≤ x, have ∃ i, ¬ c i ≤ x, by simp only [not_forall] at this ⊢; assumption, let ⟨i, hx⟩ := this in have x ≤ c i, from (h i).resolve_left hx, or.inr $ le_ωSup_of_le _ this) @[mono] lemma ωSup_le_ωSup_of_le {c₀ c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ := ωSup_le _ _ $ λ i, Exists.rec_on (h i) $ λ j h, le_trans h (le_ωSup _ _) lemma ωSup_le_iff (c : chain α) (x : α) : ωSup c ≤ x ↔ (∀ i, c i ≤ x) := begin split; intros, { transitivity ωSup c, exact le_ωSup _ _, assumption }, exact ωSup_le _ _ ‹_›, end /-- A subset `p : α → Prop` of the type closed under `ωSup` induces an `omega_complete_partial_order` on the subtype `{a : α // p a}`. -/ def subtype {α : Type*} [omega_complete_partial_order α] (p : α → Prop) (hp : ∀ (c : chain α), (∀ i ∈ c, p i) → p (ωSup c)) : omega_complete_partial_order (subtype p) := omega_complete_partial_order.lift (order_hom.subtype.val p) (λ c, ⟨ωSup _, hp (c.map (order_hom.subtype.val p)) (λ i ⟨n, q⟩, q.symm ▸ (c n).2)⟩) (λ x y h, h) (λ c, rfl) section continuity open chain variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- A monotone function `f : α →o β` is continuous if it distributes over ωSup. In order to distinguish it from the (more commonly used) continuity from topology (see topology/basic.lean), the present definition is often referred to as "Scott-continuity" (referring to Dana Scott). It corresponds to continuity in Scott topological spaces (not defined here). -/ def continuous (f : α →o β) : Prop := ∀ c : chain α, f (ωSup c) = ωSup (c.map f) /-- `continuous' f` asserts that `f` is both monotone and continuous. -/ def continuous' (f : α → β) : Prop := ∃ hf : monotone f, continuous ⟨f, hf⟩ lemma continuous'.to_monotone {f : α → β} (hf : continuous' f) : monotone f := hf.fst lemma continuous.of_bundled (f : α → β) (hf : monotone f) (hf' : continuous ⟨f, hf⟩) : continuous' f := ⟨hf, hf'⟩ lemma continuous.of_bundled' (f : α →o β) (hf' : continuous f) : continuous' f := ⟨f.mono, hf'⟩ lemma continuous'.to_bundled (f : α → β) (hf : continuous' f) : continuous ⟨f, hf.to_monotone⟩ := hf.snd @[simp, norm_cast] lemma continuous'_coe : ∀ {f : α →o β}, continuous' f ↔ continuous f | ⟨f, hf⟩ := ⟨λ ⟨hf', hc⟩, hc, λ hc, ⟨hf, hc⟩⟩ variables (f : α →o β) (g : β →o γ) lemma continuous_id : continuous (@order_hom.id α _) := by intro; rw c.map_id; refl lemma continuous_comp (hfc : continuous f) (hgc : continuous g) : continuous (g.comp f):= begin dsimp [continuous] at *, intro, rw [hfc,hgc,chain.map_comp] end lemma id_continuous' : continuous' (@id α) := continuous_id.of_bundled' _ lemma continuous_const (x : β) : continuous (order_hom.const α x) := λ c, eq_of_forall_ge_iff $ λ z, by simp [ωSup_le_iff] lemma const_continuous' (x: β) : continuous' (function.const α x) := continuous.of_bundled' (order_hom.const α x) (continuous_const x) end continuity end omega_complete_partial_order namespace part variables {α : Type u} {β : Type v} {γ : Type*} open omega_complete_partial_order lemma eq_of_chain {c : chain (part α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := begin cases ha with i ha, replace ha := ha.symm, cases hb with j hb, replace hb := hb.symm, wlog h : i ≤ j, { exact (this j hb i ha (le_of_not_le h)).symm }, rw [eq_some_iff] at ha hb, have := c.monotone h _ ha, apply mem_unique this hb end /-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `part α`. -/ protected noncomputable def ωSup (c : chain (part α)) : part α := if h : ∃a, some a ∈ c then some (classical.some h) else none lemma ωSup_eq_some {c : chain (part α)} {a : α} (h : some a ∈ c) : part.ωSup c = some a := have ∃a, some a ∈ c, from ⟨a, h⟩, have a' : some (classical.some this) ∈ c, from classical.some_spec this, calc part.ωSup c = some (classical.some this) : dif_pos this ... = some a : congr_arg _ (eq_of_chain a' h) lemma ωSup_eq_none {c : chain (part α)} (h : ¬∃a, some a ∈ c) : part.ωSup c = none := dif_neg h lemma mem_chain_of_mem_ωSup {c : chain (part α)} {a : α} (h : a ∈ part.ωSup c) : some a ∈ c := begin simp [part.ωSup] at h, split_ifs at h, { have h' := classical.some_spec h_1, rw ← eq_some_iff at h, rw ← h, exact h' }, { rcases h with ⟨ ⟨ ⟩ ⟩ } end noncomputable instance omega_complete_partial_order : omega_complete_partial_order (part α) := { ωSup := part.ωSup, le_ωSup := λ c i, by { intros x hx, rw ← eq_some_iff at hx ⊢, rw [ωSup_eq_some, ← hx], rw ← hx, exact ⟨i,rfl⟩ }, ωSup_le := by { rintros c x hx a ha, replace ha := mem_chain_of_mem_ωSup ha, cases ha with i ha, apply hx i, rw ← ha, apply mem_some } } section inst lemma mem_ωSup (x : α) (c : chain (part α)) : x ∈ ωSup c ↔ some x ∈ c := begin simp [omega_complete_partial_order.ωSup,part.ωSup], split, { split_ifs, swap, rintro ⟨⟨⟩⟩, intro h', have hh := classical.some_spec h, simp at h', subst x, exact hh }, { intro h, have h' : ∃ (a : α), some a ∈ c := ⟨_,h⟩, rw dif_pos h', have hh := classical.some_spec h', rw eq_of_chain hh h, simp } end end inst end part namespace pi variables {α : Type*} {β : α → Type*} {γ : Type*} open omega_complete_partial_order omega_complete_partial_order.chain instance [∀a, omega_complete_partial_order (β a)] : omega_complete_partial_order (Πa, β a) := { ωSup := λc a, ωSup (c.map (pi.eval_order_hom a)), ωSup_le := assume c f hf a, ωSup_le _ _ $ by { rintro i, apply hf }, le_ωSup := assume c i x, le_ωSup_of_le _ $ le_rfl } namespace omega_complete_partial_order variables [∀ x, omega_complete_partial_order $ β x] variables [omega_complete_partial_order γ] lemma flip₁_continuous' (f : ∀ x : α, γ → β x) (a : α) (hf : continuous' (λ x y, f y x)) : continuous' (f a) := continuous.of_bundled _ (λ x y h, hf.to_monotone h a) (λ c, congr_fun (hf.to_bundled _ c) a) lemma flip₂_continuous' (f : γ → Π x, β x) (hf : ∀ x, continuous' (λ g, f g x)) : continuous' f := continuous.of_bundled _ (λ x y h a, (hf a).to_monotone h) (by intro c; ext a; apply (hf a).to_bundled _ c) end omega_complete_partial_order end pi namespace prod open omega_complete_partial_order variables {α : Type*} {β : Type*} {γ : Type*} variables [omega_complete_partial_order α] variables [omega_complete_partial_order β] variables [omega_complete_partial_order γ] /-- The supremum of a chain in the product `ω`-CPO. -/ @[simps] protected def ωSup (c : chain (α × β)) : α × β := (ωSup (c.map order_hom.fst), ωSup (c.map order_hom.snd)) @[simps ωSup_fst ωSup_snd] instance : omega_complete_partial_order (α × β) := { ωSup := prod.ωSup, ωSup_le := λ c ⟨x,x'⟩ h, ⟨ωSup_le _ _ $ λ i, (h i).1, ωSup_le _ _ $ λ i, (h i).2⟩, le_ωSup := λ c i, ⟨le_ωSup (c.map order_hom.fst) i, le_ωSup (c.map order_hom.snd) i⟩ } lemma ωSup_zip (c₀ : chain α) (c₁ : chain β) : ωSup (c₀.zip c₁) = (ωSup c₀, ωSup c₁) := begin apply eq_of_forall_ge_iff, rintro ⟨z₁,z₂⟩, simp [ωSup_le_iff, forall_and_distrib], end end prod open omega_complete_partial_order namespace complete_lattice variables (α : Type u) /-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case of arbitrary suprema. -/ @[priority 100] -- see Note [lower instance priority] instance [complete_lattice α] : omega_complete_partial_order α := { ωSup := λc, ⨆ i, c i, ωSup_le := λ ⟨c, _⟩ s hs, by simp only [supr_le_iff, order_hom.coe_fun_mk] at ⊢ hs; intros i; apply hs i, le_ωSup := assume ⟨c, _⟩ i, by simp only [order_hom.coe_fun_mk]; apply le_supr_of_le i; refl } variables {α} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] lemma Sup_continuous (s : set $ α →o β) (hs : ∀ f ∈ s, continuous f) : continuous (Sup s) := begin intro c, apply eq_of_forall_ge_iff, intro z, suffices : (∀ (f ∈ s) n, (f : _) (c n) ≤ z) ↔ (∀ n (f ∈ s), (f : _) (c n) ≤ z), by simpa [ωSup_le_iff, hs _ _ _] { contextual := tt }, exact ⟨λ H n f hf, H f hf n, λ H f hf n, H n f hf⟩ end lemma supr_continuous {ι : Sort*} {f : ι → α →o β} (h : ∀ i, continuous (f i)) : continuous (⨆ i, f i) := Sup_continuous _ $ set.forall_range_iff.2 h theorem Sup_continuous' (s : set (α → β)) (hc : ∀ f ∈ s, continuous' f) : continuous' (Sup s) := begin lift s to set (α →o β) using λ f hf, (hc f hf).to_monotone, simp only [set.ball_image_iff, continuous'_coe] at hc, rw [Sup_image], norm_cast, exact supr_continuous (λ f, supr_continuous (λ hf, hc f hf)), end lemma sup_continuous {f g : α →o β} (hf : continuous f) (hg : continuous g) : continuous (f ⊔ g) := begin rw ← Sup_pair, apply Sup_continuous, rintro f (rfl|rfl|_); assumption end lemma top_continuous : continuous (⊤ : α →o β) := begin intro c, apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, forall_const, chain.map_coe, (∘), function.const, order_hom.has_top_top, order_hom.const_coe_coe], end lemma bot_continuous : continuous (⊥ : α →o β) := begin rw ← Sup_empty, exact Sup_continuous _ (λ f hf, hf.elim), end end complete_lattice namespace complete_lattice variables {α β : Type*} [omega_complete_partial_order α] [complete_linear_order β] lemma inf_continuous (f g : α →o β) (hf : continuous f) (hg : continuous g) : continuous (f ⊓ g) := begin refine λ c, eq_of_forall_ge_iff (λ z, _), simp only [inf_le_iff, hf c, hg c, ωSup_le_iff, ←forall_or_distrib_left, ←forall_or_distrib_right, function.comp_app, chain.map_coe, order_hom.has_inf_inf_coe], exact ⟨λ h _, h _ _, λ h i j, (h (max i j)).imp (le_trans $ f.mono $ c.mono $ le_max_left _ _) (le_trans $ g.mono $ c.mono $ le_max_right _ _)⟩, end lemma inf_continuous' {f g : α → β} (hf : continuous' f) (hg : continuous' g) : continuous' (f ⊓ g) := ⟨_, inf_continuous _ _ hf.snd hg.snd⟩ end complete_lattice namespace omega_complete_partial_order variables {α : Type u} {α' : Type*} {β : Type v} {β' : Type*} {γ : Type*} {φ : Type*} variables [omega_complete_partial_order α] [omega_complete_partial_order β] variables [omega_complete_partial_order γ] [omega_complete_partial_order φ] variables [omega_complete_partial_order α'] [omega_complete_partial_order β'] namespace order_hom /-- The `ωSup` operator for monotone functions. -/ @[simps] protected def ωSup (c : chain (α →o β)) : α →o β := { to_fun := λ a, ωSup (c.map (order_hom.apply a)), monotone' := λ x y h, ωSup_le_ωSup_of_le (chain.map_le_map _ $ λ a, a.monotone h) } @[simps ωSup_coe] instance omega_complete_partial_order : omega_complete_partial_order (α →o β) := omega_complete_partial_order.lift order_hom.coe_fn_hom order_hom.ωSup (λ x y h, h) (λ c, rfl) end order_hom section variables (α β) /-- A monotone function on `ω`-continuous partial orders is said to be continuous if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`. This is just the bundled version of `order_hom.continuous`. -/ structure continuous_hom extends order_hom α β := (cont : continuous (order_hom.mk to_fun monotone')) attribute [nolint doc_blame] continuous_hom.to_order_hom infixr ` →𝒄 `:25 := continuous_hom -- Input: \r\MIc instance : has_coe_to_fun (α →𝒄 β) (λ _, α → β) := ⟨λ f, f.to_order_hom.to_fun⟩ instance : has_coe (α →𝒄 β) (α →o β) := { coe := continuous_hom.to_order_hom } instance : partial_order (α →𝒄 β) := partial_order.lift (λ f, f.to_order_hom.to_fun) $ by rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ h; congr; exact h /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def continuous_hom.simps.apply (h : α →𝒄 β) : α → β := h initialize_simps_projections continuous_hom (to_order_hom_to_fun → apply, -to_order_hom) end namespace continuous_hom theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →𝒄 β, h x) h theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h protected lemma monotone (f : α →𝒄 β) : monotone f := f.monotone' @[mono] lemma apply_mono {f g : α →𝒄 β} {x y : α} (h₁ : f ≤ g) (h₂ : x ≤ y) : f x ≤ g y := order_hom.apply_mono (show (f : α →o β) ≤ g, from h₁) h₂ lemma ite_continuous' {p : Prop} [hp : decidable p] (f g : α → β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, if p then f x else g x) := by split_ifs; simp * lemma ωSup_bind {β γ : Type v} (c : chain α) (f : α →o part β) (g : α →o β → part γ) : ωSup (c.map (f.bind g)) = ωSup (c.map f) >>= ωSup (c.map g) := begin apply eq_of_forall_ge_iff, intro x, simp only [ωSup_le_iff, part.bind_le, chain.mem_map_iff, and_imp, order_hom.bind_coe, exists_imp_distrib], split; intro h''', { intros b hb, apply ωSup_le _ _ _, rintros i y hy, simp only [part.mem_ωSup] at hb, rcases hb with ⟨j,hb⟩, replace hb := hb.symm, simp only [part.eq_some_iff, chain.map_coe, function.comp_app, order_hom.apply_coe] at hy hb, replace hb : b ∈ f (c (max i j)) := f.mono (c.mono (le_max_right i j)) _ hb, replace hy : y ∈ g (c (max i j)) b := g.mono (c.mono (le_max_left i j)) _ _ hy, apply h''' (max i j), simp only [exists_prop, part.bind_eq_bind, part.mem_bind_iff, chain.map_coe, function.comp_app, order_hom.bind_coe], exact ⟨_,hb,hy⟩, }, { intros i, intros y hy, simp only [exists_prop, part.bind_eq_bind, part.mem_bind_iff, chain.map_coe, function.comp_app, order_hom.bind_coe] at hy, rcases hy with ⟨b,hb₀,hb₁⟩, apply h''' b _, { apply le_ωSup (c.map g) _ _ _ hb₁ }, { apply le_ωSup (c.map f) i _ hb₀ } }, end lemma bind_continuous' {β γ : Type v} (f : α → part β) (g : α → β → part γ) : continuous' f → continuous' g → continuous' (λ x, f x >>= g x) | ⟨hf,hf'⟩ ⟨hg,hg'⟩ := continuous.of_bundled' (order_hom.bind ⟨f,hf⟩ ⟨g,hg⟩) (by intro c; rw [ωSup_bind, ← hf', ← hg']; refl) lemma map_continuous' {β γ : Type v} (f : β → γ) (g : α → part β) (hg : continuous' g) : continuous' (λ x, f <$> g x) := by simp only [map_eq_bind_pure_comp]; apply bind_continuous' _ _ hg; apply const_continuous' lemma seq_continuous' {β γ : Type v} (f : α → part (β → γ)) (g : α → part β) (hf : continuous' f) (hg : continuous' g) : continuous' (λ x, f x <*> g x) := by simp only [seq_eq_bind_map]; apply bind_continuous' _ _ hf; apply pi.omega_complete_partial_order.flip₂_continuous'; intro; apply map_continuous' _ _ hg lemma continuous (F : α →𝒄 β) (C : chain α) : F (ωSup C) = ωSup (C.map F) := continuous_hom.cont _ _ /-- Construct a continuous function from a bare function, a continuous function, and a proof that they are equal. -/ @[simps, reducible] def of_fun (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β := by refine {to_order_hom := {to_fun := f, ..}, ..}; subst h; rcases g with ⟨⟨⟩⟩; assumption /-- Construct a continuous function from a monotone function with a proof of continuity. -/ @[simps, reducible] def of_mono (f : α →o β) (h : ∀ c : chain α, f (ωSup c) = ωSup (c.map f)) : α →𝒄 β := { to_fun := f, monotone' := f.monotone, cont := h } /-- The identity as a continuous function. -/ @[simps] def id : α →𝒄 α := of_mono order_hom.id continuous_id /-- The composition of continuous functions. -/ @[simps] def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ := of_mono (order_hom.comp (↑f) (↑g)) (continuous_comp _ _ g.cont f.cont) @[ext] protected lemma ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr; ext; apply h protected lemma coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g := continuous_hom.ext _ _ $ _root_.congr_fun h @[simp] lemma comp_id (f : β →𝒄 γ) : f.comp id = f := by ext; refl @[simp] lemma id_comp (f : β →𝒄 γ) : id.comp f = f := by ext; refl @[simp] lemma comp_assoc (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h := by ext; refl @[simp] lemma coe_apply (a : α) (f : α →𝒄 β) : (f : α →o β) a = f a := rfl /-- `function.const` is a continuous function. -/ def const (x : β) : α →𝒄 β := of_mono (order_hom.const _ x) (continuous_const x) @[simp] theorem const_apply (f : β) (a : α) : const f a = f := rfl instance [inhabited β] : inhabited (α →𝒄 β) := ⟨ const default ⟩ /-- The map from continuous functions to monotone functions is itself a monotone function. -/ @[simps] def to_mono : (α →𝒄 β) →o (α →o β) := { to_fun := λ f, f, monotone' := λ x y h, h } /-- When proving that a chain of applications is below a bound `z`, it suffices to consider the functions and values being selected from the same index in the chains. This lemma is more specific than necessary, i.e. `c₀` only needs to be a chain of monotone functions, but it is only used with continuous functions. -/ @[simp] lemma forall_forall_merge (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (i j : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := begin split; introv h, { apply h }, { apply le_trans _ (h (max i j)), transitivity c₀ i (c₁ (max i j)), { apply (c₀ i).monotone, apply c₁.monotone, apply le_max_right }, { apply c₀.monotone, apply le_max_left } } end @[simp] lemma forall_forall_merge' (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (j i : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z := by rw [forall_swap,forall_forall_merge] /-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum of the functions in the `ω`-chain. -/ @[simps] protected def ωSup (c : chain (α →𝒄 β)) : α →𝒄 β := continuous_hom.of_mono (ωSup $ c.map to_mono) begin intro c', apply eq_of_forall_ge_iff, intro z, simp only [ωSup_le_iff, (c _).continuous, chain.map_coe, order_hom.apply_coe, to_mono_coe, coe_apply, order_hom.omega_complete_partial_order_ωSup_coe, forall_forall_merge, forall_forall_merge', (∘), function.eval], end @[simps ωSup] instance : omega_complete_partial_order (α →𝒄 β) := omega_complete_partial_order.lift continuous_hom.to_mono continuous_hom.ωSup (λ x y h, h) (λ c, rfl) namespace prod /-- The application of continuous functions as a continuous function. -/ @[simps] def apply : (α →𝒄 β) × α →𝒄 β := { to_fun := λ f, f.1 f.2, monotone' := λ x y h, by {dsimp, transitivity y.fst x.snd; [apply h.1, apply y.1.monotone h.2]}, cont := begin intro c, apply le_antisymm, { apply ωSup_le, intros i, dsimp, rw (c _).fst.continuous, apply ωSup_le, intros j, apply le_ωSup_of_le (max i j), apply apply_mono, exact monotone_fst (order_hom.mono _ (le_max_left _ _)), exact monotone_snd (order_hom.mono _ (le_max_right _ _)), }, { apply ωSup_le, intros i, apply le_ωSup_of_le i, dsimp, apply order_hom.mono _, apply le_ωSup_of_le i, reflexivity, } end } end prod lemma ωSup_def (c : chain (α →𝒄 β)) (x : α) : ωSup c x = continuous_hom.ωSup c x := rfl lemma ωSup_apply_ωSup (c₀ : chain (α →𝒄 β)) (c₁ : chain α) : ωSup c₀ (ωSup c₁) = prod.apply (ωSup (c₀.zip c₁)) := by simp [prod.apply_apply, prod.ωSup_zip] /-- A family of continuous functions yields a continuous family of functions. -/ @[simps] def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ := { to_fun := λ x y, f y x, monotone' := λ x y h a, (f a).monotone h, cont := by intro; ext; change f x _ = _; rw [(f x).continuous ]; refl, } /-- `part.bind` as a continuous function. -/ @[simps { rhs_md := reducible }] noncomputable def bind {β γ : Type v} (f : α →𝒄 part β) (g : α →𝒄 β → part γ) : α →𝒄 part γ := of_mono (order_hom.bind (↑f) (↑g)) $ λ c, begin rw [order_hom.bind, ← order_hom.bind, ωSup_bind, ← f.continuous, ← g.continuous], refl end /-- `part.map` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 part β) : α →𝒄 part γ := of_fun (λ x, f <$> g x) (bind g (const (pure ∘ f))) $ by ext; simp only [map_eq_bind_pure_comp, bind_apply, order_hom.bind_coe, const_apply, order_hom.const_coe_coe, coe_apply] /-- `part.seq` as a continuous function. -/ @[simps {rhs_md := reducible}] noncomputable def seq {β γ : Type v} (f : α →𝒄 part (β → γ)) (g : α →𝒄 part β) : α →𝒄 part γ := of_fun (λ x, f x <*> g x) (bind f $ (flip $ _root_.flip map g)) (by ext; simp only [seq_eq_bind_map, flip, part.bind_eq_bind, map_apply, part.mem_bind_iff, bind_apply, order_hom.bind_coe, coe_apply, flip_apply]; refl) end continuous_hom end omega_complete_partial_order
e3177f74fd11016a2726a080f95d99b8ef803d12
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/game/birthday.lean
c9b2642f8e8b8d197536c9b0b1600500c88f3935
[ "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
5,761
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import set_theory.game.ordinal import set_theory.ordinal.natural_ops /-! # Birthdays of games The birthday of a game is an ordinal that represents at which "step" the game was constructed. We define it recursively as the least ordinal larger than the birthdays of its left and right games. We prove the basic properties about these. # Main declarations - `pgame.birthday`: The birthday of a pre-game. # Todo - Define the birthdays of `game`s and `surreal`s. - Characterize the birthdays of basic arithmetical operations. -/ universe u open ordinal open_locale natural_ops pgame namespace pgame /-- The birthday of a pre-game is inductively defined as the least strict upper bound of the birthdays of its left and right games. It may be thought as the "step" in which a certain game is constructed. -/ noncomputable def birthday : pgame.{u} → ordinal.{u} | ⟨xl, xr, xL, xR⟩ := max (lsub.{u u} $ λ i, birthday (xL i)) (lsub.{u u} $ λ i, birthday (xR i)) theorem birthday_def (x : pgame) : birthday x = max (lsub.{u u} (λ i, birthday (x.move_left i))) (lsub.{u u} (λ i, birthday (x.move_right i))) := by { cases x, rw birthday, refl } theorem birthday_move_left_lt {x : pgame} (i : x.left_moves) : (x.move_left i).birthday < x.birthday := by { cases x, rw birthday, exact lt_max_of_lt_left (lt_lsub _ i) } theorem birthday_move_right_lt {x : pgame} (i : x.right_moves) : (x.move_right i).birthday < x.birthday := by { cases x, rw birthday, exact lt_max_of_lt_right (lt_lsub _ i) } theorem lt_birthday_iff {x : pgame} {o : ordinal} : o < x.birthday ↔ (∃ i : x.left_moves, o ≤ (x.move_left i).birthday) ∨ (∃ i : x.right_moves, o ≤ (x.move_right i).birthday) := begin split, { rw birthday_def, intro h, cases lt_max_iff.1 h with h' h', { left, rwa lt_lsub_iff at h' }, { right, rwa lt_lsub_iff at h' } }, { rintro (⟨i, hi⟩ | ⟨i, hi⟩), { exact hi.trans_lt (birthday_move_left_lt i) }, { exact hi.trans_lt (birthday_move_right_lt i) } } end theorem relabelling.birthday_congr : ∀ {x y : pgame.{u}}, x ≡r y → birthday x = birthday y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ r := begin unfold birthday, congr' 1, all_goals { apply lsub_eq_of_range_eq.{u u u}, ext i, split }, all_goals { rintro ⟨j, rfl⟩ }, { exact ⟨_, (r.move_left j).birthday_congr.symm⟩ }, { exact ⟨_, (r.move_left_symm j).birthday_congr⟩ }, { exact ⟨_, (r.move_right j).birthday_congr.symm⟩ }, { exact ⟨_, (r.move_right_symm j).birthday_congr⟩ } end using_well_founded { dec_tac := pgame_wf_tac } @[simp] theorem birthday_eq_zero {x : pgame} : birthday x = 0 ↔ is_empty x.left_moves ∧ is_empty x.right_moves := by rw [birthday_def, max_eq_zero, lsub_eq_zero_iff, lsub_eq_zero_iff] @[simp] theorem birthday_zero : birthday 0 = 0 := by simp [pempty.is_empty] @[simp] theorem birthday_one : birthday 1 = 1 := by { rw birthday_def, simp } @[simp] theorem birthday_star : birthday star = 1 := by { rw birthday_def, simp } @[simp] theorem neg_birthday : ∀ x : pgame, (-x).birthday = x.birthday | ⟨xl, xr, xL, xR⟩ := begin rw [birthday_def, birthday_def, max_comm], congr; funext; apply neg_birthday end @[simp] theorem to_pgame_birthday (o : ordinal) : o.to_pgame.birthday = o := begin induction o using ordinal.induction with o IH, rw [to_pgame_def, pgame.birthday], simp only [lsub_empty, max_zero_right], nth_rewrite 0 ←lsub_typein o, congr' with x, exact IH _ (typein_lt_self x) end theorem le_birthday : ∀ x : pgame, x ≤ x.birthday.to_pgame | ⟨xl, _, xL, _⟩ := le_def.2 ⟨λ i, or.inl ⟨to_left_moves_to_pgame ⟨_, birthday_move_left_lt i⟩, by simp [le_birthday (xL i)]⟩, is_empty_elim⟩ variables (a b x : pgame.{u}) theorem neg_birthday_le : -x.birthday.to_pgame ≤ x := by simpa only [neg_birthday, ←neg_le_iff] using le_birthday (-x) @[simp] theorem birthday_add : ∀ x y : pgame.{u}, (x + y).birthday = x.birthday ♯ y.birthday | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ := begin rw [birthday_def, nadd_def], simp only [birthday_add, lsub_sum, mk_add_move_left_inl, move_left_mk, mk_add_move_left_inr, mk_add_move_right_inl, move_right_mk, mk_add_move_right_inr], rw max_max_max_comm, congr; apply le_antisymm, any_goals { exact max_le_iff.2 ⟨lsub_le_iff.2 (λ i, lt_blsub _ _ (birthday_move_left_lt i)), lsub_le_iff.2 (λ i, lt_blsub _ _ (birthday_move_right_lt i))⟩ }, all_goals { apply blsub_le_iff.2 (λ i hi, _), rcases lt_birthday_iff.1 hi with ⟨j, hj⟩ | ⟨j, hj⟩ }, { exact lt_max_of_lt_left ((nadd_le_nadd_right hj _).trans_lt (lt_lsub _ _)) }, { exact lt_max_of_lt_right ((nadd_le_nadd_right hj _).trans_lt (lt_lsub _ _)) }, { exact lt_max_of_lt_left ((nadd_le_nadd_left hj _).trans_lt (lt_lsub _ _)) }, { exact lt_max_of_lt_right ((nadd_le_nadd_left hj _).trans_lt (lt_lsub _ _)) } end using_well_founded { dec_tac := pgame_wf_tac } theorem birthday_add_zero : (a + 0).birthday = a.birthday := by simp theorem birthday_zero_add : (0 + a).birthday = a.birthday := by simp theorem birthday_add_one : (a + 1).birthday = order.succ a.birthday := by simp theorem birthday_one_add : (1 + a).birthday = order.succ a.birthday := by simp @[simp] theorem birthday_nat_cast : ∀ n : ℕ, birthday n = n | 0 := birthday_zero | (n + 1) := by simp [birthday_nat_cast] theorem birthday_add_nat (n : ℕ) : (a + n).birthday = a.birthday + n := by simp theorem birthday_nat_add (n : ℕ) : (↑n + a).birthday = a.birthday + n := by simp end pgame
b645fe38cb8e1010b86d90eca137aa6c5ebe4272
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/rewrite5.lean
826274e78c202fd65ea8c10bd164ea56fbdfb282
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
189
lean
import algebra.group open algebra variable {A : Type} variable [s : group A] include s theorem mul.right_inv (a : A) : a * a⁻¹ = 1 := by rewrite ⟨-{a}inv_inv at {1}, mul.left_inv⟩
ce677bf57f0cf822eb339a8ec3fa4622ad741188
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/computability/halting.lean
f59bc553182b15be67328377698ccae69face1cf
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
13,263
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro More partial recursive functions using a universal program; Rice's theorem and the halting problem. -/ import computability.partrec_code open encodable denumerable namespace nat.partrec open computable roption theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin rcases code.exists_code.1 hf with ⟨cf, rfl⟩, rcases code.exists_code.1 hg with ⟨cg, rfl⟩, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp [dom_iff_mem, code.evaln_complete] at h, rcases h with ⟨x, k, e⟩ | ⟨x, k, e⟩, { refine ⟨k, x, _⟩, simp [e] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp [e]⟩ }, { exact ⟨y, by simp⟩ } } }, { intros x h, rcases nat.rfind_opt_spec h with ⟨k, e⟩, revert e, simp; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable roption nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode2_iff.1 hf) (bind_decode2_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, simp [k'], have hk : (k (encode a)).dom := (H _).2.2 (by simpa [encodek2] using h), existsi hk, cases (H _).1 _ ⟨hk, rfl⟩ with h h; { simp at h, rcases h with ⟨a', ha', y, hy, e⟩, simp [e.symm, encodek] } }, { intros x h', simp [k'] at h', rcases h' with ⟨n, hn, hx⟩, have := (H _).1 _ hn, simp [mem_decode2, encode_injective.eq_iff] at this, cases this with h h; { rcases h with ⟨a', ha, rfl⟩, simp [encodek] at hx, subst a', simp [ha] } }, end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp end partrec def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /- recursively enumerable predicate -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, roption.assert (p a) (λ _, roption.some ())) theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by rcases computable_iff.1 hp with ⟨f, hf, rfl⟩; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin rcases computable_iff.1 hp with ⟨f, hf, rfl⟩, unfold re_pred, refine (partrec.cond hf (partrec.const' (roption.some ())) partrec.none).of_eq (λ n, roption.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, rcases fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂ with ⟨c, e⟩, simp at e, by_cases eval c ∈ C, { simp [h] at e, rwa ← e }, { simp at h, simp [h] at e, rw e at h, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by haveI := classical.dec; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_nonempty.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by rcases h with rfl | rfl; simp [computable_pred]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin rcases partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _ with ⟨k, pk, hk⟩, { refine partrec.of_eq pk (λ n, roption.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ end computable_pred namespace nat open vector roption /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n :: v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.part, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a :: v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, roption.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a :: v))) := by simp [(roption.bind_some_eq_map _ _).symm]; exact hf.bind hg def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a :: v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, roption.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, roption.ext $ λ b, begin simp [nat.rfind_opt, -nat.mem_rfind], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr; funext n, simp, cases f (n :: v); simp [nat.succ_ne_zero]; refl }, { have := nat.rfind_spec h, simp at this, cases f (a :: v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp [g]; simp [encodek, roption.map_id']), end, λ f hf, begin rcases exists_code.1 hf with ⟨c, rfl⟩, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
16a57acf1f86428813e3916e71dfe6fbe2d8e35c
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/nat/bitwise.lean
9d84ee8fbaec60223abc780bb505b154d473feb2
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
10,784
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ prelude import init.data.nat.lemmas init.meta.well_founded_tactics universe u namespace nat def bodd_div2 : ℕ → bool × ℕ | 0 := (ff, 0) | (succ n) := match bodd_div2 n with | (ff, m) := (tt, m) | (tt, m) := (ff, succ m) end def div2 (n : ℕ) : ℕ := (bodd_div2 n).2 def bodd (n : ℕ) : bool := (bodd_div2 n).1 @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_succ (n : ℕ) : bodd (succ n) = bnot (bodd n) := by unfold bodd bodd_div2; cases bodd_div2 n; cases fst; refl @[simp] lemma bodd_add (m n : ℕ) : bodd (m + n) = bxor (bodd m) (bodd n) := begin induction n with n IH, { simp, cases bodd m; refl }, { simp [IH], cases bodd m; cases bodd n; refl } end @[simp] lemma bodd_mul (m n : ℕ) : bodd (m * n) = bodd m && bodd n := begin induction n with n IH, { simp, cases bodd m; refl }, { simp [mul_succ, IH], cases bodd m; cases bodd n; refl } end lemma mod_two_of_bodd (n : ℕ) : n % 2 = cond (bodd n) 1 0 := begin have := congr_arg bodd (mod_add_div n 2), simp [bnot] at this, rw [show ∀ b, ff && b = ff, by intros; cases b; refl, show ∀ b, bxor b ff = b, by intros; cases b; refl] at this, rw [← this], cases mod_two_eq_zero_or_one n; rw a; refl end @[simp] lemma div2_zero : div2 0 = 0 := rfl @[simp] lemma div2_one : div2 1 = 0 := rfl @[simp] lemma div2_two : div2 2 = 1 := rfl @[simp] lemma div2_succ (n : ℕ) : div2 (succ n) = cond (bodd n) (succ (div2 n)) (div2 n) := by unfold bodd div2 bodd_div2; cases bodd_div2 n; cases fst; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | 0 := rfl | (succ n) := begin simp, refine eq.trans _ (congr_arg succ (bodd_add_div2 n)), cases bodd n; simp [cond, bnot], { rw add_comm; refl }, { rw [succ_mul, add_comm 1] } end theorem div2_val (n) : div2 n = n / 2 := by refine eq_of_mul_eq_mul_left dec_trivial (nat.add_left_cancel (eq.trans _ (mod_add_div n 2).symm)); rw [mod_two_of_bodd, bodd_add_div2] def bit (b : bool) : ℕ → ℕ := cond b bit1 bit0 lemma bit0_val (n : nat) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : nat) : bit1 n = 2 * n + 1 := congr_arg succ (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply bit0_val, apply bit1_val } lemma bit_decomp (n : nat) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def bit_cases_on {C : nat → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl def shiftl' (b : bool) (m : ℕ) : ℕ → ℕ | 0 := m | (n+1) := bit b (shiftl' n) def shiftl : ℕ → ℕ → ℕ := shiftl' ff @[simp] theorem shiftl_zero (m) : shiftl m 0 = m := rfl @[simp] theorem shiftl_succ (m n) : shiftl m (n + 1) = bit0 (shiftl m n) := rfl def shiftr : ℕ → ℕ → ℕ | m 0 := m | m (n+1) := div2 (shiftr m n) def test_bit (m n : ℕ) : bool := bodd (shiftr m n) def binary_rec {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : Π n, C n | n := if n0 : n = 0 then by rw n0; exact z else let n' := div2 n in have n' < n, begin change div2 n < n, rw div2_val, apply (div_lt_iff_lt_mul _ _ (succ_pos 1)).2, have := nat.mul_lt_mul_of_pos_left (lt_succ_self 1) (lt_of_le_of_ne (zero_le _) (ne.symm n0)), rwa mul_one at this end, by rw [← show bit (bodd n) n' = n, from bit_decomp n]; exact f (bodd n) n' (binary_rec n') def size : ℕ → ℕ := binary_rec 0 (λ_ _, succ) def bits : ℕ → list bool := binary_rec [] (λb _ IH, b :: IH) def bitwise (f : bool → bool → bool) : ℕ → ℕ → ℕ := binary_rec (λn, cond (f ff tt) n 0) (λa m Ia, binary_rec (cond (f tt ff) (bit a m) 0) (λb n _, bit (f a b) (Ia n))) def lor : ℕ → ℕ → ℕ := bitwise bor def land : ℕ → ℕ → ℕ := bitwise band def ldiff : ℕ → ℕ → ℕ := bitwise (λ a b, a && bnot b) def lxor : ℕ → ℕ → ℕ := bitwise bxor @[simp] lemma binary_rec_zero {C : nat → Sort u} (z : C 0) (f : ∀ b n, C n → C (bit b n)) : binary_rec z f 0 = z := by {rw [binary_rec], refl} /- bitwise ops -/ lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl lemma div2_bit (b n) : div2 (bit b n) = n := by rw [bit_val, div2_val, add_comm, add_mul_div_left, div_eq_of_lt, zero_add]; cases b; exact dec_trivial lemma shiftl'_add (b m n) : ∀ k, shiftl' b m (n + k) = shiftl' b (shiftl' b m n) k | 0 := rfl | (k+1) := congr_arg (bit b) (shiftl'_add k) lemma shiftl_add : ∀ m n k, shiftl m (n + k) = shiftl (shiftl m n) k := shiftl'_add _ lemma shiftr_add (m n) : ∀ k, shiftr m (n + k) = shiftr (shiftr m n) k | 0 := rfl | (k+1) := congr_arg div2 (shiftr_add k) lemma shiftl'_sub (b m) : ∀ {n k}, k ≤ n → shiftl' b m (n - k) = shiftr (shiftl' b m n) k | n 0 h := rfl | (n+1) (k+1) h := begin simp [shiftl'], rw [add_comm, shiftr_add], simp [shiftr, div2_bit], apply shiftl'_sub (nat.le_of_succ_le_succ h) end lemma shiftl_sub : ∀ m {n k}, k ≤ n → shiftl m (n - k) = shiftr (shiftl m n) k := shiftl'_sub _ lemma shiftl_eq_mul_pow (m) : ∀ n, shiftl m n = m * 2 ^ n | 0 := (mul_one _).symm | (k+1) := show bit0 (shiftl m k) = m * (2^k * 2), by rw [bit0_val, shiftl_eq_mul_pow]; simp lemma shiftl'_tt_eq_mul_pow (m) : ∀ n, shiftl' tt m n + 1 = (m + 1) * 2 ^ n | 0 := by simp [shiftl, shiftl'] | (k+1) := begin change bit1 (shiftl' tt m k) + 1 = (m + 1) * (2^k * 2), rw bit1_val, change 2 * (shiftl' tt m k + 1) = _, rw shiftl'_tt_eq_mul_pow; simp end lemma one_shiftl (n) : shiftl 1 n = 2 ^ n := (shiftl_eq_mul_pow _ _).trans (one_mul _) @[simp] lemma zero_shiftl (n) : shiftl 0 n = 0 := (shiftl_eq_mul_pow _ _).trans (zero_mul _) lemma shiftr_eq_div_pow (m) : ∀ n, shiftr m n = m / 2 ^ n | 0 := (nat.div_one _).symm | (k+1) := (congr_arg div2 (shiftr_eq_div_pow k)).trans $ by rw [div2_val, nat.div_div_eq_div_mul]; refl @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := (shiftr_eq_div_pow _ _).trans (nat.zero_div _) @[simp] lemma test_bit_zero (b n) : test_bit (bit b n) 0 = b := bodd_bit _ _ lemma test_bit_succ (m b n) : test_bit (bit b n) (succ m) = test_bit n m := have bodd (shiftr (shiftr (bit b n) 1) m) = bodd (shiftr n m), by dsimp [shiftr]; rw div2_bit, by rw [← shiftr_add, add_comm] at this; exact this lemma binary_rec_eq {C : nat → Sort u} {z : C 0} {f : ∀ b n, C n → C (bit b n)} (h : f ff 0 z = z) (b n) : binary_rec z f (bit b n) = f b n (binary_rec z f n) := begin rw [binary_rec], by_cases (bit b n = 0) with h', {simp [dif_pos h'], generalize : binary_rec._main._pack._proof_1 (bit b n) h' = e, revert e, have bf := bodd_bit b n, have n0 := div2_bit b n, rw h' at bf n0, simp at bf n0, rw [← bf, ← n0, binary_rec_zero], intros, exact h.symm }, {simp [dif_neg h'], generalize : binary_rec._main._pack._proof_2 (bit b n) = e, revert e, rw [bodd_bit, div2_bit], intros, refl} end lemma bitwise_bit_aux {f : bool → bool → bool} (h : f ff ff = ff) : @binary_rec (λ_, ℕ) (cond (f tt ff) (bit ff 0) 0) (λ b n _, bit (f ff b) (cond (f ff tt) n 0)) = λ (n : ℕ), cond (f ff tt) n 0 := begin apply funext, intro n, apply bit_cases_on n, intros b n, rw [binary_rec_eq], { cases b; try {rw h}; ginduction f ff tt with fft; simp [cond]; refl }, { rw [h, show cond (f ff tt) 0 0 = 0, by cases f ff tt; refl, show cond (f tt ff) (bit ff 0) 0 = 0, by cases f tt ff; refl]; refl } end @[simp] lemma bitwise_zero_left (f : bool → bool → bool) (n) : bitwise f 0 n = cond (f ff tt) n 0 := by unfold bitwise; rw [binary_rec_zero] @[simp] lemma bitwise_zero_right (f : bool → bool → bool) (h : f ff ff = ff) (m) : bitwise f m 0 = cond (f tt ff) m 0 := by unfold bitwise; apply bit_cases_on m; intros; rw [binary_rec_eq, binary_rec_zero]; exact bitwise_bit_aux h @[simp] lemma bitwise_zero (f : bool → bool → bool) : bitwise f 0 0 = 0 := by rw bitwise_zero_left; cases f ff tt; refl @[simp] lemma bitwise_bit {f : bool → bool → bool} (h : f ff ff = ff) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin unfold bitwise, rw [binary_rec_eq, binary_rec_eq], { ginduction f tt ff with ftf; dsimp [cond], rw [show f a ff = ff, by cases a; assumption], apply @congr_arg _ _ _ 0 (bit ff), tactic.swap, rw [show f a ff = a, by cases a; assumption], apply congr_arg (bit a), all_goals { apply bit_cases_on m, intros a m, rw [binary_rec_eq, binary_rec_zero], rw [← bitwise_bit_aux h, ftf], refl } }, { exact bitwise_bit_aux h } end theorem bitwise_swap {f : bool → bool → bool} (h : f ff ff = ff) : bitwise (function.swap f) = function.swap (bitwise f) := begin apply funext, intro m, apply funext, dsimp [function.swap], apply binary_rec _ (λ a m' IH, _) m; intro n, { rw [bitwise_zero_left, bitwise_zero_right], exact h }, apply bit_cases_on n; intros b n', rw [bitwise_bit, bitwise_bit, IH]; exact h end @[simp] lemma lor_bit : ∀ (a m b n), lor (bit a m) (bit b n) = bit (a || b) (lor m n) := bitwise_bit rfl @[simp] lemma land_bit : ∀ (a m b n), land (bit a m) (bit b n) = bit (a && b) (land m n) := bitwise_bit rfl @[simp] lemma ldiff_bit : ∀ (a m b n), ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := bitwise_bit rfl @[simp] lemma lxor_bit : ∀ (a m b n), lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := bitwise_bit rfl @[simp] lemma test_bit_bitwise {f : bool → bool → bool} (h : f ff ff = ff) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin revert m n; induction k with k IH; intros m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit h, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor : ∀ (m n k), test_bit (lor m n) k = test_bit m k || test_bit n k := test_bit_bitwise rfl @[simp] lemma test_bit_land : ∀ (m n k), test_bit (land m n) k = test_bit m k && test_bit n k := test_bit_bitwise rfl @[simp] lemma test_bit_ldiff : ∀ (m n k), test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := test_bit_bitwise rfl @[simp] lemma test_bit_lxor : ∀ (m n k), test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := test_bit_bitwise rfl end nat
fd4af76d189b272330c39a39e4eea44d7ad8ec50
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/set_theory/cardinal.lean
ce502c6e77c3ae555cdec8164778af9d41a33924
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
30,853
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.function set_theory.schroeder_bernstein open function lattice set local attribute [instance] classical.prop_decidable local attribute [instance, priority 0] nat.cast_coe universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.lattice.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ @[simp] theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} {s : set α} : mk s ≤ mk α := mk_le_of_injective subtype.val_injective @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_range_le {α β : Type u} {f : α → β} {s : set α} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range theorem mk_eq_of_injective {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨ set.embedding_of_subset h ⟩ end cardinal
57df6ad0739da496aa1bb6f464bd991c4fe5971f
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/hit/quotient.hlean
725b2670a3b6b190d3d2e97082bb3637e66e8c22
[ "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
2,374
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Quotients. This is a quotient without truncation for an arbitrary type-valued binary relation. See also .set_quotient -/ /- The hit quotient is primitive, declared in init.hit. The constructors are, given {A : Type} (R : A → A → Type), * class_of : A → quotient R (A implicit, R explicit) * eq_of_rel : Π{a a' : A}, R a a' → class_of a = class_of a' (R explicit) -/ open eq equiv sigma.ops namespace quotient variables {A : Type} {R : A → A → Type} protected definition elim {P : Type} (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : quotient R) : P := quotient.rec Pc (λa a' H, pathover_of_eq (Pp H)) x protected definition elim_on [reducible] {P : Type} (x : quotient R) (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') : P := quotient.elim Pc Pp x theorem elim_eq_of_rel {P : Type} (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') {a a' : A} (H : R a a') : ap (quotient.elim Pc Pp) (eq_of_rel R H) = Pp H := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (eq_of_rel R H)), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑quotient.elim,rec_eq_of_rel], end protected definition elim_type (Pc : A → Type) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a ≃ Pc a') : quotient R → Type := quotient.elim Pc (λa a' H, ua (Pp H)) protected definition elim_type_on [reducible] (x : quotient R) (Pc : A → Type) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a ≃ Pc a') : Type := quotient.elim_type Pc Pp x theorem elim_type_eq_of_rel (Pc : A → Type) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a ≃ Pc a') {a a' : A} (H : R a a') : transport (quotient.elim_type Pc Pp) (eq_of_rel R H) = to_fun (Pp H) := by rewrite [tr_eq_cast_ap_fn, ↑quotient.elim_type, elim_eq_of_rel];apply cast_ua_fn definition elim_type_uncurried (H : Σ(Pc : A → Type), Π⦃a a' : A⦄ (H : R a a'), Pc a ≃ Pc a') : quotient R → Type := quotient.elim_type H.1 H.2 end quotient attribute quotient.rec [recursor] attribute quotient.elim [unfold 6] [recursor 6] attribute quotient.elim_type [unfold 5] attribute quotient.elim_on [unfold 4] attribute quotient.elim_type_on [unfold 3]
32378ff62a0090af1b7086c33aa659fc7e4d6163
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/category_theory/Fintype.lean
2cb58f1d5de2a5da7ab77b6b18b66719c6394378
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,298
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Adam Topaz -/ import data.fintype.basic import data.fin import category_theory.concrete_category.bundled import category_theory.concrete_category import category_theory.full_subcategory import category_theory.skeletal /-! # The category of finite types. We define the category of finite types, denoted `Fintype` as (bundled) types with a `fintype` instance. We also define `Fintype.skeleton`, the standard skeleton of `Fintype` whose objects are `fin n` for `n : ℕ`. We prove that the obvious inclusion functor `Fintype.skeleton ⥤ Fintype` is an equivalence of categories in `Fintype.skeleton.equivalence`. We prove that `Fintype.skeleton` is a skeleton of `Fintype` in `Fintype.is_skeleton`. -/ open_locale classical open category_theory /-- The category of finite types. -/ @[derive has_coe_to_sort] def Fintype := bundled fintype namespace Fintype /-- Construct a bundled `Fintype` from the underlying type and typeclass. -/ def of (X : Type*) [fintype X] : Fintype := bundled.of X instance : inhabited Fintype := ⟨⟨pempty⟩⟩ instance {X : Fintype} : fintype X := X.2 instance : category Fintype := induced_category.category bundled.α /-- The fully faithful embedding of `Fintype` into the category of types. -/ @[derive [full, faithful], simps] def incl : Fintype ⥤ Type* := induced_functor _ instance : concrete_category Fintype := ⟨incl⟩ @[simp] lemma id_apply (X : Fintype) (x : X) : (𝟙 X : X → X) x = x := rfl @[simp] lemma comp_apply {X Y Z : Fintype} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := rfl universe u /-- The "standard" skeleton for `Fintype`. This is the full subcategory of `Fintype` spanned by objects of the form `ulift (fin n)` for `n : ℕ`. We parameterize the objects of `Fintype.skeleton` directly as `ulift ℕ`, as the type `ulift (fin m) ≃ ulift (fin n)` is nonempty if and only if `n = m`. Specifying universes, `skeleton : Type u` is a small skeletal category equivalent to `Fintype.{u}`. -/ def skeleton : Type u := ulift ℕ namespace skeleton /-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/ def mk : ℕ → skeleton := ulift.up instance : inhabited skeleton := ⟨mk 0⟩ /-- Given any object of `Fintype.skeleton`, this returns the associated natural number. -/ def len : skeleton → ℕ := ulift.down @[ext] lemma ext (X Y : skeleton) : X.len = Y.len → X = Y := ulift.ext _ _ instance : small_category skeleton.{u} := { hom := λ X Y, ulift.{u} (fin X.len) → ulift.{u} (fin Y.len), id := λ _, id, comp := λ _ _ _ f g, g ∘ f } lemma is_skeletal : skeletal skeleton.{u} := λ X Y ⟨h⟩, ext _ _ $ fin.equiv_iff_eq.mp $ nonempty.intro $ { to_fun := λ x, (h.hom ⟨x⟩).down, inv_fun := λ x, (h.inv ⟨x⟩).down, left_inv := begin intro a, change ulift.down _ = _, rw ulift.up_down, change ((h.hom ≫ h.inv) _).down = _, simpa, end, right_inv := begin intro a, change ulift.down _ = _, rw ulift.up_down, change ((h.inv ≫ h.hom) _).down = _, simpa, end } /-- The canonical fully faithful embedding of `Fintype.skeleton` into `Fintype`. -/ def incl : skeleton.{u} ⥤ Fintype.{u} := { obj := λ X, Fintype.of (ulift (fin X.len)), map := λ _ _ f, f } instance : full incl := { preimage := λ _ _ f, f } instance : faithful incl := {} instance : ess_surj incl := ess_surj.mk $ λ X, let F := fintype.equiv_fin X in ⟨mk (fintype.card X), nonempty.intro { hom := F.symm ∘ ulift.down, inv := ulift.up ∘ F }⟩ noncomputable instance : is_equivalence incl := equivalence.of_fully_faithfully_ess_surj _ /-- The equivalence between `Fintype.skeleton` and `Fintype`. -/ noncomputable def equivalence : skeleton ≌ Fintype := incl.as_equivalence @[simp] lemma incl_mk_nat_card (n : ℕ) : fintype.card (incl.obj (mk n)) = n := begin convert finset.card_fin n, apply fintype.of_equiv_card, end end skeleton /-- `Fintype.skeleton` is a skeleton of `Fintype`. -/ noncomputable def is_skeleton : is_skeleton_of Fintype skeleton skeleton.incl := { skel := skeleton.is_skeletal, eqv := by apply_instance } end Fintype
13b36f1019efc9707690664dce08b32642accd38
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/ext.lean
b876a46d5e8bce93328505ebe49a78ea17f1929c
[ "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,723
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.ext import tactic.solve_by_elim import data.stream.init import data.finset.basic import tactic.rcases section ext_trace_test setup_tactic_parser namespace tactic namespace interactive meta def ext_trace_test (patts : parse rcases_patt_parse_hi*) (fuel : parse (tk ":" *> small_nat)?) (tgt_trace : string) : tactic unit := do ⟨_, σ⟩ ← state_t.run (ext_core {}) ⟨patts, [], fuel⟩, guard $ ", ".intercalate σ.trace_msg = tgt_trace end interactive end tactic end ext_trace_test example (α β γ : Type) (f g : α × β → γ) (H : ∀ a : α, ∀ b : β, f (a,b) = g (a,b)) : f = g := begin ext_trace_test ⟨a,b⟩ "apply funext, rintro ⟨a, b⟩", apply H end example : subsingleton unit := begin split, intros, ext end example (x y : ℕ) : true := begin have : x = y, { ext <|> admit }, have : x = y, { ext i <|> admit }, have : x = y, { ext : 1 <|> admit }, trivial end example (X Y : ℕ × ℕ) (h : X.1 = Y.1) (h : X.2 = Y.2) : X = Y := begin ext; assumption end example (X Y : (ℕ → ℕ) × ℕ) (h : ∀ i, X.1 i = Y.1 i) (h : X.2 = Y.2) : X = Y := begin ext x; solve_by_elim, end example (X Y : ℕ → ℕ × ℕ) (h : ∀ i, X i = Y i) : true := begin have : X = Y, { ext i : 1, guard_target X i = Y i, admit }, have : X = Y, { ext i, guard_target (X i).fst = (Y i).fst, admit, guard_target (X i).snd = (Y i).snd, admit, }, have : X = Y, { ext : 1, guard_target X x = Y x, admit }, trivial, end example (s₀ s₁ : set ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, simp * } example (s₀ s₁ : stream ℕ) (h : s₁ = s₀) : s₀ = s₁ := by { ext1, guard_target s₀.nth n = s₁.nth n, simp * } example (s₀ s₁ : ℤ → set (ℕ × ℕ)) (h : ∀ i a b, (a,b) ∈ s₀ i ↔ (a,b) ∈ s₁ i) : s₀ = s₁ := begin ext ((i) ⟨a,b⟩), apply h end example (s₀ s₁ : ℤ → set (ℕ × ℕ)) (h : ∀ i a b, (a,b) ∈ s₀ i ↔ (a,b) ∈ s₁ i) : s₀ = s₁ := begin ext_trace_test i ⟨a,b⟩ "apply funext, rintro i, apply set.ext, rintro ⟨a, b⟩", apply h end /- extensionality -/ example : true := begin have : ∀ (s₀ s₁ : set ℤ), s₀ = s₁, { intros, ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, admit }, have : ∀ (s₀ s₁ : finset ℕ), s₀ = s₁, { intros, ext1, guard_target a ∈ s₀ ↔ a ∈ s₁, admit }, have : ∀ (s₀ s₁ : multiset ℕ), s₀ = s₁, { intros, ext1, guard_target multiset.count a s₀ = multiset.count a s₁, admit }, have : ∀ (s₀ s₁ : list ℕ), s₀ = s₁, { intros, ext1, guard_target list.nth s₀ n = list.nth s₁ n, admit }, have : ∀ (s₀ s₁ : stream ℕ), s₀ = s₁, { intros, ext1, guard_target s₀.nth n = s₁.nth n, admit }, have : ∀ n (s₀ s₁ : array n ℕ), s₀ = s₁, { intros, ext1, guard_target array.read s₀ i = array.read s₁ i, admit }, trivial end structure dependent_fields := (a : bool) (v : if a then ℕ else ℤ) @[ext] lemma df.ext (s t : dependent_fields) (h : s.a = t.a) (w : (@eq.rec _ s.a (λ b, if b then ℕ else ℤ) s.v t.a h) = t.v) : s = t := begin cases s, cases t, dsimp at *, congr, exact h, subst h, simp, simp at w, exact w, end example (s : dependent_fields) : s = s := begin tactic.ext1 [] {tactic.apply_cfg . new_goals := tactic.new_goals.all}, guard_target s.a = s.a, refl, refl, end @[ext] structure dumb (V : Type) := (val : V)
9e264fe37bc6b2f939fdbbc8bdb07be2be6b5e27
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/nat_bug2.lean
f5db9e93e646b65d9ce3a989e6842ff8bbe1407f
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
698
lean
import standard using num eq_proofs inductive nat : Type := zero : nat, succ : nat → nat namespace nat definition plus (x y : nat) : nat := nat.rec x (λn r, succ r) y definition to_nat [coercion] (n : num) : nat := num.rec zero (λn, pos_num.rec (succ zero) (λn r, plus r (plus r (succ zero))) (λn r, plus r r) n) n definition add (x y : nat) : nat := plus x y constant le : nat → nat → Prop infixl `+` := add infix `≤` := le axiom add_one (n:nat) : n + (succ zero) = succ n axiom add_le_right {n m : nat} (H : n ≤ m) (k : nat) : n + k ≤ m + k theorem succ_le {n m : nat} (H : n ≤ m) : succ n ≤ succ m := add_one m ▸ add_one n ▸ add_le_right H 1 end nat end experiment
835133b76a4c0906a025330130fcee7ec1a6cfa1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1026.lean
c9b15c96d631e847cf0491af4f965542b2574a6d
[ "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
235
lean
def foo (n : Nat) : Nat := if n = 0 then 0 else let x := n - 1 have := match () with | _ => trivial foo x termination_by _ n => n decreasing_by sorry theorem ex : foo 0 = 0 := by unfold foo sorry #check foo._unfold
c6a32a5642a99960729ad1c0e768c85fc39e56d6
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/complex/exponential.lean
ebef798d6565da0edcd39b34216dd3fe4f667d0f
[ "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
61,534
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose.sum import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators nat section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, simp only [sub_eq_add_neg] at hi, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_sum (abv x) m := rfl, simp only [this, geom_sum_eq hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := by rw [sum_sigma', sum_sigma']; exact sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), abv (a n)) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / m!)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw conj.map_sum, refine sum_congr rfl (λ n hn, _), rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div, conj_bit0, conj.map_one] end @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, pow_two, pow_two] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_square], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_square], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma tanh_mul_I : tanh (x * I) = tan x * I := by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan] lemma cos_mul_I : cos (x * I) = cosh x := by rw ← cosh_mul_I; ring_nf; simp lemma sin_mul_I : sin (x * I) = sinh x * I := have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring_nf, simp }, by simpa only [neg_mul_eq_neg_mul_symm, div_I, neg_neg] using cancel_factors.cancel_factors_eq_div h I_ne_zero lemma tan_mul_I : tan (x * I) = tanh x * I := by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I := by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc] lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I := by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I := by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc] lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I := by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div] lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel] lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx, by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] } lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, pow_two], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_square'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] } lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] } /-- De Moivre's formula -/ theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end lemma tan_eq_sin_div_cos : tan x = sin x / cos x := by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos] lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simp @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, sin_sq_le_one] lemma abs_cos_le_one : abs' (cos x) ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, cos_sq_le_one] lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw ← of_real_inj; simp [cos_two_mul'] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have complex.cos x ≠ 0, from mt (congr_arg re) hx, of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (sqrt (1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sqr hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp [cosh_add_sinh] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw ← of_real_inj; simp [sinh_add_cosh] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_square] lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_square] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) @[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone @[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt @[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ / (n! * n) := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_sum_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev', h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw ← sub_eq_add_neg, show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : begin refine congr_arg abs (sum_congr rfl (λ m hm, _)), rw [mem_filter, mem_range] at hm, rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel' hm.2] end ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.factorial_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : abs' x ≤ 1) {n : ℕ} (hn : 0 < n) : abs' (exp x - ∑ m in range n, x ^ m / m!) ≤ abs' x ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv, mul_inv']; ac_refl theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : abs' x ≤ 1) : abs' (exp x - exp_near m x 0) ≤ abs' x ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : abs' (1 + x / m * a₂ - a₁) ≤ b₁ - abs' x / m * b₂) (h : abs' (exp x - exp_near m x a₂) ≤ abs' x ^ m / m! * b₂) : abs' (exp x - exp_near n x a₁) ≤ abs' x ^ n / n! * b₁ := begin refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv'], ac_refl }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs' x ≤ 1) (e : abs' (1 - a) ≤ b - abs' x / rm * ((rm+1)/rm)) : abs' (exp x - exp_near n x a) ≤ abs' x ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : abs' (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs' 1 ^ m / m! * (b₁ * rm)) : abs' (exp 1 - exp_near n 1 a₁) ≤ abs' 1 ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : abs' (exp x - exp_near 0 x a) ≤ abs' x ^ 0 / 0! * b) : abs' (exp x - a) ≤ b := by simpa using h lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
4e2ebf62d933bfc1c88469e9973d28353edef2b1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/fintype/perm.lean
c3609830054bd67f8dc0bfb6f83484bde7c89c53
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,478
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.card import group_theory.perm.basic /-! # fintype instances for `equiv` and `perm` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Main declarations: * `perms_of_finset s`: The finset of permutations of the finset `s`. -/ open function open_locale nat universes u v variables {α β γ : Type*} open finset function list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] /-- Given a list, produce a list of all permutations of its elements. -/ def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length! | [] := rfl | (a :: l) := begin rw [length_cons, nat.factorial_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) : f ∈ perms_of_list l := begin induction l with a l IH generalizing f h, { exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) }, by_cases hfa : f a = a, { refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))), rintro rfl, exact hx hfa }, have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa, have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, { intros x hx, have hxa : x ≠ a, { rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] }, refine list.mem_of_ne_of_mem hxa (h x (λ h, _)), simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx; split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] }, suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f, { simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] }, refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩), { exact mem_of_ne_of_mem hfa (h _ hfa') }, { rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ←perm.one_def, one_mul] } end lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a :: l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; [exact ne.symm hxy, exact ne.symm hxa, exact hx]) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a :: l) hl := have hl' : l.nodup, from hl.of_cons, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, hln'.map $ λ _ _, mul_left_cancel, λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [←hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ /-- Given a finset, produce the finset of all permutations of its elements. -/ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card! := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l /-- The collection of permutations of a fintype is a fintype. -/ def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α)! := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
631af59aa1b68d6499c2dac43e40b77e99657c6b
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/meta/expr.lean
20b49e7e670cc82ea896253fda77b281d1c1cc89
[ "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
4,536
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis Additional non-tactic operations on expr and related types -/ namespace name meta def deinternalize_field : name → name | (name.mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) -- Pops the top `n` prefixes from the given name. meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest def from_components : list string → name := from_components_aux name.anonymous -- `name`s can contain numeral pieces, which are not legal names -- when typed/passed directly to the parser. We turn an arbitrary -- name into a legal identifier name. meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n end name namespace level meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level namespace expr open tactic protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat meta def is_meta_var : expr → bool | (mvar _ _ _) := tt | e := ff meta def is_sort : expr → bool | (sort _) := tt | e := ff meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es) meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr namespace environment meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) meta def is_structure_like (env : environment) (n : name) : option (nat × name) := do guardb (env.is_inductive n), d ← (env.get n).to_option, [intro] ← pure (env.constructors_of n) | none, guard (env.inductive_num_indices n = 0), some (env.inductive_num_params n, intro) meta def is_structure (env : environment) (n : name) : bool := option.is_some $ do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, expr.pi x _ _ _ ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, env.is_projection (n ++ x.deinternalize_field) end environment
2b1a123a5806770b7e45adb30120bce6ac4b8bc4
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/group/conj.lean
c032c7661002f7a4bb43280fed054ab958ee2ac9
[ "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
1,930
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Chris Hughes, Michael Howes -/ import tactic.basic algebra.group.hom /-! # Conjugacy of group elements -/ universes u v variables {α : Type u} {β : Type v} variables [group α] [group β] def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b @[refl] lemma is_conj_refl (a : α) : is_conj a a := ⟨1, by rw [one_mul, one_inv, mul_one]⟩ @[symm] lemma is_conj_symm {a b : α} : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩ @[trans] lemma is_conj_trans {a b c : α} : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩ @[simp] lemma is_conj_one_right {a : α} : is_conj 1 a ↔ a = 1 := ⟨by simp [is_conj, is_conj_refl] {contextual := tt}, by simp [is_conj_refl] {contextual := tt}⟩ @[simp] lemma is_conj_one_left {a : α} : is_conj a 1 ↔ a = 1 := calc is_conj a 1 ↔ is_conj 1 a : ⟨is_conj_symm, is_conj_symm⟩ ... ↔ a = 1 : is_conj_one_right @[simp] lemma conj_inv {a b : α} : (b * a * b⁻¹)⁻¹ = b * a⁻¹ * b⁻¹ := begin rw [mul_inv_rev _ b⁻¹, mul_inv_rev b _, inv_inv, mul_assoc], end @[simp] lemma conj_mul {a b c : α} : (b * a * b⁻¹) * (b * c * b⁻¹) = b * (a * c) * b⁻¹ := begin assoc_rw inv_mul_cancel_right, repeat {rw mul_assoc}, end @[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩ protected lemma monoid_hom.map_is_conj (f : α →* β) {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨f c, by rw [← f.map_mul, ← f.map_inv, ← f.map_mul, hc]⟩
930c447f61fd4ed0a561d124885d79e2311e9609
e4e5bde6f14c01a8a34267a9d7bb45e137735696
/src/counterexamples/spaces/finite_discrete.lean
c30f201a12973ac96a503c30568c2e976ce03136
[]
no_license
jamesdabbs/proofs
fb5dab6f3c4f3f5f952fca033ec649888ae787c6
00baf355b08e7aec00de34208e1b2cb4a8d7b701
refs/heads/master
1,645,645,735,797
1,569,559,636,000
1,569,559,636,000
211,238,170
0
0
null
null
null
null
UTF-8
Lean
false
false
3,811
lean
/- Reading list: - https://leanprover.github.io/logic_and_proof/index.html - Especially https://leanprover.github.io/logic_and_proof/sets.html -/ prelude import topology.order topology.subset_properties import data.set data.set.basic import set_theory.zfc open set open topological_space universes u variables {α β: Type u} [topological_space α] {A B C : set α} section discrete def is_discrete (s : set α) : Prop := ∀ t ⊆ s, is_open t class discrete_space (α : Type u) [topological_space α] : Prop := (is_discrete_univ : is_discrete (univ : set α)) lemma comp_intersect : A ∩ (B \ A) = ∅ := begin apply set.eq_empty_of_subset_empty, assume x, assume h : x ∈ A ∩ (B \ A), have a : x ∈ A, from and.left h, have : x ∈ B \ A, from and.right h, have c : x ∉ A, from and.right this, show x ∈ ∅, from absurd a c end theorem is_totally_separated_of_is_discrete {s : set α} (H : is_discrete s) : is_totally_separated s := begin rewrite is_totally_separated, intros, fapply exists.intro, exact singleton(x), fapply exists.intro, exact (s \ {x}), split, -- {x} is open apply H, rewrite set.singleton_subset_iff, assumption, split, -- s \ {x} is open apply H, simp, split, -- x ∈ {x} simp, split, -- y ∈ s \ {x} simp, split, assumption, show ¬y = x, finish, split, show s ⊆ {x} ∪ s \ {x}, intros, rewrite set.union_diff_cancel, show {x} ⊆ s, rw set.singleton_subset_iff, assumption, show {x} ∩ (s \ {x}) = ∅, exact comp_intersect end instance discrete_space.totally_separated_space (α : Type u) [topological_space α] [discrete_space α] : totally_separated_space α := ⟨is_totally_separated_of_is_discrete $ discrete_space.is_discrete_univ _⟩ /- TODO: * is_totally_separated A -> |A| > 1 -> ¬ is_connected A * is_discrete -> is_compact -/ end discrete section indiscrete def is_indiscrete (s : set α) : Prop := is_open s -> s = ∅ ∨ s = univ class indiscrete_space (α : Type u) [topological_space α] : Prop := (is_indiscrete_univ : is_indiscrete (univ : set α)) variable (s : set α) #check is_indiscrete s lemma nontrivial_nonempty [indiscrete_space α] (s : set α) (o : is_open s) (i : ∃ x, x ∈ s) : s = univ := begin cases i with x xs, have : s = ∅ ∨ s = univ, from sorry, cases this with empty full, have : x ∉ ∅, from set.not_mem_empty x, rewrite empty at xs, contradiction, assumption end instance indiscrete_space.irreducible_space (α : Type u) [topological_space α] [indiscrete_space α] : irreducible_space α := ⟨ begin rewrite is_irreducible, assume u v : set α, assume ou : is_open u, assume ov : is_open v, assume : ∃ x, x ∈ univ ∩ u, cases this with x iu, have : x ∈ u, from iu.right, have au : u = univ, from nontrivial_nonempty u ou ⟨x, this⟩, rewrite au, assume : ∃ y, y ∈ univ ∩ v, cases this with y iv, have : y ∈ v, from iv.right, have av : v = univ, from nontrivial_nonempty v ov ⟨y, this⟩, rewrite av, exact ⟨x, by simp⟩ end ⟩ theorem is_compact_of_is_indiscrete (H : is_indiscrete (univ : set α)) : compact (univ : set α) := begin rw compact_iff_finite_subcover, intros, suffices : ∃ x ∈ univ, sorry, cases this with x xu, have : x ∈ ⋃₀ c, from sorry, have : ∃ t ∈ c, x ∈ t, from sorry, cases this with t tu, have : t = univ, from sorry, exact ⟨singleton(t), sorry⟩ end instance indiscrete_space.compact_space (α : Type u) [topological_space α] [indiscrete_space α] : compact_space α := ⟨is_compact_of_is_indiscrete $ indiscrete_space.is_indiscrete_univ _⟩ end indiscrete
bbb3c4ea452e1574342adc6874f05062d57e9c89
47181b4ef986292573c77e09fcb116584d37ea8a
/src/abvs_equiv.lean
5557b56a5158e9f94fe6bf6c2d4a6719876eacb3
[ "MIT" ]
permissive
RaitoBezarius/berkovich-spaces
87662a2bdb0ac0beed26e3338b221e3f12107b78
0a49f75a599bcb20333ec86b301f84411f04f7cf
refs/heads/main
1,690,520,666,912
1,629,328,012,000
1,629,328,012,000
332,238,095
4
0
MIT
1,629,312,085,000
1,611,414,506,000
Lean
UTF-8
Lean
false
false
2,267
lean
import number_theory.padics.padic_norm import data.real.cau_seq import analysis.special_functions.exp_log import analysis.special_functions.pow import data.nat.prime import data.nat.basic import tactic.apply import tactic.linarith import topology.metric_space.basic open is_absolute_value variables (α: ℝ) def abvs_equiv {β} [ring β] (abv: β → ℝ) (abv': β → ℝ) [is_absolute_value abv] [is_absolute_value abv'] := ∃ α: ℝ, 0 < α ∧ (λ x: β, (abv x) ^ α) = abv' theorem abvs_equiv_reflexive {β} [ring β]: ∀ (abv: β → ℝ) [is_abv: is_absolute_value abv], @abvs_equiv _ _ abv abv is_abv is_abv := begin intros abv is_abv, use [1, by linarith], simp, end theorem abvs_equiv_symmetric {β} [ring β]: ∀ (abv abv': β → ℝ) [abv_abv: is_absolute_value abv] [abv'_abv: is_absolute_value abv'], @abvs_equiv _ _ abv abv' abv_abv abv'_abv → @abvs_equiv _ _ abv' abv abv'_abv abv_abv := begin intros abv abv' abv_abv abv'_abv p, rcases p with ⟨ α, zero_lt_α, hα ⟩, use [α⁻¹, by simp [zero_lt_α]], ext x, have abvx_nonneg: 0 ≤ abv x, from @abv_nonneg _ _ _ _ abv abv_abv x, symmetry, calc abv x = abv x ^ (1: ℝ) : by rw real.rpow_one ... = abv x ^ (α * α⁻¹) : by { simp [(ne.symm ∘ ne_of_lt) zero_lt_α], } ... = (abv x ^ α) ^ (α⁻¹) : by { rw real.rpow_mul abvx_nonneg, } ... = ((λ x, abv x ^ α) x) ^ (α⁻¹) : by simp ... = (abv' x) ^ (α⁻¹) : by rw hα, end theorem abvs_equiv_transitive {β} [ring β]: ∀ (abv abv' abv'': β → ℝ) [abv_abv: is_absolute_value abv] [abv'_abv: is_absolute_value abv'] [abv''_abv: is_absolute_value abv''], @abvs_equiv _ _ abv abv' abv_abv abv'_abv → @abvs_equiv _ _ abv' abv'' abv'_abv abv''_abv → @abvs_equiv _ _ abv abv'' abv_abv abv''_abv := begin intros abv abv' abv'' abv_abv abv'_abv abv''_abv abv_equiv_abv' abv'_equiv_abv'', rcases abv_equiv_abv' with ⟨ α, zero_lt_α, hα ⟩, rcases abv'_equiv_abv'' with ⟨ γ, zero_lt_γ, hγ ⟩, use [α * γ, by simp [zero_lt_α, zero_lt_γ]], ext x, have abvx_nonneg: 0 ≤ abv x, from @abv_nonneg _ _ _ _ abv abv_abv x, rw real.rpow_mul abvx_nonneg, rw [← hγ, ← hα], end
c8ce71aa1cbb9469dcf4bb043b86e919b84dd041
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/tools/super/splitting.lean
f30999fac1e3c84909abcbcba708ef811145cf83
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,701
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .prover_state open monad expr list tactic namespace super private meta def find_components : list expr → list (list (expr × ℕ)) → list (list (expr × ℕ)) | (e::es) comps := let (contain_e, do_not_contain_e) := partition (λc : list (expr × ℕ), c^.exists_ $ λf, (abstract_local f.1 e^.local_uniq_name)^.has_var) comps in find_components es $ list.join contain_e :: do_not_contain_e | _ comps := comps meta def get_components (hs : list expr) : list (list expr) := (find_components hs (hs^.zip_with_index^.map $ λh, [h]))^.map $ λc, (sort_on (λh : expr × ℕ, h.2) c)^.map $ λh, h.1 meta def extract_assertions : clause → prover (clause × list expr) | c := if c^.num_lits = 0 then return (c, []) else if c^.num_quants ≠ 0 then do qf ← c^.open_constn c^.num_quants, qf_wo_as ← extract_assertions qf.1, return (qf_wo_as.1^.close_constn qf.2, qf_wo_as.2) else do hd ← return $ c^.get_lit 0, hyp_opt ← get_sat_hyp_core hd^.formula hd^.is_neg, match hyp_opt with | some h := do wo_as ← extract_assertions (c^.inst h), return (wo_as.1, h :: wo_as.2) | _ := do op ← c^.open_const, op_wo_as ← extract_assertions op.1, return (op_wo_as.1^.close_const op.2, op_wo_as.2) end meta def mk_splitting_clause' (empty_clause : clause) : list (list expr) → tactic (list expr × expr) | [] := return ([], empty_clause^.proof) | ([p] :: comps) := do p' ← mk_splitting_clause' comps, return (p::p'.1, p'.2) | (comp :: comps) := do (hs, p') ← mk_splitting_clause' comps, hnc ← mk_local_def `hnc (imp (pis comp empty_clause^.local_false) empty_clause^.local_false), p'' ← return $ app hnc (lambdas comp p'), return (hnc::hs, p'') meta def mk_splitting_clause (empty_clause : clause) (comps : list (list expr)) : tactic clause := do (hs, p) ← mk_splitting_clause' empty_clause comps, return $ { empty_clause with proof := p }^.close_constn hs @[super.inf] meta def splitting_inf : inf_decl := inf_decl.mk 30 $ take given, do lf ← flip monad.lift state_t.read $ λst, st^.local_false, op ← given^.c^.open_constn given^.c^.num_binders, if list.bor (given^.c^.get_lits^.map $ λl, (is_local_not lf l^.formula)^.is_some) then return () else let comps := get_components op.2 in if comps^.length < 2 then return () else do splitting_clause ← mk_splitting_clause op.1 comps, ass ← collect_ass_hyps splitting_clause, add_sat_clause (splitting_clause^.close_constn ass) given^.sc^.sched_default, remove_redundant given^.id [] end super
30c91f0d2dd723b43e9cc83507ad389752cc7158
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/simp_command.lean
a929ef0c48e0c4de032886f63b491656bbbb8af8
[ "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
2,483
lean
import tactic.simp_command import analysis.special_functions.trigonometric /- Turn off trace messages only if the statements are simplified to true: -/ set_option trace.silence_simp_if_true true /-! Tests for the #simp command. -/ #simp 5 - 5 = 0 section arith def f (x : ℤ) := x + (x - x) #simp [f] f 3 = 3 mk_simp_attribute test "" attribute [test] f -- You can use the optional `:` to separate -- the simp lemmas and attributes from the expression to simplify. #simp with test : (f 3) = 3 attribute [simp] f #simp f 3 = 3 #simp only [f, eq_self_iff_true] f 3 = 3 + (3 - 3) local attribute [simp] sub_self variables (x : ℤ) #simp with test : (f x) = x #simp f x = x #simp only [f, eq_self_iff_true] f x = x + (x - x) #simp only [f, sub_self, eq_self_iff_true] f x = x + 0 end arith section real open real #simp [exp_ne_zero] : (λ x, deriv (λ x, (sin x) / (exp x)) x) = (λ (x : ℝ), (cos x * exp x - sin x * exp x) / exp x ^ 2) variables (x : ℝ) -- You can refer to local variables, rather than having to use lambdas. open real #simp [exp_ne_zero] : deriv (λ x, (sin x) / (exp x)) x = (cos x * exp x - sin x * exp x) / exp x ^ 2 end real section func_hyp variables (f : ℕ → ℕ) (hf : f 3 = 0) (hg : 9 = 55) #simp only [hg, eq_self_iff_true] : 9 = 55 #simp only [hf, add_zero, eq_self_iff_true] : 1 + f 3 = 1 end func_hyp namespace inst class magic_data (n : ℕ) := (dummy : ℕ) axiom spell (t : ℤ) (k : ℕ) [magic_data k] : (k = 3) ↔ (k = 77) variables (t : ℤ) (k : ℕ) [magic_data k] [ii : magic_data k] (h : k = 77 ↔ k = 8) -- We want to be able to emulate this: example : (t = t) ∧ (h = h) ∧ ((k = 3) ↔ (k = 8)) := begin simp [spell t, h] end -- Check that we can: #simp [spell t, h, ii] : (k = 3) ↔ (k = 8) #simp [spell t, h] : (k = 3) ↔ (k = 8) theorem spell' (k : ℕ) [magic_data k] : (k = 3) ↔ (k = 77) := spell 1 k attribute [simp] spell' #simp [h, ii] : (k = 3) ↔ (k = 8) #simp [h] : (k = 3) ↔ (k = 8) -- Check that the `#simp` resolver can handle depth > 2 recursive inclusions class doubly_magic_data (n : ℕ) [magic_data n] := (dummy : ℕ) variables (n : ℕ) [magic_data n] [doubly_magic_data n] (h₂ : n = 77 ↔ n = 8) @[simp] axiom spell2 (n : ℕ) [magic_data n] [doubly_magic_data n] : (n = 4) ↔ (n = 77) example : (h₂ = h₂) ∧ ((n = 4) ↔ (n = 8)) := begin simp [h₂], end #simp [h₂, ii] : (n = 4) ↔ (n = 8) #simp [h₂] : (n = 4) ↔ (n = 8) end inst
24e851fa287e339b5fe36777a4263d6c5d18bd66
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/measure_theory/probability_mass_function.lean
11e5a5321c22085aab0ead45080dc0f0e81b21cc
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
4,788
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Probability mass function -- discrete probability measures -/ import topology.instances.nnreal topology.instances.ennreal topology.algebra.infinite_sum noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} local attribute [instance] classical.prop_decidable /-- Probability mass functions, i.e. discrete probability measures -/ def {u} pmf (α : Type u) : Type u := { f : α → nnreal // is_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) := ⟨λp, α → nnreal, λp a, p.1 a⟩ @[extensionality] protected lemma ext : ∀{p q : pmf α}, (∀a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma is_sum_coe_one (p : pmf α) : is_sum p 1 := p.2 lemma has_sum_coe (p : pmf α) : has_sum p := has_sum_spec p.is_sum_coe_one @[simp] lemma tsum_coe (p : pmf α) : (∑a, p a) = 1 := tsum_eq_is_sum p.is_sum_coe_one def support (p : pmf α) : set α := {a | p.1 a ≠ 0} def pure (a : α) : pmf α := ⟨λa', if a' = a then 1 else 0, is_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := is_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (is_sum_ite_eq a (p a)) p.2 protected lemma bind.has_sum (p : pmf α) (f : α → pmf β) (b : β) : has_sum (λa:α, p a * f a b) := begin refine nnreal.has_sum_of_le (assume a, _) p.has_sum_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λb, (∑a, p a * f a b), begin simp [ennreal.is_sum_coe.symm, (ennreal.tsum_coe (bind.has_sum p f _)).symm], rw [is_sum_iff_of_has_sum ennreal.has_sum, ennreal.tsum_comm], simp [ennreal.mul_tsum, (ennreal.tsum_coe (f _).has_sum_coe), ennreal.tsum_coe p.has_sum_coe] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = (∑a, p a * f a b) := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ennreal) = (∑a, p a * f a b) := eq.trans (ennreal.tsum_coe $ bind.has_sum p f b).symm $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λa, (f a).bind g) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.mul_tsum.symm, ennreal.tsum_mul.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λa, q.bind (f a)) = q.bind (λb, p.bind (λa, f a b)) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.mul_tsum.symm, ennreal.tsum_mul.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λm, p.bind $ λa, pure (m a)) def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λa, s.count a / s.card, have s.to_finset.sum (λa, (s.count a : ℝ) / s.card) = 1, by simp [div_eq_inv_mul, finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs], have s.to_finset.sum (λa, (s.count a : nnreal) / s.card) = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.sum_coe]; simp, begin rw ← this, apply is_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ def of_fintype [fintype α] (f : α → nnreal) (h : finset.univ.sum f = 1) : pmf α := ⟨f, h ▸ is_sum_sum_of_ne_finset_zero (by simp)⟩ def bernoulli (p : nnreal) (h : p ≤ 1) : pmf bool := of_fintype (λb, cond b p (1 - p)) (nnreal.eq $ by simp [h]) end pmf
a36eab8e817124cd064b23f406cb5dea0b430050
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Syntax.lean
bfee7ec123dea99e797f8c84fbe5c69dd24db236
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,326
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Data.Name import Lean.Data.Format namespace Lean def SourceInfo.updateTrailing (trailing : Substring) : SourceInfo → SourceInfo | SourceInfo.original leading pos _ => SourceInfo.original leading pos trailing | info => info /- Syntax AST -/ def Syntax.isMissing : Syntax → Bool | Syntax.missing => true | _ => false inductive IsNode : Syntax → Prop where | mk (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node kind args) def SyntaxNode : Type := {s : Syntax // IsNode s } def unreachIsNodeMissing {β} (h : IsNode Syntax.missing) : β := False.elim (nomatch h) def unreachIsNodeAtom {β} {info val} (h : IsNode (Syntax.atom info val)) : β := False.elim (nomatch h) def unreachIsNodeIdent {β info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : β := False.elim (nomatch h) namespace SyntaxNode @[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind := match n with | ⟨Syntax.node k args, _⟩ => k | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom .., h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident .., h⟩ => unreachIsNodeIdent h @[inline] def withArgs {β} (n : SyntaxNode) (fn : Array Syntax → β) : β := match n with | ⟨Syntax.node _ args, _⟩ => fn args | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h @[inline] def getNumArgs (n : SyntaxNode) : Nat := withArgs n $ fun args => args.size @[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax := withArgs n $ fun args => args.get! i @[inline] def getArgs (n : SyntaxNode) : Array Syntax := withArgs n $ fun args => args @[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax := match n with | ⟨Syntax.node kind args, _⟩ => Syntax.node kind (fn args) | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h end SyntaxNode namespace Syntax def getAtomVal! : Syntax → String | atom _ val => val | _ => panic! "getAtomVal!: not an atom" def setAtomVal : Syntax → String → Syntax | atom info _, v => (atom info v) | stx, _ => stx @[inline] def ifNode {β} (stx : Syntax) (hyes : SyntaxNode → β) (hno : Unit → β) : β := match stx with | Syntax.node k args => hyes ⟨Syntax.node k args, IsNode.mk k args⟩ | _ => hno () @[inline] def ifNodeKind {β} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode → β) (hno : Unit → β) : β := match stx with | Syntax.node k args => if k == kind then hyes ⟨Syntax.node k args, IsNode.mk k args⟩ else hno () | _ => hno () def asNode : Syntax → SyntaxNode | Syntax.node kind args => ⟨Syntax.node kind args, IsNode.mk kind args⟩ | _ => ⟨Syntax.node nullKind #[], IsNode.mk nullKind #[]⟩ def getIdAt (stx : Syntax) (i : Nat) : Name := (stx.getArg i).getId @[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax → Array Syntax) : Syntax := match stx with | node k args => node k (fn args) | stx => stx @[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax → Syntax) : Syntax := match stx with | node k args => node k (args.modify i fn) | stx => stx @[specialize] partial def replaceM {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m (Syntax) | stx@(node kind args) => do match (← fn stx) with | some stx => return stx | none => return node kind (← args.mapM (replaceM fn)) | stx => do let o ← fn stx return o.getD stx @[specialize] partial def rewriteBottomUpM {m : Type → Type} [Monad m] (fn : Syntax → m (Syntax)) : Syntax → m (Syntax) | node kind args => do let args ← args.mapM (rewriteBottomUpM fn) fn (node kind args) | stx => fn stx @[inline] def rewriteBottomUp (fn : Syntax → Syntax) (stx : Syntax) : Syntax := Id.run $ stx.rewriteBottomUpM fn private def updateInfo : SourceInfo → String.Pos → String.Pos → SourceInfo | SourceInfo.original lead pos trail, leadStart, trailStop => SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } | info, _, _ => info private def chooseNiceTrailStop (trail : Substring) : String.Pos := trail.startPos + trail.posOf '\n' /- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token, or the beginning of the String. -/ @[inline] private def updateLeadingAux : Syntax → StateM String.Pos (Option Syntax) | atom info@(SourceInfo.original lead pos trail) val => do let trailStop := chooseNiceTrailStop trail let newInfo := updateInfo info (← get) trailStop set trailStop pure $ some (atom newInfo val) | ident info@(SourceInfo.original lead pos trail) rawVal val pre => do let trailStop := chooseNiceTrailStop trail let newInfo := updateInfo info (← get) trailStop set trailStop pure $ some (ident newInfo rawVal val pre) | _ => pure none /-- Set `SourceInfo.leading` according to the trailing stop of the preceding token. The result is a round-tripping syntax tree IF, in the input syntax tree, * all leading stops, atom contents, and trailing starts are correct * trailing stops are between the trailing start and the next leading stop. Remark: after parsing, all `SourceInfo.leading` fields are empty. The `Syntax` argument is the output produced by the parser for `source`. This function "fixes" the `source.leading` field. Additionally, we try to choose "nicer" splits between leading and trailing stops according to some heuristics so that e.g. comments are associated to the (intuitively) correct token. Note that the `SourceInfo.trailing` fields must be correct. The implementation of this Function relies on this property. -/ def updateLeading : Syntax → Syntax := fun stx => (replaceM updateLeadingAux stx).run' 0 partial def updateTrailing (trailing : Substring) : Syntax → Syntax | Syntax.atom info val => Syntax.atom (info.updateTrailing trailing) val | Syntax.ident info rawVal val pre => Syntax.ident (info.updateTrailing trailing) rawVal val pre | n@(Syntax.node k args) => if args.size == 0 then n else let i := args.size - 1 let last := updateTrailing trailing args[i] let args := args.set! i last; Syntax.node k args | s => s partial def getTailWithPos : Syntax → Option Syntax | stx@(atom info _) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node _ args => args.findSomeRev? getTailWithPos | _ => none private def reprintLeaf (info : SourceInfo) (val : String) : String := match info with | SourceInfo.original lead _ trail => s!"{lead}{val}{trail}" -- no source info => add gracious amounts of whitespace to definitely separate tokens -- Note that the proper pretty printer does not use this function. -- The parser as well always produces source info, so round-tripping is still -- guaranteed. | _ => s!" {val} " partial def reprint : Syntax → Option String | atom info val => reprintLeaf info val | ident info rawVal _ _ => reprintLeaf info rawVal.toString | node kind args => if kind == choiceKind then if args.size == 0 then failure else do let s ← reprint args[0] args[1:].foldlM (init := s) fun s stx => do let s' ← reprint stx guard (s == s') pure s else args.foldlM (fun r stx => do let s ← reprint stx; pure $ r ++ s) "" | _ => "" /-- Represents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right. Indices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`. If the `Traverser` is used linearly, updates are linear in the `Syntax` object as well. -/ structure Traverser where cur : Syntax parents : Array Syntax idxs : Array Nat namespace Traverser def fromSyntax (stx : Syntax) : Traverser := ⟨stx, #[], #[]⟩ def setCur (t : Traverser) (stx : Syntax) : Traverser := { t with cur := stx } /-- Advance to the `idx`-th child of the current node. -/ def down (t : Traverser) (idx : Nat) : Traverser := if idx < t.cur.getNumArgs then { cur := t.cur.getArg idx, parents := t.parents.push $ t.cur.setArg idx arbitrary, idxs := t.idxs.push idx } else { cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx } /-- Advance to the parent of the current node, if any. -/ def up (t : Traverser) : Traverser := if t.parents.size > 0 then let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back { cur := cur, parents := t.parents.pop, idxs := t.idxs.pop } else t /-- Advance to the left sibling of the current node, if any. -/ def left (t : Traverser) : Traverser := if t.parents.size > 0 then t.up.down (t.idxs.back - 1) else t /-- Advance to the right sibling of the current node, if any. -/ def right (t : Traverser) : Traverser := if t.parents.size > 0 then t.up.down (t.idxs.back + 1) else t end Traverser /-- Monad class that gives read/write access to a `Traverser`. -/ class MonadTraverser (m : Type → Type) where st : MonadState Traverser m namespace MonadTraverser variable {m : Type → Type} [Monad m] [t : MonadTraverser m] def getCur : m Syntax := Traverser.cur <$> t.st.get def setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx) def goDown (idx : Nat) : m Unit := @modify _ _ t.st (fun t => t.down idx) def goUp : m Unit := @modify _ _ t.st (fun t => t.up) def goLeft : m Unit := @modify _ _ t.st (fun t => t.left) def goRight : m Unit := @modify _ _ t.st (fun t => t.right) def getIdx : m Nat := do let st ← t.st.get st.idxs.back?.getD 0 end MonadTraverser end Syntax namespace SyntaxNode @[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name := (n.getArg i).getId end SyntaxNode def mkListNode (args : Array Syntax) : Syntax := Syntax.node nullKind args namespace Syntax -- quotation node kinds are formed from a unique quotation name plus "quot" def isQuot : Syntax → Bool | Syntax.node (Name.str _ "quot" _) _ => true | Syntax.node `Lean.Parser.Term.dynamicQuot _ => true | _ => false def getQuotContent (stx : Syntax) : Syntax := if stx.isOfKind `Lean.Parser.Term.dynamicQuot then stx[3] else stx[1] -- antiquotation node kinds are formed from the original node kind (if any) plus "antiquot" def isAntiquot : Syntax → Bool | Syntax.node (Name.str _ "antiquot" _) _ => true | _ => false def mkAntiquotNode (term : Syntax) (nesting := 0) (name : Option String := none) (kind := Name.anonymous) : Syntax := let nesting := mkNullNode (mkArray nesting (mkAtom "$")) let term := match term.isIdent with | true => term | false => mkNode `antiquotNestedExpr #[mkAtom "(", term, mkAtom ")"] let name := match name with | some name => mkNode `antiquotName #[mkAtom ":", mkAtom name] | none => mkNullNode mkNode (kind ++ `antiquot) #[mkAtom "$", nesting, term, name] -- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices. def isEscapedAntiquot (stx : Syntax) : Bool := !stx[1].getArgs.isEmpty -- Also works for antiquotation splices. def unescapeAntiquot (stx : Syntax) : Syntax := if isAntiquot stx then stx.setArg 1 $ mkNullNode stx[1].getArgs.pop else stx -- Also works for token antiquotations. def getAntiquotTerm (stx : Syntax) : Syntax := let e := if stx.isAntiquot then stx[2] else stx[3] if e.isIdent then e else -- `e` is from `"(" >> termParser >> ")"` e[1] def antiquotKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot" _) args => if args[3].isOfKind `antiquotName then some k else -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`) some Name.anonymous | _ => none -- An "antiquotation splice" is something like `$[...]?` or `$[...]*`. def antiquotSpliceKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot_scope" _) args => some k | _ => none def isAntiquotSplice (stx : Syntax) : Bool := antiquotSpliceKind? stx |>.isSome def getAntiquotSpliceContents (stx : Syntax) : Array Syntax := stx[3].getArgs -- `$[..],*` or `$x,*` ~> `,*` def getAntiquotSpliceSuffix (stx : Syntax) : Syntax := if stx.isAntiquotSplice then stx[5] else stx[1] def mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax := let nesting := mkNullNode (mkArray nesting (mkAtom "$")) mkNode (kind ++ `antiquot_splice) #[mkAtom "$", nesting, mkAtom "[", mkNullNode contents, mkAtom "]", mkAtom suffix] -- `$x,*` etc. def antiquotSuffixSplice? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot_suffix_splice" _) args => some k | _ => none def isAntiquotSuffixSplice (stx : Syntax) : Bool := antiquotSuffixSplice? stx |>.isSome -- `$x` in the example above def getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax := stx[0] def mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax := mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix] def isTokenAntiquot (stx : Syntax) : Bool := stx.isOfKind `token_antiquot end Syntax end Lean
79b749525e22c3579a77c0e9443a8e6462f66ecd
618003631150032a5676f229d13a079ac875ff77
/src/tactic/simpa.lean
be5469e7583271b85fb8f59b9d6ada3abdc76e3c
[ "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
2,209
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.doc_commands namespace tactic namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional /-- This is a "finishing" tactic modification of `simp`. It has two forms. * `simpa [rules, ...] using e` will simplify the goal and the type of `e` using `rules`, then try to close the goal using `e`. Simplifying the type of `e` makes it more likely to match the goal (which has also been simplified). This construction also tends to be more robust under changes to the simp lemma set. * `simpa [rules, ...]` will simplify the goal and the type of a hypothesis `this` if present in the context, then try to close the goal using the `assumption` tactic. -/ meta def simpa (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := let simp_at lc close_tac := try (simp use_iota_eqn no_dflt hs attr_names (loc.ns lc) cfg) >> (close_tac <|> trivial) in match tgt with | none := get_local `this >> simp_at [some `this, none] assumption <|> simp_at [none] assumption | some e := do e ← i_to_expr e <|> do { ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result pty ← pp ty, ptgt ← pp e, -- Fail deliberately, to advise regarding `simp; exact` usage fail ("simpa failed, 'using' expression type not directly " ++ "inferrable. Try:\n\nsimpa ... using\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, match e with | local_const _ lc _ _ := simp_at [some lc, none] (get_local lc >>= tactic.exact) | e := do t ← infer_type e, assertv `this t e >> simp_at [some `this, none] (get_local `this >>= tactic.exact) end end add_tactic_doc { name := "simpa", category := doc_category.tactic, decl_names := [`tactic.interactive.simpa], tags := ["simplification"] } end interactive end tactic
2e151eb06f830e2cead8e782c74fc68bbb4e8a51
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/eq.lean
9bc9ff084daea541ef9173dcfe54f29885ea7be0
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
1,481
lean
--#check eq.refl --#check eq.symm --#check eq.trans namespace hidden universe u --#check @eq.refl.{u} --#check @eq.symm.{u} --#check @eq.trans.{u} lemma L1 : 2 + 3 = 5 := eq.refl _ --#check L1 lemma L2 : 2 + 3 = 5 := rfl --#check L2 lemma L3 : ∀ (α : Type u) (a b : α)(p : α → Prop), a = b → p a → p b := assume α a b p q H, eq.subst q H --#check L3 lemma L4 : ∀ (α : Type u) (a b : α)(p : α → Prop), a = b → p a → p b := assume α a b p q H, q ▸ H -- \t --#check L4 lemma cong : ∀ {α β : Type u} {x y : α} (f : α → β), x = y → f x = f y := assume α β x y f p, p ▸ rfl --#check @cong lemma L5 : ∀ {α β : Type u} {f g : α → β} (x : α) , f = g → f x = g x := begin intros α β f g x p, rw p end --#check L5 lemma L6 : ∀ {α β : Type u} {f g : α → β} (x y : α), f = g → x = y → f x = g y := begin intros α β f g x y H1 H2, rw H1, rw H2 end --#check L6 --#check @congr_arg -- same as cong --#check @congr_fun --#check @congr --#check @add_zero --#check @zero_add --#check @mul_one --#check @one_mul --#check @neg_add_self --#check @add_neg_self --#check @sub_self --#check @add_comm --#check @add_assoc --#check @mul_comm --#check @mul_assoc --#check @mul_add --#check @left_distrib --#check @add_mul --#check @right_distrib --#check @mul_sub --#check @sub_mul lemma L7 : forall (x y z : ℤ), x * (y + z) = x * y + x * z := assume x y z, mul_add x y z --#check L7 end hidden
6417c0a4965cfc844742f87d37f5c24cd1246de9
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/sheaves/sheaf.lean
efa565245ef23207d607929f02b28b3292ee741a
[]
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
1,523
lean
/- Sheaf (of types). https://stacks.math.columbia.edu/tag/006S -/ import sheaves.covering.covering import sheaves.presheaf universes u v open topological_space lattice section sheaf_condition variables {α : Type u} [topological_space α] -- Restriction map from U to U ∩ V. def res_to_inter_left (F : presheaf α) (U V : opens α) : (F U) → (F (U ∩ V)) := F.res U (U ∩ V) (set.inter_subset_left U V) -- Restriction map from V to U ∩ V. def res_to_inter_right (F : presheaf α) (U V : opens α) : (F V) → (F (U ∩ V)) := F.res V (U ∩ V) (set.inter_subset_right U V) -- Sheaf condition. def locality (F : presheaf α) := ∀ {U} (OC : covering U) (s t : F U), (∀ i, F.res U (OC.Uis i) (subset_covering i) s = F.res U (OC.Uis i) (subset_covering i) t) → s = t def gluing (F : presheaf α) := ∀ {U} (OC : covering U), ∀ (s : Π i, F (OC.Uis i)), (∀ j k, res_to_inter_left F (OC.Uis j) (OC.Uis k) (s j) = res_to_inter_right F (OC.Uis j) (OC.Uis k) (s k)) → ∃ S, ∀ i, F.res U (OC.Uis i) (subset_covering i) S = s i end sheaf_condition -- Definition of a sheaf of types. structure sheaf (α : Type u) [T : topological_space α] := (F : presheaf α) (locality : locality F) (gluing : gluing F) section sheaf_of_types variables {α : Type u} [T : topological_space α] include T instance sheaf.to_presheaf : has_coe (sheaf α) (presheaf α) := ⟨λ S, S.F⟩ def is_sheaf (F : presheaf α) := locality F ∧ gluing F end sheaf_of_types
f645ef817aff9589f4f100dd5ae194e5cf763a94
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/NearRing.lean
d4dc08c43f11856b7d902b6bbddd1881aa09aa38
[]
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,849
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 NearRing structure NearRing (A : Type) : Type := (times : (A → (A → A))) (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)))) (neg : (A → A)) (leftInverse_inv_op_zero : (∀ {x : A} , (plus x (neg x)) = zero)) (rightInverse_inv_op_zero : (∀ {x : A} , (plus (neg x) x) = zero)) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x)))) open NearRing structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) (zeroS : AS) (negS : (AS → AS)) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (zeroP : (Prod A A)) (negP : ((Prod A A) → (Prod A A))) (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)))) (leftInverse_inv_op_0P : (∀ {xP : (Prod A A)} , (plusP xP (negP xP)) = zeroP)) (rightInverse_inv_op_0P : (∀ {xP : (Prod A A)} , (plusP (negP xP) xP) = zeroP)) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP 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} (Ne1 : (NearRing A1)) (Ne2 : (NearRing A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Ne1) x1 x2)) = ((times Ne2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ne1) x1 x2)) = ((plus Ne2) (hom x1) (hom x2)))) (pres_zero : (hom (zero Ne1)) = (zero Ne2)) (pres_neg : (∀ {x1 : A1} , (hom ((neg Ne1) x1)) = ((neg Ne2) (hom x1)))) structure RelInterp {A1 : Type} {A2 : Type} (Ne1 : (NearRing A1)) (Ne2 : (NearRing A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Ne1) x1 x2) ((times Ne2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ne1) x1 x2) ((plus Ne2) y1 y2)))))) (interp_zero : (interp (zero Ne1) (zero Ne2))) (interp_neg : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((neg Ne1) x1) ((neg Ne2) y1))))) inductive NearRingTerm : Type | timesL : (NearRingTerm → (NearRingTerm → NearRingTerm)) | plusL : (NearRingTerm → (NearRingTerm → NearRingTerm)) | zeroL : NearRingTerm | negL : (NearRingTerm → NearRingTerm) open NearRingTerm inductive ClNearRingTerm (A : Type) : Type | sing : (A → ClNearRingTerm) | timesCl : (ClNearRingTerm → (ClNearRingTerm → ClNearRingTerm)) | plusCl : (ClNearRingTerm → (ClNearRingTerm → ClNearRingTerm)) | zeroCl : ClNearRingTerm | negCl : (ClNearRingTerm → ClNearRingTerm) open ClNearRingTerm inductive OpNearRingTerm (n : ℕ) : Type | v : ((fin n) → OpNearRingTerm) | timesOL : (OpNearRingTerm → (OpNearRingTerm → OpNearRingTerm)) | plusOL : (OpNearRingTerm → (OpNearRingTerm → OpNearRingTerm)) | zeroOL : OpNearRingTerm | negOL : (OpNearRingTerm → OpNearRingTerm) open OpNearRingTerm inductive OpNearRingTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpNearRingTerm2) | sing2 : (A → OpNearRingTerm2) | timesOL2 : (OpNearRingTerm2 → (OpNearRingTerm2 → OpNearRingTerm2)) | plusOL2 : (OpNearRingTerm2 → (OpNearRingTerm2 → OpNearRingTerm2)) | zeroOL2 : OpNearRingTerm2 | negOL2 : (OpNearRingTerm2 → OpNearRingTerm2) open OpNearRingTerm2 def simplifyCl {A : Type} : ((ClNearRingTerm A) → (ClNearRingTerm A)) | (plusCl zeroCl x) := x | (plusCl x zeroCl) := x | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | zeroCl := zeroCl | (negCl x1) := (negCl (simplifyCl x1)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpNearRingTerm n) → (OpNearRingTerm n)) | (plusOL zeroOL x) := x | (plusOL x zeroOL) := x | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | zeroOL := zeroOL | (negOL x1) := (negOL (simplifyOpB x1)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpNearRingTerm2 n A) → (OpNearRingTerm2 n A)) | (plusOL2 zeroOL2 x) := x | (plusOL2 x zeroOL2) := x | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | zeroOL2 := zeroOL2 | (negOL2 x1) := (negOL2 (simplifyOp x1)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((NearRing A) → (NearRingTerm → A)) | Ne (timesL x1 x2) := ((times Ne) (evalB Ne x1) (evalB Ne x2)) | Ne (plusL x1 x2) := ((plus Ne) (evalB Ne x1) (evalB Ne x2)) | Ne zeroL := (zero Ne) | Ne (negL x1) := ((neg Ne) (evalB Ne x1)) def evalCl {A : Type} : ((NearRing A) → ((ClNearRingTerm A) → A)) | Ne (sing x1) := x1 | Ne (timesCl x1 x2) := ((times Ne) (evalCl Ne x1) (evalCl Ne x2)) | Ne (plusCl x1 x2) := ((plus Ne) (evalCl Ne x1) (evalCl Ne x2)) | Ne zeroCl := (zero Ne) | Ne (negCl x1) := ((neg Ne) (evalCl Ne x1)) def evalOpB {A : Type} {n : ℕ} : ((NearRing A) → ((vector A n) → ((OpNearRingTerm n) → A))) | Ne vars (v x1) := (nth vars x1) | Ne vars (timesOL x1 x2) := ((times Ne) (evalOpB Ne vars x1) (evalOpB Ne vars x2)) | Ne vars (plusOL x1 x2) := ((plus Ne) (evalOpB Ne vars x1) (evalOpB Ne vars x2)) | Ne vars zeroOL := (zero Ne) | Ne vars (negOL x1) := ((neg Ne) (evalOpB Ne vars x1)) def evalOp {A : Type} {n : ℕ} : ((NearRing A) → ((vector A n) → ((OpNearRingTerm2 n A) → A))) | Ne vars (v2 x1) := (nth vars x1) | Ne vars (sing2 x1) := x1 | Ne vars (timesOL2 x1 x2) := ((times Ne) (evalOp Ne vars x1) (evalOp Ne vars x2)) | Ne vars (plusOL2 x1 x2) := ((plus Ne) (evalOp Ne vars x1) (evalOp Ne vars x2)) | Ne vars zeroOL2 := (zero Ne) | Ne vars (negOL2 x1) := ((neg Ne) (evalOp Ne vars x1)) def inductionB {P : (NearRingTerm → Type)} : ((∀ (x1 x2 : NearRingTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : NearRingTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P zeroL) → ((∀ (x1 : NearRingTerm) , ((P x1) → (P (negL x1)))) → (∀ (x : NearRingTerm) , (P x)))))) | ptimesl pplusl p0l pnegl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl p0l pnegl x1) (inductionB ptimesl pplusl p0l pnegl x2)) | ptimesl pplusl p0l pnegl (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl p0l pnegl x1) (inductionB ptimesl pplusl p0l pnegl x2)) | ptimesl pplusl p0l pnegl zeroL := p0l | ptimesl pplusl p0l pnegl (negL x1) := (pnegl _ (inductionB ptimesl pplusl p0l pnegl x1)) def inductionCl {A : Type} {P : ((ClNearRingTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClNearRingTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClNearRingTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P zeroCl) → ((∀ (x1 : (ClNearRingTerm A)) , ((P x1) → (P (negCl x1)))) → (∀ (x : (ClNearRingTerm A)) , (P x))))))) | psing ptimescl ppluscl p0cl pnegcl (sing x1) := (psing x1) | psing ptimescl ppluscl p0cl pnegcl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl p0cl pnegcl x1) (inductionCl psing ptimescl ppluscl p0cl pnegcl x2)) | psing ptimescl ppluscl p0cl pnegcl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl p0cl pnegcl x1) (inductionCl psing ptimescl ppluscl p0cl pnegcl x2)) | psing ptimescl ppluscl p0cl pnegcl zeroCl := p0cl | psing ptimescl ppluscl p0cl pnegcl (negCl x1) := (pnegcl _ (inductionCl psing ptimescl ppluscl p0cl pnegcl x1)) def inductionOpB {n : ℕ} {P : ((OpNearRingTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpNearRingTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpNearRingTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P zeroOL) → ((∀ (x1 : (OpNearRingTerm n)) , ((P x1) → (P (negOL x1)))) → (∀ (x : (OpNearRingTerm n)) , (P x))))))) | pv ptimesol pplusol p0ol pnegol (v x1) := (pv x1) | pv ptimesol pplusol p0ol pnegol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol p0ol pnegol x1) (inductionOpB pv ptimesol pplusol p0ol pnegol x2)) | pv ptimesol pplusol p0ol pnegol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol p0ol pnegol x1) (inductionOpB pv ptimesol pplusol p0ol pnegol x2)) | pv ptimesol pplusol p0ol pnegol zeroOL := p0ol | pv ptimesol pplusol p0ol pnegol (negOL x1) := (pnegol _ (inductionOpB pv ptimesol pplusol p0ol pnegol x1)) def inductionOp {n : ℕ} {A : Type} {P : ((OpNearRingTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpNearRingTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpNearRingTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P zeroOL2) → ((∀ (x1 : (OpNearRingTerm2 n A)) , ((P x1) → (P (negOL2 x1)))) → (∀ (x : (OpNearRingTerm2 n A)) , (P x)))))))) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 x2)) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 x2)) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 zeroOL2 := p0ol2 | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 (negOL2 x1) := (pnegol2 _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 x1)) def stageB : (NearRingTerm → (Staged NearRingTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | zeroL := (Now zeroL) | (negL x1) := (stage1 negL (codeLift1 negL) (stageB x1)) def stageCl {A : Type} : ((ClNearRingTerm A) → (Staged (ClNearRingTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | zeroCl := (Now zeroCl) | (negCl x1) := (stage1 negCl (codeLift1 negCl) (stageCl x1)) def stageOpB {n : ℕ} : ((OpNearRingTerm n) → (Staged (OpNearRingTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | zeroOL := (Now zeroOL) | (negOL x1) := (stage1 negOL (codeLift1 negOL) (stageOpB x1)) def stageOp {n : ℕ} {A : Type} : ((OpNearRingTerm2 n A) → (Staged (OpNearRingTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | zeroOL2 := (Now zeroOL2) | (negOL2 x1) := (stage1 negOL2 (codeLift1 negOL2) (stageOp x1)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (zeroT : (Repr A)) (negT : ((Repr A) → (Repr A))) end NearRing
8cad306e98d72899e64d6ae240cc51ce57c8bac5
e151e9053bfd6d71740066474fc500a087837323
/src/hott/types/trunc.lean
6c673d3c24b78bf404e3b8e7e92af85fce73af43
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
36,121
lean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Properties of trunc_index, is_trunc, trunctype, trunc, and the pointed versions of these -/ -- NOTE: the fact that (is_trunc n A) is a mere proposition is proved in .prop_trunc import ..function .unit universes u v w hott_theory namespace hott open hott.sigma hott.pi hott.function hott.equiv trunctype nat hott.is_equiv hott.prod pointed hott.nat hott.is_trunc hott.algebra hott.sum sum hott.unit /- basic computation with ℕ₋₂, its operations and its order -/ namespace trunc_index instance has_le_trunc_index : has_le ℕ₋₂ := ⟨trunc_index.le⟩ @[hott] def minus_one_le_succ (n : ℕ₋₂) : -1 ≤ n.+1 := succ_le_succ (minus_two_le n) @[hott] def zero_le_of_nat (n : ℕ) : 0 ≤ of_nat n := succ_le_succ (minus_one_le_succ _) @[hott, reducible] protected def code : ℕ₋₂ → ℕ₋₂ → Type | -2 -2 := unit | -2 (succ m) := empty | (succ n) -2 := empty | (succ n) (succ m) := n = m @[hott] protected def refl : Πn, trunc_index.code n n | -2 := ⋆ | (succ n) := idp @[hott] protected def encode {n m : ℕ₋₂} (p : n = m) : trunc_index.code n m := p ▸ trunc_index.refl n @[hott] protected def decode : Π(n m : ℕ₋₂), trunc_index.code n m → n = m | -2 -2 := λc, idp | -2 (succ l) := λc, empty.elim c | (succ k) -2 := λc, empty.elim c | (succ k) (succ l) := λc, ap succ c @[hott] def succ_ne_minus_two (n : ℕ₋₂) : succ n ≠ -2 := trunc_index.encode @[hott, instance] protected def has_decidable_eq : Π(n m : ℕ₋₂), decidable (n = m) | -2 -2 := decidable.inl rfl | (n.+1) -2 := decidable.inr trunc_index.encode | -2 (m.+1) := decidable.inr trunc_index.encode | (n.+1) (m.+1) := match has_decidable_eq n m with | decidable.inl xeqy := decidable.inl (ap succ xeqy) | decidable.inr xney := decidable.inr (λh, xney (trunc_index.encode h)) end @[hott] def not_succ_le_minus_two {n : ℕ₋₂} (H : n .+1 ≤ -2) : empty := begin have : Πm, n.+1 ≤ m → m = -2 → empty, { intros m H, hinduction H with m H IH, exact succ_ne_minus_two n, exact succ_ne_minus_two m }, exact this -2 H idp end @[hott] protected def le_trans {n m k : ℕ₋₂} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k := begin induction H2 with k H2 IH, { exact H1}, { exact le.step IH} end @[hott] protected def pred (n : ℕ₋₂) : ℕ₋₂ := trunc_index.rec -2 (λm _, m) n @[hott] protected def pred_le (n : ℕ₋₂) : trunc_index.pred n ≤ n := by cases n; repeat { constructor } @[hott] def pred_le_pred {n m : ℕ₋₂} (H : n ≤ m) : trunc_index.pred n ≤ trunc_index.pred m := begin hinduction H with k H2 IH, apply le.tr_refl, exact trunc_index.le_trans IH (trunc_index.pred_le k) end @[hott] def le_of_succ_le_succ {n m : ℕ₋₂} (H : n.+1 ≤ m.+1) : n ≤ m := pred_le_pred H @[hott] def not_succ_le_self {n : ℕ₋₂} : ¬n.+1 ≤ n := begin induction n with n IH; intro H, { exact not_succ_le_minus_two H}, { exact IH (le_of_succ_le_succ H)} end @[hott] protected def le_antisymm {n m : ℕ₋₂} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := begin induction H2 with n H2 IH, { refl }, { apply empty.elim, apply @not_succ_le_self n, exact trunc_index.le_trans H1 H2} end @[hott] protected def le_succ {n m : ℕ₋₂} (H1 : n ≤ m) : n ≤ m.+1 := le.step H1 @[hott] protected def self_le_succ (n : ℕ₋₂) : n ≤ n.+1 := le.step (trunc_index.le.tr_refl n) -- the order is total @[hott] protected def le_sum_le (n m : ℕ₋₂) : n ≤ m ⊎ m ≤ n := begin induction m with m IH, { exact inr (minus_two_le _)}, { cases IH with H H, { exact inl (trunc_index.le_succ H)}, { hinduction H with n' H x, { exact inl (trunc_index.self_le_succ _)}, { exact inr (succ_le_succ H)}}} end end trunc_index open trunc_index @[hott, instance, reducible] def linear_weak_order_trunc_index : linear_weak_order trunc_index := linear_weak_order.mk le trunc_index.le.tr_refl @trunc_index.le_trans @trunc_index.le_antisymm trunc_index.le_sum_le namespace trunc_index /- more theorems about truncation indices -/ @[hott] def zero_add (n : ℕ₋₂) : (0 : ℕ₋₂) + n = n := begin cases n with n, refl, cases n with n, refl, induction n with n IH, refl, exact ap succ IH end @[hott] def add_zero (n : ℕ₋₂) : n + (0 : ℕ₋₂) = n := by refl @[hott] def succ_add_nat (n : ℕ₋₂) (m : ℕ) : n.+1 + m = (n + m).+1 := begin induction m with m IH, refl, exact ap succ IH end @[hott] def nat_add_succ (n : ℕ) (m : ℕ₋₂) : ↑n + m.+1 = (n + m).+1 := begin cases m with m, refl, cases m with m, refl, induction m with m IH, refl, exact ap succ IH end @[hott] def add_nat_succ (n : ℕ₋₂) (m : ℕ) : n + (nat.succ m) = (n + m).+1 := by refl @[hott] def nat_succ_add (n : ℕ) (m : ℕ₋₂) : ↑(nat.succ n) + m = (n + m).+1 := begin cases m with m, refl, cases m with m, refl, induction m with m IH, refl, exact ap succ IH end @[hott] def sub_two_add_two (n : ℕ₋₂) : sub_two (add_two n) = n := begin induction n with n IH, { refl }, { exact ap succ IH} end @[hott] def add_two_sub_two (n : ℕ) : add_two (sub_two n) = n := begin induction n with n IH, { refl }, { exact ap nat.succ IH} end @[hott] def of_nat_add_plus_two_of_nat (n m : ℕ) : n +2+ m = of_nat (n + m + 2) := begin induction m with m IH, { refl }, { exact ap succ IH} end @[hott] def of_nat_add_of_nat (n m : ℕ) : of_nat n + of_nat m = of_nat (n + m) := begin induction m with m IH, { refl }, { exact ap succ IH} end @[hott] def succ_add_plus_two (n m : ℕ₋₂) : n.+1 +2+ m = (n +2+ m).+1 := begin induction m with m IH, { refl }, { exact ap succ IH} end @[hott] def add_plus_two_succ (n m : ℕ₋₂) : n +2+ m.+1 = (n +2+ m).+1 := idp @[hott] def add_succ_succ (n m : ℕ₋₂) : n + m.+2 = n +2+ m := idp @[hott] def succ_add_succ (n m : ℕ₋₂) : n.+1 + m.+1 = n +2+ m := begin cases m with m IH, { refl }, { apply succ_add_plus_two} end @[hott] def succ_succ_add (n m : ℕ₋₂) : n.+2 + m = n +2+ m := begin cases m with m IH, { refl }, { exact succ_add_succ _ _ ⬝ succ_add_plus_two _ _} end @[hott] def succ_sub_two (n : ℕ) : (nat.succ n).-2 = n.-2 .+1 := rfl @[hott] def sub_two_succ_succ (n : ℕ) : n.-2.+1.+1 = n := rfl @[hott] def succ_sub_two_succ (n : ℕ) : (nat.succ n).-2.+1 = n := rfl @[hott] def of_nat_add_two (n : ℕ₋₂) : of_nat (add_two n) = n.+2 := begin induction n with n IH, refl, exact ap succ IH end @[hott] def of_nat_le_of_nat {n m : ℕ} (H : n ≤ m) : (of_nat n ≤ of_nat m) := begin induction H with m H IH, { apply le.refl }, { exact trunc_index.le_succ IH} end @[hott] def sub_two_le_sub_two {n m : ℕ} (H : n ≤ m) : n.-2 ≤ m.-2 := begin induction H with m H IH, { apply le.refl }, { exact trunc_index.le_succ IH} end @[hott] def add_two_le_add_two {n m : ℕ₋₂} (H : n ≤ m) : add_two n ≤ add_two m := begin induction H with m H IH, { refl }, { constructor, exact IH}, end @[hott] def le_of_sub_two_le_sub_two {n m : ℕ} (H : n.-2 ≤ m.-2) : n ≤ m := begin rwr [←add_two_sub_two n, ←add_two_sub_two m], exact add_two_le_add_two H, end @[hott] def le_of_of_nat_le_of_nat {n m : ℕ} (H : of_nat n ≤ of_nat m) : n ≤ m := begin apply le_of_sub_two_le_sub_two, exact le_of_succ_le_succ (le_of_succ_le_succ H) end @[hott] protected theorem succ_le_of_not_le {n m : ℕ₋₂} (H : ¬ n ≤ m) : m.+1 ≤ n := begin cases (le.total n m) with H2 H2, { apply empty.elim, exact H H2}, { hinduction H2 with n' H2' x, { apply empty.elim, exact H (le.refl _)}, { exact succ_le_succ H2'}} end @[hott, instance] def trunc_index.decidable_le : Π(n m : ℕ₋₂), decidable (n ≤ m) := begin intro n, induction n with n IH; intro m, { left, apply minus_two_le}, cases m with m, { right, apply not_succ_le_minus_two}, cases IH m with H H, { left, apply succ_le_succ H}, right, intro H2, apply H, exact le_of_succ_le_succ H2 end end trunc_index open trunc_index namespace is_trunc variables {A : Type _} {B : Type _} {n : ℕ₋₂} /- closure properties of truncatedness -/ @[hott] theorem is_trunc_is_embedding_closed (f : A → B) [Hf : is_embedding f] [HB : is_trunc n B] (Hn : -1 ≤ n) : is_trunc n A := begin unfreezeI; induction n with n, {apply empty.elim, exact not_succ_le_minus_two Hn}, {apply is_trunc_succ_intro, intros a a', fapply @is_trunc_is_equiv_closed_rev _ _ n (ap f), resetI, apply_instance } end @[hott] theorem is_trunc_is_retraction_closed (f : A → B) [Hf : is_retraction f] (n : ℕ₋₂) [HA : is_trunc n A] : is_trunc n B := begin unfreezeI; induction n with n IH generalizing A B f Hf HA, { induction Hf with g ε, fapply is_contr.mk, { exactI f (center A) }, { intro b, apply concat, { apply (ap f), exact (center_eq (g b)) }, { apply ε }}}, { induction Hf with g ε, apply is_trunc_succ_intro, intros b b', napply @IH (g b = g b') _ (λq, (ε b)⁻¹ ⬝ ap f q ⬝ ε b'), { apply (is_retraction.mk (ap g)), { intro p, induction p, dsimp [ap], apply con.left_inv }}, { apply is_trunc_eq }} end @[hott] def is_embedding_to_fun (A B : Type _) : is_embedding (@to_fun A B) := λf f', is_equiv_ap_to_fun _ _ /- theorems about trunctype -/ @[hott] protected def trunctype.sigma_char (n : ℕ₋₂) : (trunctype.{u} n) ≃ (Σ (A : Type u), is_trunc n A) := begin fapply equiv.MK, { intro A, exact (⟨carrier A, struct A⟩)}, { intro S, exact (trunctype.mk S.1 S.2)}, { intro S, induction S with S1 S2, refl }, { intro A, induction A with A1 A2, refl }, end @[hott] def trunctype_eq_equiv (n : ℕ₋₂) (A B : n-Type) : (A = B) ≃ (carrier A = carrier B) := calc (A = B) ≃ (to_fun (trunctype.sigma_char n) A = to_fun (trunctype.sigma_char n) B) : eq_equiv_fn_eq_of_equiv (trunctype.sigma_char n) A B ... ≃ ((to_fun (trunctype.sigma_char n) A).1 = (to_fun (trunctype.sigma_char n) B).1) : equiv.symm (equiv_subtype _ _) ... ≃ (carrier A = carrier B) : erfl @[hott, instance] theorem is_trunc_trunctype (n : ℕ₋₂) : is_trunc n.+1 (n-Type) := begin apply is_trunc_succ_intro, intros X Y, fapply is_trunc_equiv_closed_rev _ (trunctype_eq_equiv _ _ _), fapply is_trunc_equiv_closed_rev _ (eq_equiv_equiv _ _), induction n, { napply is_contr_of_inhabited_prop, { apply is_trunc_equiv }, { apply equiv_of_is_contr_of_is_contr }}, { apply is_trunc_equiv } end /- univalence for truncated types -/ @[hott] def teq_equiv_equiv {n : ℕ₋₂} {A B : n-Type} : (A = B) ≃ (A ≃ B) := trunctype_eq_equiv n A B ⬝e eq_equiv_equiv A B @[hott] def tua {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : A = B := (trunctype_eq_equiv n A B)⁻¹ᶠ (ua f) @[hott] def tua_refl {n : ℕ₋₂} (A : n-Type) : tua (@erfl A) = idp := begin refine ap (trunctype_eq_equiv n A A)⁻¹ᶠ (ua_refl A) ⬝ _, refine ap (eq_of_fn_eq_fn _) _ ⬝ eq_of_fn_eq_fn'_idp _ _, apply ap (dpair_eq_dpair idp) (is_prop.elim _ idpo), apply is_trunc.is_trunc_pathover end @[hott] def tua_trans {n : ℕ₋₂} {A B C : n-Type} (f : A ≃ B) (g : B ≃ C) : tua (f ⬝e g) = tua f ⬝ tua g := begin refine ap (trunctype_eq_equiv n A C)⁻¹ᶠ (ua_trans f g) ⬝ _, refine ap (eq_of_fn_eq_fn _) _ ⬝ eq_of_fn_eq_fn'_con _ _ _, refine _ ⬝ dpair_eq_dpair_con _ _ _ _, apply ap (dpair_eq_dpair _), apply is_prop.elim end @[hott] def tua_symm {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : tua f⁻¹ᵉ = (tua f)⁻¹ := begin apply eq_inv_of_con_eq_idp', refine (tua_trans _ _)⁻¹ ⬝ _, refine ap tua _ ⬝ (tua_refl _), apply equiv_eq, exact to_right_inv f end @[hott] def tcast {n : ℕ₋₂} {A B : n-Type} (p : A = B) (a : A) : B := cast (ap trunctype.carrier p) a @[hott] def ptcast {n : ℕ₋₂} {A B : n-Type*} (p : A = B) : ↑A →* ↑B := pcast (ap ptrunctype.to_pType p) @[hott] theorem tcast_tua_fn {n : ℕ₋₂} {A B : n-Type} (f : A ≃ B) : tcast (tua f) = to_fun f := begin cases A with A HA, cases B with B HB, dsimp at f, hinduction f using rec_on_ua_idp, have : HA = HB, from is_prop.elim _ _, hinduction this, exact ap tcast (tua_refl _) end /- theorems about decidable equality and axiom K -/ @[hott] theorem is_set_of_axiom_K {A : Type _} (K : Π{a : A} (p : a = a), p = idp) : is_set A := is_set.mk _ (λa b p q, begin induction q, apply K end) @[hott] theorem is_set_of_relation {A : Type u} (R : A → A → Type u) (mere : Π(a b : A), is_prop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) : is_set A := is_set_of_axiom_K (λa p, have H2 : transport (λx, R a x → a = x) p (@imp a a) = @imp a a, from apdt (@imp a) p, have H3 : Π(r : R a a), transport (λx, a = x) p (imp r) = imp (transport (λx, R a x) p r), from to_fun ((heq_pi _ _ _)⁻¹ᵉ) H2, have H4 : imp (refl a) ⬝ p = imp (refl a), from calc imp (refl a) ⬝ p = transport (λx, a = x) p (imp (refl a)) : (eq_transport_r _ _)⁻¹ ... = imp (transport (λx, R a x) p (refl a)) : H3 _ ... = imp (refl a) : ap imp (is_prop.elim _ _), cancel_left (imp (refl a)) H4) @[hott] def relation_equiv_eq {A : Type _} (R : A → A → Type _) (mere : Π(a b : A), is_prop (R a b)) (refl : Π(a : A), R a a) (imp : Π{a b : A}, R a b → a = b) (a b : A) : R a b ≃ a = b := have is_set A, from is_set_of_relation R mere refl @imp, by exactI equiv_of_is_prop imp (λp, transport (R a) p (refl a)) local attribute [reducible] not @[hott] theorem is_set_of_double_neg_elim {A : Type _} (H : Π(a b : A), ¬¬a = b → a = b) : is_set A := is_set_of_relation (λa b, ¬¬a = b) (by apply_instance) (λa n, n idp) H section open decidable --this is proven differently in init.hedberg @[hott] theorem is_set_of_decidable_eq (A : Type _) [H : decidable_eq A] : is_set A := is_set_of_double_neg_elim (λa b, decidable.by_contradiction) end @[hott] theorem is_trunc_of_axiom_K_of_le {A : Type _} {n : ℕ₋₂} (H : -1 ≤ n) (K : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := @is_trunc_succ_intro _ _ (λa b, is_trunc_of_imp_is_trunc_of_le H begin intro p; induction p; apply K end) @[hott] theorem is_trunc_succ_of_is_trunc_loop (Hn : -1 ≤ n) (Hp : Π(a : A), is_trunc n (a = a)) : is_trunc (n.+1) A := begin apply is_trunc_succ_intro, intros a a', apply is_trunc_of_imp_is_trunc_of_le Hn, intro p, induction p, apply Hp end @[hott] theorem is_prop_iff_is_contr {A : Type _} (a : A) : is_prop A ↔ is_contr A := iff.intro (λH, by exactI is_contr.mk a (is_prop.elim a)) (by introI; apply_instance) @[hott] theorem is_trunc_succ_iff_is_trunc_loop (A : Type _) (Hn : -1 ≤ n) : is_trunc (n.+1) A ↔ Π(a : A), is_trunc n (a = a) := iff.intro (by introI; apply_instance) (is_trunc_succ_of_is_trunc_loop Hn) @[hott] theorem is_trunc_iff_is_contr_loopn_succ (n : ℕ) (A : Type _) : is_trunc n A ↔ Π(a : A), is_contr (Ω[n+1](pointed.Mk a)) := begin induction n with n IH generalizing A, { dsimp [loopn], transitivity _, { apply is_trunc_succ_iff_is_trunc_loop, apply le.refl }, { apply pi_iff_pi, intro a, apply is_prop_iff_is_contr, refl }}, { dsimp [loopn], transitivity _, { apply @is_trunc_succ_iff_is_trunc_loop @n, apply minus_one_le_succ }, apply pi_iff_pi, intro a, transitivity _, apply IH, transitivity _, apply pi_iff_pi, intro p, rwr [@loopn_space_loop_irrel (pointed.MK A a) n p], exact ⟨λf, f idp, λH _, H⟩ } end @[hott] theorem is_trunc_iff_is_contr_loopn (n : ℕ) (A : Type _) : is_trunc (n.-2.+1) A ↔ (Π(a : A), is_contr (Ω[n](pointed.Mk a))) := begin induction n with n, { dsimp [sub_two,loopn], apply iff.intro, intros H a, exactI is_contr_of_inhabited_prop a, intro H, apply is_prop_of_imp_is_contr, exact H}, { applyI is_trunc_iff_is_contr_loopn_succ }, end -- rename to is_contr_loopn_of_is_trunc @[hott] theorem is_contr_loop_of_is_trunc (n : ℕ) (A : Type*) [H : is_trunc (n.-2.+1) A] : is_contr (Ω[n] A) := begin unfreezeI; induction A, apply iff.mp (is_trunc_iff_is_contr_loopn _ _) H end -- rename to is_trunc_loopn_of_is_trunc @[hott] theorem is_trunc_loop_of_is_trunc (n : ℕ₋₂) (k : ℕ) (A : Type*) [H : is_trunc n A] : is_trunc n (Ω[k] A) := begin induction k with k IH, { exact H }, { applyI is_trunc_eq } end @[hott] def is_trunc_loopn (k : ℕ₋₂) (n : ℕ) (A : Type*) [H : is_trunc (k+n) A] : is_trunc k (Ω[n] A) := begin unfreezeI; induction n with n IH generalizing k H, exact H, napply is_trunc_eq, napply IH, rwr [succ_add_nat], rwr [add_nat_succ] at H, exact H end @[hott] def is_set_loopn (n : ℕ) (A : Type*) [is_trunc n A] : is_set (Ω[n] A) := have is_trunc (0 + ↑n) A, by rwr [trunc_index.zero_add]; apply_instance, by exactI is_trunc_loopn 0 n A @[hott] def pequiv_punit_of_is_contr (A : Type*) (H : is_contr A) : A ≃* unit* := pequiv_of_equiv (equiv_unit_of_is_contr A) (is_prop.elim _ _) @[hott] def pequiv_punit_of_is_contr' (A : Type _) (H : is_contr A) : pointed.MK A (center A) ≃* unit* := pequiv_punit_of_is_contr (pointed.MK A (center A)) H @[hott] def is_trunc_is_contr_fiber (n : ℕ₋₂) {A B : Type _} (f : A → B) (b : B) [is_trunc n A] [is_trunc n B] : is_trunc n (is_contr (fiber f b)) := begin unfreezeI; cases n, { applyI is_contr_of_inhabited_prop, napply is_contr_fun_of_is_equiv, apply is_equiv_of_is_contr }, { applyI is_trunc_succ_of_is_prop } end end is_trunc open is_trunc namespace trunc variables {n : ℕ₋₂} {A : Type u} {B : Type _} {a₁ a₂ a₃ a₄ : A} @[hott] def trunc_functor2 {n : ℕ₋₂} {A B C : Type _} (f : A → B → C) (x : trunc n A) (y : trunc n B) : trunc n C := by hinduction x with a; hinduction y with b; exact tr (f a b) @[hott] def tconcat (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) : trunc n (a₁ = a₃) := trunc_functor2 concat p q @[hott] def tinverse (p : trunc n (a₁ = a₂)) : trunc n (a₂ = a₁) := trunc_functor _ inverse p @[hott, reducible] def tidp : trunc n (a₁ = a₁) := tr idp @[hott] def tassoc (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) (r : trunc n (a₃ = a₄)) : tconcat (tconcat p q) r = tconcat p (tconcat q r) := by hinduction p; hinduction q; hinduction r; exact ap tr (con.assoc _ _ _) @[hott] def tidp_tcon (p : trunc n (a₁ = a₂)) : tconcat tidp p = p := by hinduction p; exact ap tr (idp_con _) @[hott] def tcon_tidp (p : trunc n (a₁ = a₂)) : tconcat p tidp = p := by hinduction p; refl @[hott] def left_tinv (p : trunc n (a₁ = a₂)) : tconcat (tinverse p) p = tidp := by hinduction p; exact ap tr (con.left_inv _) @[hott] def right_tinv (p : trunc n (a₁ = a₂)) : tconcat p (tinverse p) = tidp := by hinduction p; exact ap tr (con.right_inv _) @[hott] def tap (f : A → B) (p : trunc n (a₁ = a₂)) : trunc n (f a₁ = f a₂) := trunc_functor _ (ap f) p @[hott] def tap_tidp (f : A → B) : tap f (@tidp n A a₁) = tidp := idp @[hott] def tap_tcon (f : A → B) (p : trunc n (a₁ = a₂)) (q : trunc n (a₂ = a₃)) : tap f (tconcat p q) = tconcat (tap f p) (tap f q) := by hinduction p; hinduction q; exact ap tr (ap_con _ _ _) /- characterization of equality in truncated types -/ @[hott] protected def code (n : ℕ₋₂) (aa aa' : trunc n.+1 A) : trunctype.{u} n := by hinduction aa with a; hinduction aa' with a'; exact trunctype.mk' n (trunc n (a = a')) @[hott] protected def encode {n : ℕ₋₂} {aa aa' : trunc n.+1 A} : aa = aa' → trunc.code n aa aa' := begin intro p, induction p, hinduction aa with a, exact tr idp end @[hott] protected def decode {n : ℕ₋₂} (aa aa' : trunc n.+1 A) : trunc.code n aa aa' → aa = aa' := begin hinduction aa' with a', hinduction aa with a, dsimp [trunc.code, trunc.rec_on], intro x, hinduction x with p, exact ap tr p, end @[hott] def trunc_eq_equiv (n : ℕ₋₂) (aa aa' : trunc n.+1 A) : aa = aa' ≃ trunc.code n aa aa' := begin fapply equiv.MK, { apply trunc.encode}, { apply trunc.decode}, { hinduction aa', hinduction aa, intro x, hinduction x with p, induction p, refl }, { intro p, hinduction p, hinduction aa, refl }, end @[hott] def tr_eq_tr_equiv (n : ℕ₋₂) (a a' : A) : (tr a = tr a' :> trunc n.+1 A) ≃ trunc n (a = a') := trunc_eq_equiv _ _ _ @[hott] def trunc_eq {n : ℕ₋₂} {a a' : A} (p : trunc n (a = a')) :tr a = tr a' :> trunc n.+1 A := (tr_eq_tr_equiv _ _ _)⁻¹ᵉ.to_fun p @[hott] def code_mul {n : ℕ₋₂} {aa₁ aa₂ aa₃ : trunc n.+1 A} (g : trunc.code n aa₁ aa₂) (h : trunc.code n aa₂ aa₃) : trunc.code n aa₁ aa₃ := begin hinduction aa₁ with a₁, hinduction aa₂ with a₂, hinduction aa₃ with a₃, apply tconcat g h, end /- encode preserves concatenation -/ @[hott] def encode_con' {n : ℕ₋₂} {aa₁ aa₂ aa₃ : trunc n.+1 A} (p : aa₁ = aa₂) (q : aa₂ = aa₃) : trunc.encode (p ⬝ q) = code_mul (trunc.encode p) (trunc.encode q) := begin induction p, induction q, hinduction aa₁ with a₁, refl end @[hott] def encode_con {n : ℕ₋₂} {a₁ a₂ a₃ : A} (p : tr a₁ = tr a₂ :> trunc (n.+1) A) (q : tr a₂ = tr a₃ :> trunc (n.+1) A) : trunc.encode (p ⬝ q) = tconcat (trunc.encode p) (trunc.encode q) := encode_con' p q /- the principle of unique choice -/ @[hott] def unique_choice {P : A → Type _} [H : Πa, is_prop (P a)] (f : Πa, ∥ P a ∥) (a : A) : P a := (trunc_equiv _ _).to_fun (f a) /- transport over a truncated family -/ @[hott] def trunc_transport {a a' : A} {P : A → Type _} (p : a = a') (n : ℕ₋₂) (x : P a) : transport (λa, trunc n (P a)) p (tr x) = tr (p ▸ x) := by induction p; refl /- pathover over a truncated family -/ @[hott] def trunc_pathover {A : Type _} {B : A → Type _} {n : ℕ₋₂} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : @tr n _ b =[p; λa, trunc n (B a)] @tr n _ b' := by induction q; constructor /- truncations preserve truncatedness -/ @[hott, instance, priority 500] def is_trunc_trunc_of_is_trunc (A : Type _) (n m : ℕ₋₂) [H : is_trunc n A] : is_trunc n (trunc m A) := begin unfreezeI; induction n with n IH generalizing A m H, { napply is_contr_equiv_closed, { symmetry, napply trunc_equiv, applyI (@is_trunc_of_le _ -2), apply minus_two_le}, apply_instance }, { induction m with m, { apply (@is_trunc_of_le _ -2), apply minus_two_le}, { apply is_trunc_succ_intro, intros aa aa', hinduction aa, hinduction aa', apply is_trunc_equiv_closed_rev, { apply tr_eq_tr_equiv }, { apply IH }}} end /- equivalences between truncated types (see also hit.trunc) -/ @[hott] def trunc_trunc_equiv_left (A : Type _) {n m : ℕ₋₂} (H : n ≤ m) : trunc n (trunc m A) ≃ trunc n A := begin haveI H2 := is_trunc_of_le (trunc n A) H, fapply equiv.MK, { intro x, hinduction x with x, hinduction x with x, exact tr x }, { intro x, hinduction x with x, exact tr (tr x) }, { intro x, hinduction x with x, refl }, { intro x, hinduction x with x, hinduction x with x, refl } end @[hott] def trunc_trunc_equiv_right (A : Type _) {n m : ℕ₋₂} (H : n ≤ m) : trunc m (trunc n A) ≃ trunc n A := begin napply trunc_equiv, exact is_trunc_of_le _ H, end @[hott] def trunc_equiv_trunc_of_le {n m : ℕ₋₂} {A B : Type _} (H : n ≤ m) (f : trunc m A ≃ trunc m B) : trunc n A ≃ trunc n B := (trunc_trunc_equiv_left A H)⁻¹ᵉ ⬝e trunc_equiv_trunc n f ⬝e trunc_trunc_equiv_left B H @[hott] def trunc_trunc_equiv_trunc_trunc (n m : ℕ₋₂) (A : Type _) : trunc n (trunc m A) ≃ trunc m (trunc n A) := begin fapply equiv.MK; intro x, { hinduction x with x, hinduction x with x, exact tr (tr x) }, { hinduction x with x, hinduction x with x, exact tr (tr x) }, { hinduction x with x, hinduction x with x, refl }, { hinduction x with x, hinduction x with x, refl } end @[hott] theorem is_trunc_trunc_of_le (A : Type _) (n : ℕ₋₂) {m k : ℕ₋₂} (H : m ≤ k) [is_trunc n (trunc k A)] : is_trunc n (trunc m A) := begin apply is_trunc_equiv_closed, { apply trunc_trunc_equiv_left, exact H }, apply_instance end @[hott] def trunc_functor_homotopy {X Y : Type _} (n : ℕ₋₂) {f g : X → Y} (p : f ~ g) (x : trunc n X) : trunc_functor n f x = trunc_functor n g x := begin hinduction x with x, exact ap tr (p x) end @[hott] def trunc_functor_homotopy_of_le {n k : ℕ₋₂} {A B : Type _} (f : A → B) (H : n ≤ k) : to_fun (trunc_trunc_equiv_left B H) ∘ trunc_functor n (trunc_functor k f) ∘ to_fun (trunc_trunc_equiv_left A H)⁻¹ᵉ ~ trunc_functor n f := begin intro x, hinduction x with x, refl end @[hott] def is_equiv_trunc_functor_of_le {n k : ℕ₋₂} {A B : Type _} (f : A → B) (H : n ≤ k) [Hf : is_equiv (trunc_functor k f)] : is_equiv (trunc_functor n f) := is_equiv_of_equiv_of_homotopy (trunc_equiv_trunc_of_le H (equiv.mk (trunc_functor k f) Hf)) (trunc_functor_homotopy_of_le f H) /- trunc_functor preserves surjectivity -/ --set_option trace.hinduction true @[hott] def is_surjective_trunc_functor {A B : Type _} (n : ℕ₋₂) (f : A → B) [H : is_surjective f] : is_surjective (trunc_functor n f) := begin cases n with n; intro b, { exact tr (fiber.mk (center _) (is_prop.elim _ _)) }, { haveI : Πb, is_trunc n.+1 (image (trunc_functor n.+1 f) b), { intro b, exact is_trunc_of_le _ (minus_one_le_succ _) }, unfreezeI; hinduction b with b, hinduction H b with x p, induction p with a p, exact tr (fiber.mk (tr a) (ap tr p)) } end /- truncation of pointed types -/ @[hott] def ptrunc (n : ℕ₋₂) (X : Type*) : Type* := ⟨trunc n X, tr pt⟩ @[hott] instance is_trunc_ptrunc (n : ℕ₋₂) (X : Type*) : is_trunc n (ptrunc n X) := is_trunc_trunc n X @[hott] def pttrunc (n : ℕ₋₂) (X : Type*) : n-Type* := ptrunctype.mk (ptrunc n X) (is_trunc_trunc n X) /- pointed maps involving ptrunc -/ @[hott] def ptrunc_functor {X Y : Type*} (n : ℕ₋₂) (f : X →* Y) : ptrunc n X →* ptrunc n Y := pmap.mk (trunc_functor n f) (ap tr (respect_pt f)) @[hott] def ptr (n : ℕ₋₂) (A : Type*) : A →* ptrunc n A := pmap.mk tr idp @[hott] def puntrunc (n : ℕ₋₂) (A : Type*) [is_trunc n A] : ptrunc n A →* A := pmap.mk untrunc_of_is_trunc idp @[hott] def ptrunc.elim (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] (f : X →* Y) : ptrunc n X →* Y := pmap.mk (trunc.elim f) (respect_pt f) /- pointed equivalences involving ptrunc -/ @[hott] def ptrunc_pequiv_ptrunc (n : ℕ₋₂) {X Y : Type*} (H : X ≃* Y) : ptrunc n X ≃* ptrunc n Y := pequiv_of_equiv (trunc_equiv_trunc n (equiv_of_pequiv H)) (ap tr (respect_pt H.to_pmap)) @[hott] def ptrunc_pequiv (n : ℕ₋₂) (X : Type*) [H : is_trunc n X] : ptrunc n X ≃* X := pequiv_of_equiv (trunc_equiv n X) idp @[hott] def ptrunc_ptrunc_pequiv_left (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : ptrunc n (ptrunc m A) ≃* ptrunc n A := pequiv_of_equiv (trunc_trunc_equiv_left A H) idp @[hott] def ptrunc_ptrunc_pequiv_right (A : Type*) {n m : ℕ₋₂} (H : n ≤ m) : ptrunc m (ptrunc n A) ≃* ptrunc n A := pequiv_of_equiv (trunc_trunc_equiv_right A H) idp @[hott] def ptrunc_pequiv_ptrunc_of_le {n m : ℕ₋₂} {A B : Type*} (H : n ≤ m) (f : ptrunc m A ≃* ptrunc m B) : ptrunc n A ≃* ptrunc n B := (ptrunc_ptrunc_pequiv_left A H)⁻¹ᵉ* ⬝e* ptrunc_pequiv_ptrunc n f ⬝e* ptrunc_ptrunc_pequiv_left B H @[hott] def ptrunc_ptrunc_pequiv_ptrunc_ptrunc (n m : ℕ₋₂) (A : Type*) : ptrunc n (ptrunc m A) ≃* ptrunc m (ptrunc n A) := pequiv_of_equiv (trunc_trunc_equiv_trunc_trunc n m A) idp @[hott] def loop_ptrunc_pequiv (n : ℕ₋₂) (A : Type*) : Ω (ptrunc (n+1) A) ≃* ptrunc n (Ω A) := pequiv_of_equiv (tr_eq_tr_equiv _ _ _) idp @[hott] def loop_ptrunc_pequiv_con {n : ℕ₋₂} {A : Type*} (p q : Ω (ptrunc (n+1) A)) : (loop_ptrunc_pequiv n A).to_pmap (p ⬝ q) = tconcat ((loop_ptrunc_pequiv n A).to_pmap p) ((loop_ptrunc_pequiv n A).to_pmap q) := encode_con p q @[hott] def loopn_ptrunc_pequiv (n : ℕ₋₂) (k : ℕ) (A : Type*) : Ω[k] (ptrunc (n+k) A) ≃* ptrunc n (Ω[k] A) := begin induction k with k IH generalizing n, { refl }, { refine _ ⬝e* loop_ptrunc_pequiv n (Ω[k] A), change Ω (Ω[k] (ptrunc (n + succ k) A)) ≃* Ω (ptrunc (n + 1) (Ω[k] A)), apply loop_pequiv_loop, refine _ ⬝e* IH (n.+1), exact loopn_pequiv_loopn k (pequiv_of_eq (ap (λn, ptrunc n A) (succ_add_nat _ _)⁻¹ᵖ)) } end @[hott] def loopn_ptrunc_pequiv_con {n : ℕ₋₂} {k : ℕ} {A : Type*} (p q : Ω[succ k] (ptrunc (n+nat.succ k) A)) : (loopn_ptrunc_pequiv n (succ k) A).to_pmap (p ⬝ q) = tconcat ((loopn_ptrunc_pequiv n (succ k) A).to_pmap p) ((loopn_ptrunc_pequiv n (succ k) A).to_pmap q) := begin refine _ ⬝ loop_ptrunc_pequiv_con _ _, exact ap (loop_ptrunc_pequiv _ _).to_fun (loop_pequiv_loop_con _ _ _) end @[hott] def loopn_ptrunc_pequiv_inv_con {n : ℕ₋₂} {k : ℕ} {A : Type*} (p q : ptrunc n (Ω[succ k] A)) : (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ*.to_fun (tconcat p q) = (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ*.to_fun p ⬝ (loopn_ptrunc_pequiv n (succ k) A)⁻¹ᵉ*.to_fun q := equiv.inv_preserve_binary (loopn_ptrunc_pequiv n (succ k) A).to_equiv concat tconcat (@loopn_ptrunc_pequiv_con n k A) p q /- pointed homotopies involving ptrunc -/ @[hott] def ptrunc_functor_pcompose {X Y Z : Type*} (n : ℕ₋₂) (g : Y →* Z) (f : X →* Y) : ptrunc_functor n (g ∘* f) ~* ptrunc_functor n g ∘* ptrunc_functor n f := begin fapply phomotopy.mk, { exact trunc_functor_compose n g f }, { refine idp_con _ ⬝ _, refine whisker_right _ (ap_compose' _ _ _) ⬝ _, refine whisker_right _ (ap_compose tr g _) ⬝ _, exact (ap_con _ _ _)⁻¹ }, end @[hott] def ptrunc_functor_pid (X : Type*) (n : ℕ₋₂) : ptrunc_functor n (pid X) ~* pid (ptrunc n X) := begin fapply phomotopy.mk, { apply trunc_functor_id}, { refl }, end @[hott] def ptrunc_functor_pcast {X Y : Type*} (n : ℕ₋₂) (p : X = Y) : ptrunc_functor n (pcast p) ~* pcast (ap (ptrunc n) p) := begin fapply phomotopy.mk, { intro x, refine trunc_functor_cast _ _ _ ⬝ _, refine ap010 (@hott.eq.cast (ptrunc n X) (@ptrunc n Y)) _ x, refine ap_compose' _ _ _ ⬝ _ ⬝ ap_compose _ _ _, refl }, { induction p, refl }, end @[hott] def ptrunc_functor_phomotopy {X Y : Type*} (n : ℕ₋₂) {f g : X →* Y} (p : f ~* g) : ptrunc_functor n f ~* ptrunc_functor n g := begin fapply phomotopy.mk, { exact trunc_functor_homotopy n p}, { refine (ap_con _ _ _)⁻¹ ⬝ _, exact ap02 tr (to_homotopy_pt p)}, end @[hott] def pcast_ptrunc (n : ℕ₋₂) {A B : Type*} (p : A = B) : pcast (ap (ptrunc n) p) ~* ptrunc_functor n (pcast p) := begin fapply phomotopy.mk, { intro a, induction p, exact (trunc_functor_id _ _ _)⁻¹ }, { induction p, refl } end @[hott] def ptrunc_elim_ptr (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] (f : X →* Y) : ptrunc.elim n f ∘* ptr n X ~* f := begin fapply phomotopy.mk, { refl }, { refl } end @[hott] def ptrunc_elim_phomotopy (n : ℕ₋₂) {X Y : Type*} [is_trunc n Y] {f g : X →* Y} (H : f ~* g) : ptrunc.elim n f ~* ptrunc.elim n g := begin fapply phomotopy.mk, { intro x, hinduction x with x, exact H x }, { exact to_homotopy_pt H } end @[hott] def ap1_ptrunc_functor (n : ℕ₋₂) {A B : Type*} (f : A →* B) : Ω→ (ptrunc_functor (n.+1) f) ∘* (loop_ptrunc_pequiv n A)⁻¹ᵉ*.to_pmap ~* (loop_ptrunc_pequiv n B)⁻¹ᵉ*.to_pmap ∘* ptrunc_functor n (Ω→ f) := begin fapply phomotopy.mk, { intro p, hinduction p with p, refine ((ap_inv _ _)⁻¹ ◾ (ap_compose _ _ _)⁻¹ ◾ idp) ⬝ _ ⬝ (ap_con _ _ _)⁻¹ᵖ, apply whisker_right, refine _ ⬝ (ap_con _ _ _)⁻¹ᵖ, exact whisker_left _ (ap_compose' _ _ _)⁻¹ᵖ }, { induction B with B b, induction f with f p, dsimp at f, dsimp at p, hinduction p, refl } end @[hott] def ap1_ptrunc_elim (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc (n.+1) B] : Ω→ (ptrunc.elim (n.+1) f) ∘* (loop_ptrunc_pequiv n A)⁻¹ᵉ*.to_pmap ~* ptrunc.elim n (Ω→ f) := begin fapply phomotopy.mk, { intro p, hinduction p with p, exact idp ◾ (ap_compose _ _ _)⁻¹ ◾ idp }, { refl } end @[hott] def ap1_ptr (n : ℕ₋₂) (A : Type*) : Ω→ (ptr (n.+1) A) ~* (loop_ptrunc_pequiv n A)⁻¹ᵉ*.to_pmap ∘* ptr n (Ω A) := begin fapply phomotopy.mk, { intro p, apply idp_con }, { refl } end @[hott] def ptrunc_elim_ptrunc_functor (n : ℕ₋₂) {A B C : Type*} (g : B →* C) (f : A →* B) [is_trunc n C] : ptrunc.elim n g ∘* ptrunc_functor n f ~* ptrunc.elim n (g ∘* f) := begin fapply phomotopy.mk, { intro x, hinduction x with a, refl }, { refine idp_con _ ⬝ whisker_right _ (ap_compose' _ _ _)⁻¹ᵖ }, end end trunc open trunc /- The truncated encode-decode method -/ namespace eq @[hott] def truncated_encode {k : ℕ₋₂} {A : Type _} {a₀ a : A} {code : A → Type _} [Πa, is_trunc k (code a)] (c₀ : code a₀) (p : trunc k (a₀ = a)) : code a := begin hinduction p with p, exact transport code p c₀ end @[hott] def truncated_encode_decode_method {k : ℕ₋₂} {A : Type _} (a₀ a : A) (code : A → Type _) [Πa, is_trunc k (code a)] (c₀ : code a₀) (decode : Π(a : A) (c : code a), trunc k (a₀ = a)) (encode_decode : Π(a : A) (c : code a), truncated_encode c₀ (decode a c) = c) (decode_encode : decode a₀ c₀ = tr idp) : trunc k (a₀ = a) ≃ code a := begin fapply equiv.MK, { exact truncated_encode c₀}, { apply decode}, { intro c, apply encode_decode}, { intro p, hinduction p with p, induction p, exact decode_encode}, end end eq /- some consequences for properties about functions (surjectivity etc.) -/ namespace function variables {A : Type _} {B : Type _} @[hott, instance] def is_surjective_of_is_equiv (f : A → B) [H : is_equiv f] : is_surjective f := λb, begin dsimp [image, image'], apply center end @[hott] def is_equiv_equiv_is_embedding_times_is_surjective (f : A → B) : is_equiv f ≃ (is_embedding f × is_surjective f) := equiv_of_is_prop (λH, (by resetI; apply_instance, by resetI; apply_instance)) (λP, prod.rec_on P (λH₁ H₂, by exactI is_equiv_of_is_surjective_of_is_embedding _)) /- @[hott] theorem 8.8.1: A function is an equivalence if it's an embedding and it's action on sets is an surjection -/ @[hott] def is_equiv_of_is_surjective_trunc_of_is_embedding {A B : Type _} (f : A → B) [H : is_embedding f] [H' : is_surjective (trunc_functor 0 f)] : is_equiv f := have is_surjective f, begin intro b, hinduction H' (tr b) with x p, hinduction p with a p, hinduction a with a, dsimp [trunc_functor] at p, hinduction ((tr_eq_tr_equiv _ _ _).to_fun p) with x q, exact image.mk a q end, by exactI is_equiv_of_is_surjective_of_is_embedding f /- Corollary 8.8.2: A function f is an equivalence if Ωf and trunc_functor 0 f are equivalences -/ @[hott] def is_equiv_of_is_equiv_ap1_of_is_equiv_trunc {A B : Type _} (f : A → B) [H : Πa, is_equiv (ap1 (pmap_of_map f a))] [H' : is_equiv (trunc_functor 0 f)] : is_equiv f := have is_embedding f, begin intros a a', apply is_equiv_of_imp_is_equiv, intro p, have q := ap (@tr 0 _) p, have r := @eq_of_fn_eq_fn' _ _ (trunc_functor 0 f) _ (tr a) (tr a') q, hinduction (tr_eq_tr_equiv _ _ _).to_fun r with x s, induction s, apply is_equiv.homotopy_closed (ap1 (pmap_of_map f a)), intro p, apply idp_con end, by exactI is_equiv_of_is_surjective_trunc_of_is_embedding f -- Whitehead's principle itself is in homotopy.homotopy_group, since it needs the @[hott] def of -- a homotopy group. end function end hott
b9ddc58508cef15cd08d6a15b23cbd4d4ea7b4fd
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/metric_space/hausdorff_distance.lean
1362de6fc1f5f1719bf2483804448d6e35821a37
[ "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
52,591
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.isometry import topology.instances.ennreal import analysis.specific_limits /-! # Hausdorff distance The Hausdorff distance on subsets of a metric (or emetric) space. Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d` such that any point `s` is within `d` of a point in `t`, and conversely. This quantity is often infinite (think of `s` bounded and `t` unbounded), and therefore better expressed in the setting of emetric spaces. ## Main definitions This files introduces: * `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space * `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space * Versions of these notions on metric spaces, called respectively `inf_dist` and `Hausdorff_dist` * `thickening δ s`, the open thickening by radius `δ` of a set `s` in a pseudo emetric space. * `cthickening δ s`, the closed thickening by radius `δ` of a set `s` in a pseudo emetric space. -/ noncomputable theory open_locale classical nnreal ennreal topological_space universes u v w open classical set function topological_space filter namespace emetric section inf_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t : set α} {Φ : α → β} /-! ### Distance of a point to a set as a function into `ℝ≥0∞`. -/ /-- The minimal edistance of a point to a set -/ def inf_edist (x : α) (s : set α) : ℝ≥0∞ := ⨅ y ∈ s, edist x y @[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ := infi_emptyset lemma le_inf_edist {d} : d ≤ inf_edist x s ↔ ∀ y ∈ s, d ≤ edist x y := by simp only [inf_edist, le_infi_iff] /-- The edist to a union is the minimum of the edists -/ @[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t := infi_union /-- The edist to a singleton is the edistance to the single point of this singleton -/ @[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y := infi_singleton /-- The edist to a set is bounded above by the edist to any of its points -/ lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y := binfi_le _ h /-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/ lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 := nonpos_iff_eq_zero.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h /-- The edist is monotonous with respect to inclusion -/ lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s := infi_le_infi_of_subset h /-- The edist to a set is `< r` iff there exists a point in the set at edistance `< r` -/ lemma inf_edist_lt_iff {r : ℝ≥0∞} : inf_edist x s < r ↔ ∃ y ∈ s, edist x y < r := by simp_rw [inf_edist, infi_lt_iff] /-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and the edist from `x` to `y` -/ lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y := calc (⨅ z ∈ s, edist x z) ≤ ⨅ z ∈ s, edist y z + edist x y : binfi_le_binfi $ λ z hz, (edist_triangle _ _ _).trans_eq (add_comm _ _) ... = (⨅ z ∈ s, edist y z) + edist x y : by simp only [ennreal.infi_add] /-- The edist to a set depends continuously on the point -/ @[continuity] lemma continuous_inf_edist : continuous (λx, inf_edist x s) := continuous_of_le_add_edist 1 (by simp) $ by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff] /-- The edist to a set and to its closure coincide -/ lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s := begin refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _, refine ennreal.le_of_forall_pos_le_add (λε εpos h, _), have ε0 : 0 < (ε / 2 : ℝ≥0∞) := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2, from ennreal.lt_add_right h.ne ε0.ne', rcases inf_edist_lt_iff.mp this with ⟨y, ycs, hy⟩, -- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2 rcases emetric.mem_closure_iff.1 ycs (ε/2) ε0 with ⟨z, zs, dyz⟩, -- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2 calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add (le_of_lt hy) (le_of_lt dyz) ... = inf_edist x (closure s) + ↑ε : by rw [add_assoc, ennreal.add_halves] end /-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/ lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 := ⟨λ h, by { rw ← inf_edist_closure, exact inf_edist_zero_of_mem h }, λ h, emetric.mem_closure_iff.2 $ λ ε εpos, inf_edist_lt_iff.mp $ by rwa h⟩ /-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/ lemma mem_iff_inf_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 := begin convert ← mem_closure_iff_inf_edist_zero, exact h.closure_eq end lemma disjoint_closed_ball_of_lt_inf_edist {r : ℝ≥0∞} (h : r < inf_edist x s) : disjoint (closed_ball x r) s := begin rw disjoint_left, assume y hy h'y, apply lt_irrefl (inf_edist x s), calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem h'y ... ≤ r : by rwa [mem_closed_ball, edist_comm] at hy ... < inf_edist x s : h end /-- The infimum edistance is invariant under isometries -/ lemma inf_edist_image (hΦ : isometry Φ) : inf_edist (Φ x) (Φ '' t) = inf_edist x t := by simp only [inf_edist, infi_image, hΦ.edist_eq] lemma _root_.is_open.exists_Union_is_closed {U : set α} (hU : is_open U) : ∃ F : ℕ → set α, (∀ n, is_closed (F n)) ∧ (∀ n, F n ⊆ U) ∧ ((⋃ n, F n) = U) ∧ monotone F := begin obtain ⟨a, a_pos, a_lt_one⟩ : ∃ (a : ℝ≥0∞), 0 < a ∧ a < 1 := exists_between (ennreal.zero_lt_one), let F := λ (n : ℕ), (λ x, inf_edist x Uᶜ) ⁻¹' (Ici (a^n)), have F_subset : ∀ n, F n ⊆ U, { assume n x hx, have : inf_edist x Uᶜ ≠ 0 := ((ennreal.pow_pos a_pos _).trans_le hx).ne', contrapose! this, exact inf_edist_zero_of_mem this }, refine ⟨F, λ n, is_closed.preimage continuous_inf_edist is_closed_Ici, F_subset, _, _⟩, show monotone F, { assume m n hmn x hx, simp only [mem_Ici, mem_preimage] at hx ⊢, apply le_trans (ennreal.pow_le_pow_of_le_one a_lt_one.le hmn) hx }, show (⋃ n, F n) = U, { refine subset.antisymm (by simp only [Union_subset_iff, F_subset, forall_const]) (λ x hx, _), have : ¬(x ∈ Uᶜ), by simpa using hx, rw mem_iff_inf_edist_zero_of_closed hU.is_closed_compl at this, have B : 0 < inf_edist x Uᶜ, by simpa [pos_iff_ne_zero] using this, have : filter.tendsto (λ n, a^n) at_top (𝓝 0) := ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 a_lt_one, rcases ((tendsto_order.1 this).2 _ B).exists with ⟨n, hn⟩, simp only [mem_Union, mem_Ici, mem_preimage], exact ⟨n, hn.le⟩ }, end lemma _root_.is_compact.exists_inf_edist_eq_edist (hs : is_compact s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_edist x s = edist x y := begin have A : continuous (λ y, edist x y) := continuous_const.edist continuous_id, obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, ∀ z, z ∈ s → edist x y ≤ edist x z := hs.exists_forall_le hne A.continuous_on, exact ⟨y, ys, le_antisymm (inf_edist_le_edist_of_mem ys) (by rwa le_inf_edist)⟩ end end inf_edist --section /-! ### The Hausdorff distance as a function into `ℝ≥0∞`. -/ /-- The Hausdorff edistance between two sets is the smallest `r` such that each set is contained in the `r`-neighborhood of the other one -/ @[irreducible] def Hausdorff_edist {α : Type u} [pseudo_emetric_space α] (s t : set α) : ℝ≥0∞ := (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) lemma Hausdorff_edist_def {α : Type u} [pseudo_emetric_space α] (s t : set α) : Hausdorff_edist s t = (⨆ x ∈ s, inf_edist x t) ⊔ (⨆ y ∈ t, inf_edist y s) := by rw Hausdorff_edist section Hausdorff_edist variables {α : Type u} {β : Type v} [pseudo_emetric_space α] [pseudo_emetric_space β] {x y : α} {s t u : set α} {Φ : α → β} /-- The Hausdorff edistance of a set to itself vanishes -/ @[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 := begin simp only [Hausdorff_edist_def, sup_idem, ennreal.supr_eq_zero], exact λ x hx, inf_edist_zero_of_mem hx end /-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/ lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s := by unfold Hausdorff_edist; apply sup_comm /-- Bounding the Hausdorff edistance by bounding the edistance of any point in each set to the other set -/ lemma Hausdorff_edist_le_of_inf_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) : Hausdorff_edist s t ≤ r := begin simp only [Hausdorff_edist, sup_le_iff, supr_le_iff], exact ⟨H1, H2⟩ end /-- Bounding the Hausdorff edistance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_edist_le_of_mem_edist {r : ℝ≥0∞} (H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) : Hausdorff_edist s t ≤ r := begin refine Hausdorff_edist_le_of_inf_edist _ _, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_edist_le_edist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_edist_le_edist_of_mem ys) hy } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t := begin rw Hausdorff_edist_def, refine le_trans _ le_sup_left, exact le_bsupr x h end /-- If the Hausdorff distance is `<r`, then any point in one of the sets has a corresponding point at distance `<r` in the other set -/ lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ℝ≥0∞} (h : x ∈ s) (H : Hausdorff_edist s t < r) : ∃ y ∈ t, edist x y < r := inf_edist_lt_iff.mp $ calc inf_edist x t ≤ Hausdorff_edist s t : inf_edist_le_Hausdorff_edist_of_mem h ... < r : H /-- The distance from `x` to `s` or `t` is controlled in terms of the Hausdorff distance between `s` and `t` -/ lemma inf_edist_le_inf_edist_add_Hausdorff_edist : inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t := ennreal.le_of_forall_pos_le_add $ λε εpos h, begin have ε0 : (ε / 2 : ℝ≥0∞) ≠ 0 := by simpa [pos_iff_ne_zero] using εpos, have : inf_edist x s < inf_edist x s + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).1.ne ε0, rcases inf_edist_lt_iff.mp this with ⟨y, ys, dxy⟩, -- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2 have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 := ennreal.lt_add_right (ennreal.add_lt_top.1 h).2.ne ε0, rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩, -- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2 calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt ... ≤ edist x y + edist y z : edist_triangle _ _ _ ... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add dxy.le dyz.le ... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm, add_left_comm] end /-- The Hausdorff edistance is invariant under eisometries -/ lemma Hausdorff_edist_image (h : isometry Φ) : Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t := by simp only [Hausdorff_edist_def, supr_image, inf_edist_image h] /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_edist_le_ediam (hs : s.nonempty) (ht : t.nonempty) : Hausdorff_edist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_edist_le_of_mem_edist _ _, { intros z hz, exact ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { intros z hz, exact ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u := begin rw Hausdorff_edist_def, simp only [sup_le_iff, supr_le_iff], split, show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist s t + Hausdorff_edist t u : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xs) _, show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ Hausdorff_edist u t + Hausdorff_edist t s : add_le_add_right (inf_edist_le_Hausdorff_edist_of_mem xu) _ ... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm] end /-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/ lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t := calc Hausdorff_edist s t = 0 ↔ s ⊆ closure t ∧ t ⊆ closure s : by simp only [Hausdorff_edist_def, ennreal.sup_eq_zero, ennreal.supr_eq_zero, ← mem_closure_iff_inf_edist_zero, subset_def] ... ↔ closure s = closure t : ⟨λ h, subset.antisymm (closure_minimal h.1 is_closed_closure) (closure_minimal h.2 is_closed_closure), λ h, ⟨h ▸ subset_closure, h.symm ▸ subset_closure⟩⟩ /-- The Hausdorff edistance between a set and its closure vanishes -/ @[simp, priority 1100] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_closure] /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t := begin refine le_antisymm _ _, { calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle ... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] }, { calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle ... = Hausdorff_edist (closure s) t : by simp } end /-- Replacing a set by its closure does not change the Hausdorff edistance. -/ @[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t := by simp [@Hausdorff_edist_comm _ _ s _] /-- The Hausdorff edistance between sets or their closures is the same -/ @[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t := by simp /-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/ lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) : Hausdorff_edist s t = 0 ↔ s = t := by rw [Hausdorff_edist_zero_iff_closure_eq_closure, hs.closure_eq, ht.closure_eq] /-- The Haudorff edistance to the empty set is infinite -/ lemma Hausdorff_edist_empty (ne : s.nonempty) : Hausdorff_edist s ∅ = ∞ := begin rcases ne with ⟨x, xs⟩, have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs, simpa using this, end /-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/ lemma nonempty_of_Hausdorff_edist_ne_top (hs : s.nonempty) (fin : Hausdorff_edist s t ≠ ⊤) : t.nonempty := t.eq_empty_or_nonempty.elim (λ ht, (fin $ ht.symm ▸ Hausdorff_edist_empty hs).elim) id lemma empty_or_nonempty_of_Hausdorff_edist_ne_top (fin : Hausdorff_edist s t ≠ ⊤) : s = ∅ ∧ t = ∅ ∨ s.nonempty ∧ t.nonempty := begin cases s.eq_empty_or_nonempty with hs hs, { cases t.eq_empty_or_nonempty with ht ht, { exact or.inl ⟨hs, ht⟩ }, { rw Hausdorff_edist_comm at fin, exact or.inr ⟨nonempty_of_Hausdorff_edist_ne_top ht fin, ht⟩ } }, { exact or.inr ⟨hs, nonempty_of_Hausdorff_edist_ne_top hs fin⟩ } end end Hausdorff_edist -- section end emetric --namespace /-! Now, we turn to the same notions in metric spaces. To avoid the difficulties related to `Inf` and `Sup` on `ℝ` (which is only conditionally complete), we use the notions in `ℝ≥0∞` formulated in terms of the edistance, and coerce them to `ℝ`. Then their properties follow readily from the corresponding properties in `ℝ≥0∞`, modulo some tedious rewriting of inequalities from one to the other. -/ namespace metric section variables {α : Type u} {β : Type v} [pseudo_metric_space α] [pseudo_metric_space β] {s t u : set α} {x y : α} {Φ : α → β} open emetric /-! ### Distance of a point to a set as a function into `ℝ`. -/ /-- The minimal distance of a point to a set -/ def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s) /-- the minimal distance is always nonnegative -/ lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist] /-- the minimal distance to the empty set is 0 (if you want to have the more reasonable value ∞ instead, use `inf_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 := by simp [inf_dist] /-- In a metric space, the minimal edistance to a nonempty set is finite -/ lemma inf_edist_ne_top (h : s.nonempty) : inf_edist x s ≠ ⊤ := begin rcases h with ⟨y, hy⟩, apply lt_top_iff_ne_top.1, calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy ... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _) end /-- The minimal distance of a point to a set containing it vanishes -/ lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 := by simp [inf_edist_zero_of_mem h, inf_dist] /-- The minimal distance to a singleton is the distance to the unique point in this singleton -/ @[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y := by simp [inf_dist, inf_edist, dist_edist] /-- The minimal distance to a set is bounded by the distance to any point in this set -/ lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y := begin rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ⟨_, h⟩) (edist_ne_top _ _)], exact inf_edist_le_edist_of_mem h end /-- The minimal distance is monotonous with respect to inclusion -/ lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s.nonempty) : inf_dist x t ≤ inf_dist x s := begin have ht : t.nonempty := hs.mono h, rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)], exact inf_edist_le_inf_edist_of_subset h end /-- The minimal distance to a set is `< r` iff there exists a point in this set at distance `< r` -/ lemma inf_dist_lt_iff {r : ℝ} (hs : s.nonempty) : inf_dist x s < r ↔ ∃ y ∈ s, dist x y < r := by simp_rw [inf_dist, ← ennreal.lt_of_real_iff_to_real_lt (inf_edist_ne_top hs), inf_edist_lt_iff, ennreal.lt_of_real_iff_to_real_lt (edist_ne_top _ _), ← dist_edist] /-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo the distance between `x` and `y` -/ lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y := begin cases s.eq_empty_or_nonempty with hs hs, { simp [hs, dist_nonneg] }, { rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _), ennreal.to_real_le_to_real (inf_edist_ne_top hs)], { exact inf_edist_le_inf_edist_add_edist }, { simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }} end lemma not_mem_of_dist_lt_inf_dist (h : dist x y < inf_dist x s) : y ∉ s := λ hy, h.not_le $ inf_dist_le_dist_of_mem hy lemma disjoint_ball_inf_dist : disjoint (ball x (inf_dist x s)) s := disjoint_left.2 $ λ y hy, not_mem_of_dist_lt_inf_dist $ calc dist x y = dist y x : dist_comm _ _ ... < inf_dist x s : hy lemma disjoint_closed_ball_of_lt_inf_dist {r : ℝ} (h : r < inf_dist x s) : disjoint (closed_ball x r) s := disjoint_ball_inf_dist.mono_left $ closed_ball_subset_ball h variable (s) /-- The minimal distance to a set is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set is uniformly continuous in point -/ lemma uniform_continuous_inf_dist_pt : uniform_continuous (λx, inf_dist x s) := (lipschitz_inf_dist_pt s).uniform_continuous /-- The minimal distance to a set is continuous in point -/ @[continuity] lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) := (uniform_continuous_inf_dist_pt s).continuous variable {s} /-- The minimal distance to a set and its closure coincide -/ lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s := by simp [inf_dist, inf_edist_closure] /-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/ lemma mem_closure_iff_inf_dist_zero (h : s.nonempty) : x ∈ closure s ↔ inf_dist x s = 0 := by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.mem_iff_inf_dist_zero (h : is_closed s) (hs : s.nonempty) : x ∈ s ↔ inf_dist x s = 0 := by rw [←mem_closure_iff_inf_dist_zero hs, h.closure_eq] /-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/ lemma _root_.is_closed.not_mem_iff_inf_dist_pos (h : is_closed s) (hs : s.nonempty) : x ∉ s ↔ 0 < inf_dist x s := begin rw ← not_iff_not, push_neg, simp [h.mem_iff_inf_dist_zero hs, le_antisymm_iff, inf_dist_nonneg], end /-- The infimum distance is invariant under isometries -/ lemma inf_dist_image (hΦ : isometry Φ) : inf_dist (Φ x) (Φ '' t) = inf_dist x t := by simp [inf_dist, inf_edist_image hΦ] lemma inf_dist_inter_closed_ball_of_mem (h : y ∈ s) : inf_dist x (s ∩ closed_ball x (dist y x)) = inf_dist x s := begin replace h : y ∈ s ∩ closed_ball x (dist y x) := ⟨h, mem_closed_ball.2 le_rfl⟩, refine le_antisymm _ (inf_dist_le_inf_dist_of_subset (inter_subset_left _ _) ⟨y, h⟩), refine not_lt.1 (λ hlt, _), rcases (inf_dist_lt_iff ⟨y, h.1⟩).mp hlt with ⟨z, hzs, hz⟩, cases le_or_lt (dist z x) (dist y x) with hle hlt, { exact hz.not_le (inf_dist_le_dist_of_mem ⟨hzs, hle⟩) }, { rw [dist_comm z, dist_comm y] at hlt, exact (hlt.trans hz).not_le (inf_dist_le_dist_of_mem h) } end lemma _root_.is_compact.exists_inf_dist_eq_dist (h : is_compact s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_dist x s = dist x y := let ⟨y, hys, hy⟩ := h.exists_inf_edist_eq_edist hne x in ⟨y, hys, by rw [inf_dist, dist_edist, hy]⟩ lemma _root_.is_closed.exists_inf_dist_eq_dist [proper_space α] (h : is_closed s) (hne : s.nonempty) (x : α) : ∃ y ∈ s, inf_dist x s = dist x y := begin rcases hne with ⟨z, hz⟩, rw ← inf_dist_inter_closed_ball_of_mem hz, set t := s ∩ closed_ball x (dist z x), have htc : is_compact t := (is_compact_closed_ball x (dist z x)).inter_left h, have htne : t.nonempty := ⟨z, hz, mem_closed_ball.2 le_rfl⟩, obtain ⟨y, ⟨hys, hyx⟩, hyd⟩ : ∃ y ∈ t, inf_dist x t = dist x y := htc.exists_inf_dist_eq_dist htne x, exact ⟨y, hys, hyd⟩ end lemma exists_mem_closure_inf_dist_eq_dist [proper_space α] (hne : s.nonempty) (x : α) : ∃ y ∈ closure s, inf_dist x s = dist x y := by simpa only [inf_dist_eq_closure] using is_closed_closure.exists_inf_dist_eq_dist hne.closure x lemma closed_ball_inf_dist_compl_subset_closure' {E : Type*} [semi_normed_group E] [normed_space ℝ E] {x : E} {s : set E} (hx : s ∈ 𝓝 x) (hs : s ≠ univ) : closed_ball x (inf_dist x sᶜ) ⊆ closure s := begin have hne : sᶜ.nonempty, from nonempty_compl.2 hs, have hpos : 0 < inf_dist x sᶜ, { rwa [← inf_dist_eq_closure, ← is_closed_closure.not_mem_iff_inf_dist_pos hne.closure, closure_compl, mem_compl_iff, not_not, mem_interior_iff_mem_nhds] }, rw ← closure_ball x hpos, apply closure_mono, rw [← le_eq_subset, ← is_compl_compl.disjoint_right_iff], exact disjoint_ball_inf_dist end lemma closed_ball_inf_dist_compl_subset_closure {E : Type*} [normed_group E] [normed_space ℝ E] {x : E} {s : set E} (hx : x ∈ s) (hs : s ≠ univ) : closed_ball x (inf_dist x sᶜ) ⊆ closure s := begin by_cases hx' : x ∈ closure sᶜ, { rw [mem_closure_iff_inf_dist_zero (nonempty_compl.2 hs)] at hx', simpa [hx'] using subset_closure hx }, { rw [closure_compl, mem_compl_iff, not_not, mem_interior_iff_mem_nhds] at hx', exact closed_ball_inf_dist_compl_subset_closure' hx' hs } end /-! ### Distance of a point to a set as a function into `ℝ≥0`. -/ /-- The minimal distance of a point to a set as a `ℝ≥0` -/ def inf_nndist (x : α) (s : set α) : ℝ≥0 := ennreal.to_nnreal (inf_edist x s) @[simp] lemma coe_inf_nndist : (inf_nndist x s : ℝ) = inf_dist x s := rfl /-- The minimal distance to a set (as `ℝ≥0`) is Lipschitz in point with constant 1 -/ lemma lipschitz_inf_nndist_pt (s : set α) : lipschitz_with 1 (λx, inf_nndist x s) := lipschitz_with.of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist /-- The minimal distance to a set (as `ℝ≥0`) is uniformly continuous in point -/ lemma uniform_continuous_inf_nndist_pt (s : set α) : uniform_continuous (λx, inf_nndist x s) := (lipschitz_inf_nndist_pt s).uniform_continuous /-- The minimal distance to a set (as `ℝ≥0`) is continuous in point -/ lemma continuous_inf_nndist_pt (s : set α) : continuous (λx, inf_nndist x s) := (uniform_continuous_inf_nndist_pt s).continuous /-! ### The Hausdorff distance as a function into `ℝ`. -/ /-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to be `0`, arbitrarily -/ def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t) /-- The Hausdorff distance is nonnegative -/ lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t := by simp [Hausdorff_dist] /-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance. -/ lemma Hausdorff_edist_ne_top_of_nonempty_of_bounded (hs : s.nonempty) (ht : t.nonempty) (bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ := begin rcases hs with ⟨cs, hcs⟩, rcases ht with ⟨ct, hct⟩, rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩, rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩, have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt), { apply Hausdorff_edist_le_of_mem_edist, { assume x xs, existsi [ct, hct], have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }, { assume x xt, existsi [cs, hcs], have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _), rwa [edist_dist, ennreal.of_real_le_of_real_iff], exact le_trans dist_nonneg this }}, exact ne_top_of_le_ne_top ennreal.of_real_ne_top this end /-- The Hausdorff distance between a set and itself is zero -/ @[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 := by simp [Hausdorff_dist] /-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/ lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s := by simp [Hausdorff_dist, Hausdorff_edist_comm] /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 := begin cases s.eq_empty_or_nonempty with h h, { simp [h] }, { simp [Hausdorff_dist, Hausdorff_edist_empty h] } end /-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable value ∞ instead, use `Hausdorff_edist`, which takes values in ℝ≥0∞) -/ @[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 := by simp [Hausdorff_dist_comm] /-- Bounding the Hausdorff distance by bounding the distance of any point in each set to the other set -/ lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) : Hausdorff_dist s t ≤ r := begin by_cases h1 : Hausdorff_edist s t = ⊤, { rwa [Hausdorff_dist, h1, ennreal.top_to_real] }, cases s.eq_empty_or_nonempty with hs hs, { rwa [hs, Hausdorff_dist_empty'] }, cases t.eq_empty_or_nonempty with ht ht, { rwa [ht, Hausdorff_dist_empty] }, have : Hausdorff_edist s t ≤ ennreal.of_real r, { apply Hausdorff_edist_le_of_inf_edist _ _, { assume x hx, have I := H1 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top ht) ennreal.of_real_ne_top] at I }, { assume x hx, have I := H2 x hx, rwa [inf_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real (inf_edist_ne_top hs) ennreal.of_real_ne_top] at I }}, rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr, ennreal.to_real_le_to_real h1 ennreal.of_real_ne_top] end /-- Bounding the Hausdorff distance by exhibiting, for any point in each set, another point in the other set at controlled distance -/ lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r) (H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) : Hausdorff_dist s t ≤ r := begin apply Hausdorff_dist_le_of_inf_dist hr, { assume x xs, rcases H1 x xs with ⟨y, yt, hy⟩, exact le_trans (inf_dist_le_dist_of_mem yt) hy }, { assume x xt, rcases H2 x xt with ⟨y, ys, hy⟩, exact le_trans (inf_dist_le_dist_of_mem ys) hy } end /-- The Hausdorff distance is controlled by the diameter of the union -/ lemma Hausdorff_dist_le_diam (hs : s.nonempty) (bs : bounded s) (ht : t.nonempty) (bt : bounded t) : Hausdorff_dist s t ≤ diam (s ∪ t) := begin rcases hs with ⟨x, xs⟩, rcases ht with ⟨y, yt⟩, refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _, { exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ }, { exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ } end /-- The distance to a set is controlled by the Hausdorff distance -/ lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ Hausdorff_dist s t := begin have ht : t.nonempty := nonempty_of_Hausdorff_edist_ne_top ⟨x, hx⟩ fin, rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin], exact inf_edist_le_Hausdorff_edist_of_mem hx end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r := begin have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H, have : Hausdorff_edist s t < ennreal.of_real r, { rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0), ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H }, rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩, rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr, exact ⟨y, hy, yr⟩ end /-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance `<r` of a point in the other set -/ lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r) (fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r := begin rw Hausdorff_dist_comm at H, rw Hausdorff_edist_comm at fin, simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin end /-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance between `s` and `t` -/ lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) : inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t := begin rcases empty_or_nonempty_of_Hausdorff_edist_ne_top fin with ⟨hs,ht⟩|⟨hs,ht⟩, { simp only [hs, ht, Hausdorff_dist_empty, inf_dist_empty, zero_add] }, rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top hs) fin, ennreal.to_real_le_to_real (inf_edist_ne_top ht)], { exact inf_edist_le_inf_edist_add_Hausdorff_edist }, { exact ennreal.add_ne_top.2 ⟨inf_edist_ne_top hs, fin⟩ } end /-- The Hausdorff distance is invariant under isometries -/ lemma Hausdorff_dist_image (h : isometry Φ) : Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t := by simp [Hausdorff_dist, Hausdorff_edist_image h] /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin by_cases Hausdorff_edist s u = ⊤, { calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h] ... ≤ Hausdorff_dist s t + Hausdorff_dist t u : add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) }, { have Dtu : Hausdorff_edist t u < ⊤ := calc Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle ... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm] ... < ⊤ : lt_top_iff_ne_top.mpr $ ennreal.add_ne_top.mpr ⟨fin, h⟩, rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist, ← ennreal.to_real_add fin Dtu.ne, ennreal.to_real_le_to_real h], { exact Hausdorff_edist_triangle }, { simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }} end /-- The Hausdorff distance satisfies the triangular inequality -/ lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) : Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u := begin rw Hausdorff_edist_comm at fin, have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin, simpa [add_comm, Hausdorff_dist_comm] using I end /-- The Hausdorff distance between a set and its closure vanish -/ @[simp, priority 1100] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Replacing a set by its closure does not change the Hausdorff distance. -/ @[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- The Hausdorff distance between two sets and their closures coincide -/ @[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t := by simp [Hausdorff_dist] /-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/ lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ closure s = closure t := by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] /-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/ lemma _root_.is_closed.Hausdorff_dist_zero_iff_eq (hs : is_closed s) (ht : is_closed t) (fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t := by simp [←Hausdorff_edist_zero_iff_eq_of_closed hs ht, Hausdorff_dist, ennreal.to_real_eq_zero_iff, fin] end --section section thickening variables {α : Type u} [pseudo_emetric_space α] open emetric /-- The (open) `δ`-thickening `thickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at distance less than `δ` from some point of `E`. -/ def thickening (δ : ℝ) (E : set α) : set α := {x : α | inf_edist x E < ennreal.of_real δ} /-- The (open) thickening equals the preimage of an open interval under `inf_edist`. -/ lemma thickening_eq_preimage_inf_edist (δ : ℝ) (E : set α) : thickening δ E = (λ x, inf_edist x E) ⁻¹' (Iio (ennreal.of_real δ)) := rfl /-- The (open) thickening is an open set. -/ lemma is_open_thickening {δ : ℝ} {E : set α} : is_open (thickening δ E) := continuous.is_open_preimage continuous_inf_edist _ is_open_Iio /-- The (open) thickening of the empty set is empty. -/ @[simp] lemma thickening_empty (δ : ℝ) : thickening δ (∅ : set α) = ∅ := by simp only [thickening, set_of_false, inf_edist_empty, not_top_lt] /-- The (open) thickening `thickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ lemma thickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : thickening δ₁ E ⊆ thickening δ₂ E := preimage_mono (Iio_subset_Iio (ennreal.of_real_le_of_real hle)) /-- The (open) thickening `thickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ lemma thickening_subset_of_subset (δ : ℝ) {E₁ E₂ : set α} (h : E₁ ⊆ E₂) : thickening δ E₁ ⊆ thickening δ E₂ := λ _ hx, lt_of_le_of_lt (inf_edist_le_inf_edist_of_subset h) hx lemma mem_thickening_iff_exists_edist_lt {δ : ℝ} (E : set α) (x : α) : x ∈ thickening δ E ↔ ∃ z ∈ E, edist x z < ennreal.of_real δ := inf_edist_lt_iff variables {X : Type u} [pseudo_metric_space X] /-- A point in a metric space belongs to the (open) `δ`-thickening of a subset `E` if and only if it is at distance less than `δ` from some point of `E`. -/ lemma mem_thickening_iff {δ : ℝ} (E : set X) (x : X) : x ∈ thickening δ E ↔ (∃ z ∈ E, dist x z < δ) := begin have key_iff : ∀ (z : X), edist x z < ennreal.of_real δ ↔ dist x z < δ, { intros z, rw dist_edist, have d_lt_top : edist x z < ∞, by simp only [edist_dist, ennreal.of_real_lt_top], have key := (@ennreal.of_real_lt_of_real_iff_of_nonneg ((edist x z).to_real) δ (ennreal.to_real_nonneg)), rwa ennreal.of_real_to_real d_lt_top.ne at key, }, simp_rw [mem_thickening_iff_exists_edist_lt, key_iff], end @[simp] lemma thickening_singleton (δ : ℝ) (x : X) : thickening δ ({x} : set X) = ball x δ := by { ext, simp [mem_thickening_iff] } /-- The (open) `δ`-thickening `thickening δ E` of a subset `E` in a metric space equals the union of balls of radius `δ` centered at points of `E`. -/ lemma thickening_eq_bUnion_ball {δ : ℝ} {E : set X} : thickening δ E = ⋃ x ∈ E, ball x δ := by { ext x, rw mem_Union₂, exact mem_thickening_iff E x, } lemma bounded.thickening {δ : ℝ} {E : set X} (h : bounded E) : bounded (thickening δ E) := begin refine bounded_iff_mem_bounded.2 (λ x hx, _), rcases h.subset_ball x with ⟨R, hR⟩, refine (bounded_iff_subset_ball x).2 ⟨R + δ, _⟩, assume y hy, rcases (mem_thickening_iff _ _).1 hy with ⟨z, zE, hz⟩, calc dist y x ≤ dist z x + dist y z : by { rw add_comm, exact dist_triangle _ _ _ } ... ≤ R + δ : add_le_add (hR zE) hz.le end end thickening --section section cthickening variables {α : Type*} [pseudo_emetric_space α] open emetric /-- The closed `δ`-thickening `cthickening δ E` of a subset `E` in a pseudo emetric space consists of those points that are at infimum distance at most `δ` from `E`. -/ def cthickening (δ : ℝ) (E : set α) : set α := {x : α | inf_edist x E ≤ ennreal.of_real δ} lemma mem_cthickening_of_edist_le (x y : α) (δ : ℝ) (E : set α) (h : y ∈ E) (h' : edist x y ≤ ennreal.of_real δ) : x ∈ cthickening δ E := (inf_edist_le_edist_of_mem h).trans h' lemma mem_cthickening_of_dist_le {α : Type*} [pseudo_metric_space α] (x y : α) (δ : ℝ) (E : set α) (h : y ∈ E) (h' : dist x y ≤ δ) : x ∈ cthickening δ E := begin apply mem_cthickening_of_edist_le x y δ E h, rw edist_dist, exact ennreal.of_real_le_of_real h', end lemma cthickening_eq_preimage_inf_edist (δ : ℝ) (E : set α) : cthickening δ E = (λ x, inf_edist x E) ⁻¹' (Iic (ennreal.of_real δ)) := rfl /-- The closed thickening is a closed set. -/ lemma is_closed_cthickening {δ : ℝ} {E : set α} : is_closed (cthickening δ E) := is_closed.preimage continuous_inf_edist is_closed_Iic /-- The closed thickening of the empty set is empty. -/ @[simp] lemma cthickening_empty (δ : ℝ) : cthickening δ (∅ : set α) = ∅ := by simp only [cthickening, ennreal.of_real_ne_top, set_of_false, inf_edist_empty, top_le_iff] lemma cthickening_of_nonpos {δ : ℝ} (hδ : δ ≤ 0) (E : set α) : cthickening δ E = closure E := by { ext x, simp [mem_closure_iff_inf_edist_zero, cthickening, ennreal.of_real_eq_zero.2 hδ] } /-- The closed thickening with radius zero is the closure of the set. -/ @[simp] lemma cthickening_zero (E : set α) : cthickening 0 E = closure E := cthickening_of_nonpos le_rfl E /-- The closed thickening `cthickening δ E` of a fixed subset `E` is an increasing function of the thickening radius `δ`. -/ lemma cthickening_mono {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : cthickening δ₁ E ⊆ cthickening δ₂ E := preimage_mono (Iic_subset_Iic.mpr (ennreal.of_real_le_of_real hle)) @[simp] lemma cthickening_singleton {α : Type*} [pseudo_metric_space α] (x : α) {δ : ℝ} (hδ : 0 ≤ δ) : cthickening δ ({x} : set α) = closed_ball x δ := by { ext y, simp [cthickening, edist_dist, ennreal.of_real_le_of_real_iff hδ] } lemma closed_ball_subset_cthickening_singleton {α : Type*} [pseudo_metric_space α] (x : α) (δ : ℝ) : closed_ball x δ ⊆ cthickening δ ({x} : set α) := begin rcases lt_or_le δ 0 with hδ|hδ, { simp only [closed_ball_eq_empty.mpr hδ, empty_subset] }, { simp only [cthickening_singleton x hδ] } end /-- The closed thickening `cthickening δ E` with a fixed thickening radius `δ` is an increasing function of the subset `E`. -/ lemma cthickening_subset_of_subset (δ : ℝ) {E₁ E₂ : set α} (h : E₁ ⊆ E₂) : cthickening δ E₁ ⊆ cthickening δ E₂ := λ _ hx, le_trans (inf_edist_le_inf_edist_of_subset h) hx lemma cthickening_subset_thickening {δ₁ : ℝ≥0} {δ₂ : ℝ} (hlt : (δ₁ : ℝ) < δ₂) (E : set α) : cthickening δ₁ E ⊆ thickening δ₂ E := λ _ hx, lt_of_le_of_lt hx ((ennreal.of_real_lt_of_real_iff (lt_of_le_of_lt δ₁.prop hlt)).mpr hlt) /-- The closed thickening `cthickening δ₁ E` is contained in the open thickening `thickening δ₂ E` if the radius of the latter is positive and larger. -/ lemma cthickening_subset_thickening' {δ₁ δ₂ : ℝ} (δ₂_pos : 0 < δ₂) (hlt : δ₁ < δ₂) (E : set α) : cthickening δ₁ E ⊆ thickening δ₂ E := λ _ hx, lt_of_le_of_lt hx ((ennreal.of_real_lt_of_real_iff δ₂_pos).mpr hlt) /-- The open thickening `thickening δ E` is contained in the closed thickening `cthickening δ E` with the same radius. -/ lemma thickening_subset_cthickening (δ : ℝ) (E : set α) : thickening δ E ⊆ cthickening δ E := by { intros x hx, rw [thickening, mem_set_of_eq] at hx, exact hx.le, } lemma thickening_subset_cthickening_of_le {δ₁ δ₂ : ℝ} (hle : δ₁ ≤ δ₂) (E : set α) : thickening δ₁ E ⊆ cthickening δ₂ E := (thickening_subset_cthickening δ₁ E).trans (cthickening_mono hle E) lemma bounded.cthickening {α : Type*} [pseudo_metric_space α] {δ : ℝ} {E : set α} (h : bounded E) : bounded (cthickening δ E) := begin have : bounded (thickening (max (δ + 1) 1) E) := h.thickening, apply bounded.mono _ this, exact cthickening_subset_thickening' (zero_lt_one.trans_le (le_max_right _ _)) ((lt_add_one _).trans_le (le_max_left _ _)) _ end lemma thickening_subset_interior_cthickening (δ : ℝ) (E : set α) : thickening δ E ⊆ interior (cthickening δ E) := (subset_interior_iff_open.mpr (is_open_thickening)).trans (interior_mono (thickening_subset_cthickening δ E)) lemma closure_thickening_subset_cthickening (δ : ℝ) (E : set α) : closure (thickening δ E) ⊆ cthickening δ E := (closure_mono (thickening_subset_cthickening δ E)).trans is_closed_cthickening.closure_subset /-- The closed thickening of a set contains the closure of the set. -/ lemma closure_subset_cthickening (δ : ℝ) (E : set α) : closure E ⊆ cthickening δ E := by { rw ← cthickening_of_nonpos (min_le_right δ 0), exact cthickening_mono (min_le_left δ 0) E, } /-- The (open) thickening of a set contains the closure of the set. -/ lemma closure_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : set α) : closure E ⊆ thickening δ E := by { rw ← cthickening_zero, exact cthickening_subset_thickening' δ_pos δ_pos E, } /-- A set is contained in its own (open) thickening. -/ lemma self_subset_thickening {δ : ℝ} (δ_pos : 0 < δ) (E : set α) : E ⊆ thickening δ E := (@subset_closure _ _ E).trans (closure_subset_thickening δ_pos E) /-- A set is contained in its own closed thickening. -/ lemma self_subset_cthickening {δ : ℝ} (E : set α) : E ⊆ cthickening δ E := subset_closure.trans (closure_subset_cthickening δ E) lemma cthickening_eq_Inter_cthickening' {δ : ℝ} (s : set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ (Ioc δ ε)).nonempty) (E : set α) : cthickening δ E = ⋂ ε ∈ s, cthickening ε E := begin apply subset.antisymm, { exact subset_Inter₂ (λ _ hε, cthickening_mono (le_of_lt (hsδ hε)) E), }, { unfold thickening cthickening, intros x hx, simp only [mem_Inter, mem_set_of_eq] at *, apply ennreal.le_of_forall_pos_le_add, intros η η_pos _, rcases hs (δ + η) (lt_add_of_pos_right _ (nnreal.coe_pos.mpr η_pos)) with ⟨ε, ⟨hsε, hε⟩⟩, apply ((hx ε hsε).trans (ennreal.of_real_le_of_real hε.2)).trans, rw ennreal.coe_nnreal_eq η, exact ennreal.of_real_add_le, }, end lemma cthickening_eq_Inter_cthickening {δ : ℝ} (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : δ < ε), cthickening ε E := begin apply cthickening_eq_Inter_cthickening' (Ioi δ) rfl.subset, simp_rw inter_eq_right_iff_subset.mpr Ioc_subset_Ioi_self, exact λ _ hε, nonempty_Ioc.mpr hε, end lemma cthickening_eq_Inter_thickening' {δ : ℝ} (δ_nn : 0 ≤ δ) (s : set ℝ) (hsδ : s ⊆ Ioi δ) (hs : ∀ ε, δ < ε → (s ∩ (Ioc δ ε)).nonempty) (E : set α) : cthickening δ E = ⋂ ε ∈ s, thickening ε E := begin refine (subset_Inter₂ $ λ ε hε, _).antisymm _, { obtain ⟨ε', hsε', hε'⟩ := hs ε (hsδ hε), have ss := cthickening_subset_thickening' (lt_of_le_of_lt δ_nn hε'.1) hε'.1 E, exact ss.trans (thickening_mono hε'.2 E), }, { rw cthickening_eq_Inter_cthickening' s hsδ hs E, exact Inter₂_mono (λ ε hε, thickening_subset_cthickening ε E) } end lemma cthickening_eq_Inter_thickening {δ : ℝ} (δ_nn : 0 ≤ δ) (E : set α) : cthickening δ E = ⋂ (ε : ℝ) (h : δ < ε), thickening ε E := begin apply cthickening_eq_Inter_thickening' δ_nn (Ioi δ) rfl.subset, simp_rw inter_eq_right_iff_subset.mpr Ioc_subset_Ioi_self, exact λ _ hε, nonempty_Ioc.mpr hε, end /-- The closure of a set equals the intersection of its closed thickenings of positive radii accumulating at zero. -/ lemma closure_eq_Inter_cthickening' (E : set α) (s : set ℝ) (hs : ∀ ε, 0 < ε → (s ∩ (Ioc 0 ε)).nonempty) : closure E = ⋂ δ ∈ s, cthickening δ E := begin by_cases hs₀ : s ⊆ Ioi 0, { rw ← cthickening_zero, apply cthickening_eq_Inter_cthickening' _ hs₀ hs, }, obtain ⟨δ, hδs, δ_nonpos⟩ := not_subset.mp hs₀, rw [set.mem_Ioi, not_lt] at δ_nonpos, apply subset.antisymm, { exact subset_Inter₂ (λ ε _, closure_subset_cthickening ε E), }, { rw ← cthickening_of_nonpos δ_nonpos E, exact bInter_subset_of_mem hδs, }, end /-- The closure of a set equals the intersection of its closed thickenings of positive radii. -/ lemma closure_eq_Inter_cthickening (E : set α) : closure E = ⋂ (δ : ℝ) (h : 0 < δ), cthickening δ E := by { rw ← cthickening_zero, exact cthickening_eq_Inter_cthickening E, } /-- The closure of a set equals the intersection of its open thickenings of positive radii accumulating at zero. -/ lemma closure_eq_Inter_thickening' (E : set α) (s : set ℝ) (hs₀ : s ⊆ Ioi 0) (hs : ∀ ε, 0 < ε → (s ∩ (Ioc 0 ε)).nonempty) : closure E = ⋂ δ ∈ s, thickening δ E := by { rw ← cthickening_zero, apply cthickening_eq_Inter_thickening' le_rfl _ hs₀ hs, } /-- The closure of a set equals the intersection of its (open) thickenings of positive radii. -/ lemma closure_eq_Inter_thickening (E : set α) : closure E = ⋂ (δ : ℝ) (h : 0 < δ), thickening δ E := by { rw ← cthickening_zero, exact cthickening_eq_Inter_thickening rfl.ge E, } /-- The frontier of the (open) thickening of a set is contained in an `inf_edist` level set. -/ lemma frontier_thickening_subset (E : set α) {δ : ℝ} (δ_pos : 0 < δ) : frontier (thickening δ E) ⊆ {x : α | inf_edist x E = ennreal.of_real δ} := begin have singleton_preim : {x : α | inf_edist x E = ennreal.of_real δ } = (λ x , inf_edist x E) ⁻¹' {ennreal.of_real δ}, { simp only [preimage, mem_singleton_iff] }, rw [thickening_eq_preimage_inf_edist, singleton_preim, ← (frontier_Iio' ⟨(0 : ℝ≥0∞), ennreal.of_real_pos.mpr δ_pos⟩)], exact continuous_inf_edist.frontier_preimage_subset (Iio (ennreal.of_real δ)), end /-- The frontier of the closed thickening of a set is contained in an `inf_edist` level set. -/ lemma frontier_cthickening_subset (E : set α) {δ : ℝ} : frontier (cthickening δ E) ⊆ {x : α | inf_edist x E = ennreal.of_real δ} := begin have singleton_preim : {x : α | inf_edist x E = ennreal.of_real δ } = (λ x , inf_edist x E) ⁻¹' {ennreal.of_real δ}, { simp only [preimage, mem_singleton_iff] }, rw [cthickening_eq_preimage_inf_edist, singleton_preim, ← frontier_Iic' ⟨∞, ennreal.of_real_lt_top⟩], exact continuous_inf_edist.frontier_preimage_subset (Iic (ennreal.of_real δ)), end /-- The closed ball of radius `δ` centered at a point of `E` is included in the closed thickening of `E`. -/ lemma closed_ball_subset_cthickening {α : Type*} [pseudo_metric_space α] {x : α} {E : set α} (hx : x ∈ E) (δ : ℝ) : closed_ball x δ ⊆ cthickening δ E := begin refine (closed_ball_subset_cthickening_singleton _ _).trans (cthickening_subset_of_subset _ _), simpa using hx, end /-- The closed thickening of a compact set `E` is the union of the balls `closed_ball x δ` over `x ∈ E`. -/ lemma _root_.is_compact.cthickening_eq_bUnion_closed_ball {α : Type*} [pseudo_metric_space α] {δ : ℝ} {E : set α} (hE : is_compact E) (hδ : 0 ≤ δ) : cthickening δ E = ⋃ x ∈ E, closed_ball x δ := begin rcases eq_empty_or_nonempty E with rfl|hne, { simp only [cthickening_empty, Union_false, Union_empty] }, refine subset.antisymm (λ x hx, _) (Union₂_subset $ λ x hx, closed_ball_subset_cthickening hx _), obtain ⟨y, yE, hy⟩ : ∃ y ∈ E, emetric.inf_edist x E = edist x y := hE.exists_inf_edist_eq_edist hne _, have D1 : edist x y ≤ ennreal.of_real δ := (le_of_eq hy.symm).trans hx, have D2 : dist x y ≤ δ, { rw edist_dist at D1, exact (ennreal.of_real_le_of_real_iff hδ).1 D1 }, exact mem_bUnion yE D2, end end cthickening --section end metric --namespace
2476eb042bbceacb02e1d6d164c88788eb50f957
d1bbf1801b3dcb214451d48214589f511061da63
/src/computability/partrec.lean
6cc99be8383572b95367793746e2babf815518e8
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,984
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 computability.primrec import data.nat.psub import data.pfun /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable roption namespace nat section rfind parameter (p : ℕ →. bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : ∀m k, n ≤ k + m → acc (lbp p) k, { from λa, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} := suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m}, from this 0 (λ n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, h₂⟩, rcases decidable.lt_trichotomy m n with h₃|h₃|h₃, { exact h₂ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)), intros n h, cases decidable.lt_or_eq_of_le h with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : ℕ →. bool) : roption ℕ := ⟨_, λ h, (rfind_x p h).1⟩ theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := h.snd ▸ (rfind_x p h.fst).2.1 theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → ff ∈ p m := h.snd ▸ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom := iff.rfl theorem rfind_dom' {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom := exists_congr $ λ n, and_congr_right $ λ pn, ⟨λ H m h, (eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _), λ H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (h₂ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ λ h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ λ a h, let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in (p0 ▸ h₂ (zero_le _) : (@roption.none bool).dom) def rfind_opt {α} (f : ℕ → option α) : roption α := (rfind (λ n, (f n).is_some)).bind (λ n, f n) theorem rfind_opt_spec {α} {f : ℕ → option α} {a} (h : a ∈ rfind_opt f) : ∃ n, a ∈ f n := let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩ theorem rfind_opt_dom {α} {f : ℕ → option α} : (rfind_opt f).dom ↔ ∃ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩), λ h, begin have h' : ∃ n, (f n).is_some := h.imp (λ n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (λ n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊢, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {α} {f : ℕ → option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n := ⟨rfind_opt_spec, λ ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (ℕ →. ℕ) → Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec ↑(λ n : ℕ, n.unpair.1) | right : partrec ↑(λ n : ℕ, n.unpair.2) | pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n) | comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f) | prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n, n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f → partrec (λ a, rfind (λ n, (λ m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g := hf.of_eq (λ n, eq_some_iff.2 (H n)) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (λ n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (λ n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (λ n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (λ n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (λ a, (f a).bind (λ n, n.elim (g a) (λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ λ a, ext $ λ s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩, λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩ theorem ppred : partrec (λ n, ppred n) := have primrec₂ (λ n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).to₂, (of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $ λ n, begin cases n; simp, { exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {α σ} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec (λ n, roption.bind (decode α n) (λ a, (f a).map encode)) def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2) def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ) def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable (λ p : α × β, f p.1 p.2) theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ λ n, by simp; cases decode α n; simp theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp theorem computable.part {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf theorem computable₂.part {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : computable (λ a : α, s) := (primrec.const _).to_comp theorem of_option {f : α → option β} (hf : computable f) : partrec (λ a, (f a : roption β)) := (nat.partrec.ppred.comp hf).of_eq $ λ n, begin cases decode α n with a; simp, cases f a with b; simp end theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl protected theorem id : computable (@id α) := primrec.id.to_comp theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp theorem pair {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) := (hf.pair hg).of_eq $ λ n, by cases decode α n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length α) := primrec.list_length.to_comp theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode α _) := primrec.encode.to_comp protected theorem decode : computable (decode α) := primrec.decode.to_comp protected theorem of_nat (α) [denumerable α] : computable (of_nat α) := (primrec.of_nat _).to_comp theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some α) := primrec.option_some.to_comp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g := hf.of_eq (λ a, eq_some_iff.2 (H a)) theorem none : partrec (λ a : α, @roption.none σ) := nat.partrec.none.of_eq $ λ n, by cases decode α n; simp protected theorem some : partrec (@roption.some α) := computable.id theorem const' (s : roption σ) : partrec (λ a : α, s) := by haveI := classical.dec s.dom; exact (of_option (const (to_option s))).of_eq (λ a, of_to_option s) protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ λ n, by simp [(<*>)]; cases e : decode α n with a; simp [e, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (λ a b, roption.some (g a b)) hf hg theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ λ n, begin cases e : decode α n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [encodek] end theorem comp {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) := (hf.comp hg).of_eq $ λ n, by simp; cases e : decode α n with a; simp [e, encodek] theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrec₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := ⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp, λ h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end partrec₂ namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem comp {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, f (g a)) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ (λ a b, f (g a b)) := hf.comp hg end computable namespace computable₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end computable₂ namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) : partrec (λ a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (λ b, cond b 0 1)) .comp primrec.snd).to₂.to_comp).of_eq $ λ n, begin cases e : decode α n with a; simp [e, nat.rfind_zero_none, map_id'], congr, funext n, simp [roption.map_map, (∘)], apply map_id' (λ b, _), cases b; refl end theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) : partrec (λ a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).part.to₂).bind (of_option hf) theorem nat_cases_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec (λ a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $ λ a, begin simp, cases f a; simp, refine ext (λ b, ⟨λ H, _, λ H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ }, { have : ∀ m, (nat.elim (roption.some (g a)) (λ y IH, IH.bind (λ _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode2_iff {f : α →. σ} : partrec f ↔ nat.partrec (λ n, roption.bind (decode2 α n) (λ a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $ (map hf (computable.encode.comp snd).to₂).comp snd, λ h, map_encode_iff.1 $ by simpa [encodek2] using (nat_iff.2 h).comp (@computable.encode α _)⟩ theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) → partrec (λ (a : α), vector.m_of_fn (λ i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_roption_some {α n} : ∀ (f : fin n → α), vector.m_of_fn (λ i, roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n, (decode β n).bind (f a)) ↔ computable₂ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind (computable.comp hf fst).to₂.part) $ λ n, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; simp, λ hf, begin have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases (some option.none) (λ n, roption.map (f a.1) (decode β n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).to₂), refine this.of_eq (λ a, _), simp, cases decode β a.2; simp [encodek] end⟩ theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n, (decode β n).map (f a)) ↔ computable₂ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.part).of_eq $ λ a, by simp; induction f a; simp * theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂ theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : @computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ λ a, by cases o a; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ λ a, by cases f a; refl theorem option_map {f : α → option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_get_or_else {f : α → option β} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, (f a).get_or_else (g a)) := (computable.option_cases hf hg (show computable₂ (λ a b, b), from computable.snd)).of_eq $ λ a, by cases f a; refl theorem subtype_mk {f : α → β} {p : β → Prop} [decidable_pred p] {h : ∀ a, p (f a)} (hp : primrec_pred p) (hf : computable f) : @computable _ _ _ (primcodable.subtype hp) (λ a, (⟨f a, h a⟩ : subtype p)) := nat.partrec.of_eq hf $ λ n, by cases decode α n; simp [subtype.encode_eq] theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : @computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f := suffices computable₂ (λ a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_concat] end theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ λ a, by simp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem option_some_iff {f : α →. σ} : partrec (λ a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ λ n, by simp [roption.bind_assoc, bind_some_eq_map], λ hf, hf.map (option_some.comp snd).to₂⟩ theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : @partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (λ (a : α), nat.cases (roption.some (f a)) (λ n, roption.bind (decode β n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.part $ ((@computable.decode β _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).to₂, this.of_eq $ λ a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) := have partrec (λ a, (option.cases_on (sum.cases_on (f a) (λ b, option.none) option.some : option γ) (some (sum.cases_on (f a) (λ b, some (g a b)) (λ c, option.none))) (λ c, (h a c).map option.some) : roption (option σ))) := option_cases_right (sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂) (sum_cases hf (option_some.comp hg) (const option.none).to₂) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp theorem sum_cases_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $ λ a, by cases f a; simp private lemma fix_aux {f : α →. σ ⊕ α} (hf : partrec f) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in (∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩, have : ∀ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨a₂, am₂, fa₂⟩, exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) }, cases n; simp [F] at h₂, {cases h₂}, rcases h₂ with h₂ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h h₂ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), ∃ n, sum.inl b ∈ F a n ∧ ∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩, exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ }, intros a₁ h₁, apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk, rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩, { refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, h₂⟩ }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩, { refine ⟨n, hn₁, λ m mn km, _⟩, cases lt_or_eq_of_le km with km km, { exact hn₂ _ mn km }, { exact km ▸ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, am₃⟩ } } } end theorem fix {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in have hF : partrec₂ F := partrec.nat_elim snd (sum_inr.comp fst).part (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).to₂ (hf.comp snd).to₂).to₂, let p := λ a n, @roption.map _ bool (λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in have hp : partrec₂ p := hF.map ((sum_cases computable.id (const tt).to₂ (const ff).to₂).comp snd).to₂, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $ λ a, ext $ λ b, by simp; apply fix_aux hf end partrec
0d7bc68e48954c5cb5e2369c83e31a6315af9686
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/algebra/archimedean.lean
fbb191ddaf6f0691e183885ae1b83012d6ed702b
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,928
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.field_power import data.rat /-! # Archimedean groups and fields. This file defines the archimedean property for ordered groups and proves several results connected to this notion. Being archimedean means that for all elements `x` and `y>0` there exists a natural number `n` such that `x ≤ n • y`. ## Main definitions * `archimedean` is a typeclass for an ordered additive commutative monoid to have the archimedean property. * `archimedean.floor_ring` defines a floor function on an archimedean linearly ordered ring making it into a `floor_ring`. * `round` defines a function rounding to the nearest integer for a linearly ordered field which is also a floor ring. ## Main statements * `ℕ`, `ℤ`, and `ℚ` are archimedean. -/ variables {α : Type*} /-- An ordered additive commutative monoid is called `archimedean` if for any two elements `x`, `y` such that `0 < y` there exists a natural number `n` such that `x ≤ n • y`. -/ class archimedean (α) [ordered_add_comm_monoid α] : Prop := (arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y) instance order_dual.archimedean [ordered_add_comm_group α] [archimedean α] : archimedean (order_dual α) := ⟨λ x y hy, let ⟨n, hn⟩ := archimedean.arch (-x : α) (neg_pos.2 hy) in ⟨n, by rwa [neg_nsmul, neg_le_neg_iff] at hn⟩⟩ namespace linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] [archimedean α] /-- An archimedean decidable linearly ordered `add_comm_group` has a version of the floor: for `a > 0`, any `g` in the group lies between some two consecutive multiples of `a`. -/ lemma exists_int_smul_near_of_pos {a : α} (ha : 0 < a) (g : α) : ∃ (k : ℤ), k • a ≤ g ∧ g < (k + 1) • a := begin let s : set ℤ := {n : ℤ | n • a ≤ g}, obtain ⟨k, hk : -g ≤ k • a⟩ := archimedean.arch (-g) ha, have h_ne : s.nonempty := ⟨-k, by simpa using neg_le_neg hk⟩, obtain ⟨k, hk⟩ := archimedean.arch g ha, have h_bdd : ∀ n ∈ s, n ≤ (k : ℤ), { assume n hn, apply (gsmul_le_gsmul_iff ha).mp, rw ← gsmul_coe_nat at hk, exact le_trans hn hk }, obtain ⟨m, hm, hm'⟩ := int.exists_greatest_of_bdd ⟨k, h_bdd⟩ h_ne, refine ⟨m, hm, _⟩, by_contra H, linarith [hm' _ $ not_lt.mp H] end lemma exists_int_smul_near_of_pos' {a : α} (ha : 0 < a) (g : α) : ∃ (k : ℤ), 0 ≤ g - k • a ∧ g - k • a < a := begin obtain ⟨k, h1, h2⟩ := exists_int_smul_near_of_pos ha g, rw add_gsmul at h2, refine ⟨k, sub_nonneg.mpr h1, _⟩, simpa [sub_lt_iff_lt_add'] using h2 end end linear_ordered_add_comm_group theorem exists_nat_gt [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) : ∃ n : ℕ, x < n := let ⟨n, h⟩ := archimedean.arch x zero_lt_one in ⟨n+1, lt_of_le_of_lt (by rwa ← nsmul_one) (nat.cast_lt.2 (nat.lt_succ_self _))⟩ theorem exists_nat_ge [ordered_semiring α] [archimedean α] (x : α) : ∃ n : ℕ, x ≤ n := begin nontriviality α, exact (exists_nat_gt x).imp (λ n, le_of_lt) end lemma add_one_pow_unbounded_of_pos [ordered_semiring α] [nontrivial α] [archimedean α] (x : α) {y : α} (hy : 0 < y) : ∃ n : ℕ, x < (y + 1) ^ n := have 0 ≤ 1 + y, from add_nonneg zero_le_one hy.le, let ⟨n, h⟩ := archimedean.arch x hy in ⟨n, calc x ≤ n • y : h ... = n * y : nsmul_eq_mul _ _ ... < 1 + n * y : lt_one_add _ ... ≤ (1 + y) ^ n : one_add_mul_le_pow' (mul_nonneg hy.le hy.le) (mul_nonneg this this) (add_nonneg zero_le_two hy.le) _ ... = (y + 1) ^ n : by rw [add_comm]⟩ section linear_ordered_ring variables [linear_ordered_ring α] [archimedean α] lemma pow_unbounded_of_one_lt (x : α) {y : α} (hy1 : 1 < y) : ∃ n : ℕ, x < y ^ n := sub_add_cancel y 1 ▸ add_one_pow_unbounded_of_pos _ (sub_pos.2 hy1) /-- Every x greater than or equal to 1 is between two successive natural-number powers of every y greater than one. -/ lemma exists_nat_pow_near {x : α} {y : α} (hx : 1 ≤ x) (hy : 1 < y) : ∃ n : ℕ, y ^ n ≤ x ∧ x < y ^ (n + 1) := have h : ∃ n : ℕ, x < y ^ n, from pow_unbounded_of_one_lt _ hy, by classical; exact let n := nat.find h in have hn : x < y ^ n, from nat.find_spec h, have hnp : 0 < n, from pos_iff_ne_zero.2 (λ hn0, by rw [hn0, pow_zero] at hn; exact (not_le_of_gt hn hx)), have hnsp : nat.pred n + 1 = n, from nat.succ_pred_eq_of_pos hnp, have hltn : nat.pred n < n, from nat.pred_lt (ne_of_gt hnp), ⟨nat.pred n, le_of_not_lt (nat.find_min h hltn), by rwa hnsp⟩ theorem exists_int_gt (x : α) : ∃ n : ℤ, x < n := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa ← coe_coe⟩ theorem exists_int_lt (x : α) : ∃ n : ℤ, (n : α) < x := let ⟨n, h⟩ := exists_int_gt (-x) in ⟨-n, by rw int.cast_neg; exact neg_lt.1 h⟩ theorem exists_floor (x : α) : ∃ (fl : ℤ), ∀ (z : ℤ), z ≤ fl ↔ (z : α) ≤ x := begin haveI := classical.prop_decidable, have : ∃ (ub : ℤ), (ub:α) ≤ x ∧ ∀ (z : ℤ), (z:α) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩), refine this.imp (λ fl h z, _), cases h with h₁ h₂, exact ⟨λ h, le_trans (int.cast_le.2 h) h₁, h₂ z⟩, end end linear_ordered_ring section linear_ordered_field variables [linear_ordered_field α] /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_int_pow_near'`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n ≤ x ∧ x < y ^ (n + 1) := by classical; exact let ⟨N, hN⟩ := pow_unbounded_of_one_lt x⁻¹ hy in have he: ∃ m : ℤ, y ^ m ≤ x, from ⟨-N, le_of_lt (by { rw [fpow_neg y (↑N), gpow_coe_nat], exact (inv_lt hx (lt_trans (inv_pos.2 hx) hN)).1 hN })⟩, let ⟨M, hM⟩ := pow_unbounded_of_one_lt x hy in have hb: ∃ b : ℤ, ∀ m, y ^ m ≤ x → m ≤ b, from ⟨M, λ m hm, le_of_not_lt (λ hlt, not_lt_of_ge (fpow_le_of_le (le_of_lt hy) (le_of_lt hlt)) (lt_of_le_of_lt hm (by rwa ← gpow_coe_nat at hM)))⟩, let ⟨n, hn₁, hn₂⟩ := int.exists_greatest_of_bdd hb he in ⟨n, hn₁, lt_of_not_ge (λ hge, not_le_of_gt (int.lt_succ _) (hn₂ _ hge))⟩ /-- Every positive `x` is between two successive integer powers of another `y` greater than one. This is the same as `exists_int_pow_near`, but with ≤ and < the other way around. -/ lemma exists_int_pow_near' [archimedean α] {x : α} {y : α} (hx : 0 < x) (hy : 1 < y) : ∃ n : ℤ, y ^ n < x ∧ x ≤ y ^ (n + 1) := let ⟨m, hle, hlt⟩ := exists_int_pow_near (inv_pos.2 hx) hy in have hyp : 0 < y, from lt_trans zero_lt_one hy, ⟨-(m+1), by rwa [fpow_neg, inv_lt (fpow_pos_of_pos hyp _) hx], by rwa [neg_add, neg_add_cancel_right, fpow_neg, le_inv hx (fpow_pos_of_pos hyp _)]⟩ /-- For any `y < 1` and any positive `x`, there exists `n : ℕ` with `y ^ n < x`. -/ lemma exists_pow_lt_of_lt_one [archimedean α] {x y : α} (hx : 0 < x) (hy : y < 1) : ∃ n : ℕ, y ^ n < x := begin by_cases y_pos : y ≤ 0, { use 1, simp only [pow_one], linarith, }, rw [not_le] at y_pos, rcases pow_unbounded_of_one_lt (x⁻¹) (one_lt_inv y_pos hy) with ⟨q, hq⟩, exact ⟨q, by rwa [inv_pow', inv_lt_inv hx (pow_pos y_pos _)] at hq⟩ end /-- Given `x` and `y` between `0` and `1`, `x` is between two successive powers of `y`. This is the same as `exists_nat_pow_near`, but for elements between `0` and `1` -/ lemma exists_nat_pow_near_of_lt_one [archimedean α] {x : α} {y : α} (xpos : 0 < x) (hx : x ≤ 1) (ypos : 0 < y) (hy : y < 1) : ∃ n : ℕ, y ^ (n + 1) < x ∧ x ≤ y ^ n := begin rcases exists_nat_pow_near (one_le_inv_iff.2 ⟨xpos, hx⟩) (one_lt_inv_iff.2 ⟨ypos, hy⟩) with ⟨n, hn, h'n⟩, refine ⟨n, _, _⟩, { rwa [inv_pow', inv_lt_inv xpos (pow_pos ypos _)] at h'n }, { rwa [inv_pow', inv_le_inv (pow_pos ypos _) xpos] at hn } end variables [floor_ring α] lemma sub_floor_div_mul_nonneg (x : α) {y : α} (hy : 0 < y) : 0 ≤ x - ⌊x / y⌋ * y := begin conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← sub_mul, exact mul_nonneg (sub_nonneg.2 (floor_le _)) (le_of_lt hy) end lemma sub_floor_div_mul_lt (x : α) {y : α} (hy : 0 < y) : x - ⌊x / y⌋ * y < y := sub_lt_iff_lt_add.2 begin conv in y {rw ← one_mul y}, conv in x {rw ← div_mul_cancel x (ne_of_lt hy).symm}, rw ← add_mul, exact (mul_lt_mul_right hy).2 (by rw add_comm; exact lt_floor_add_one _), end end linear_ordered_field instance : archimedean ℕ := ⟨λ n m m0, ⟨n, by simpa only [mul_one, nat.nsmul_eq_mul] using nat.mul_le_mul_left n m0⟩⟩ instance : archimedean ℤ := ⟨λ n m m0, ⟨n.to_nat, le_trans (int.le_to_nat _) $ by simpa only [nsmul_eq_mul, int.nat_cast_eq_coe_nat, zero_add, mul_one] using mul_le_mul_of_nonneg_left (int.add_one_le_iff.2 m0) (int.coe_zero_le n.to_nat)⟩⟩ /-- A linear ordered archimedean ring is a floor ring. This is not an `instance` because in some cases we have a computable `floor` function. -/ noncomputable def archimedean.floor_ring (α) [linear_ordered_ring α] [archimedean α] : floor_ring α := { floor := λ x, classical.some (exists_floor x), le_floor := λ z x, classical.some_spec (exists_floor x) z } section linear_ordered_field variables [linear_ordered_field α] theorem archimedean_iff_nat_lt : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x < n := ⟨@exists_nat_gt α _ _, λ H, ⟨λ x y y0, (H (x / y)).imp $ λ n h, le_of_lt $ by rwa [div_lt_iff y0, ← nsmul_eq_mul] at h⟩⟩ theorem archimedean_iff_nat_le : archimedean α ↔ ∀ x : α, ∃ n : ℕ, x ≤ n := archimedean_iff_nat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (nat.cast_lt.2 (lt_add_one _))⟩⟩ theorem exists_rat_gt [archimedean α] (x : α) : ∃ q : ℚ, x < q := let ⟨n, h⟩ := exists_nat_gt x in ⟨n, by rwa rat.cast_coe_nat⟩ theorem archimedean_iff_rat_lt : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x < q := ⟨@exists_rat_gt α _, λ H, archimedean_iff_nat_lt.2 $ λ x, let ⟨q, h⟩ := H x in ⟨nat_ceil q, lt_of_lt_of_le h $ by simpa only [rat.cast_coe_nat] using (@rat.cast_le α _ _ _).2 (le_nat_ceil _)⟩⟩ theorem archimedean_iff_rat_le : archimedean α ↔ ∀ x : α, ∃ q : ℚ, x ≤ q := archimedean_iff_rat_lt.trans ⟨λ H x, (H x).imp $ λ _, le_of_lt, λ H x, let ⟨n, h⟩ := H x in ⟨n+1, lt_of_le_of_lt h (rat.cast_lt.2 (lt_add_one _))⟩⟩ variable [archimedean α] theorem exists_rat_lt (x : α) : ∃ q : ℚ, (q : α) < x := let ⟨n, h⟩ := exists_int_lt x in ⟨n, by rwa rat.cast_coe_int⟩ theorem exists_rat_btwn {x y : α} (h : x < y) : ∃ q : ℚ, x < q ∧ (q:α) < y := begin cases exists_nat_gt (y - x)⁻¹ with n nh, cases exists_floor (x * n) with z zh, refine ⟨(z + 1 : ℤ) / n, _⟩, have n0' := (inv_pos.2 (sub_pos.2 h)).trans nh, have n0 := nat.cast_pos.1 n0', rw [rat.cast_div_of_ne_zero, rat.cast_coe_nat, rat.cast_coe_int, div_lt_iff n0'], refine ⟨(lt_div_iff n0').2 $ (lt_iff_lt_of_le_iff_le (zh _)).1 (lt_add_one _), _⟩, rw [int.cast_add, int.cast_one], refine lt_of_le_of_lt (add_le_add_right ((zh _).1 (le_refl _)) _) _, rwa [← lt_sub_iff_add_lt', ← sub_mul, ← div_lt_iff' (sub_pos.2 h), one_div], { rw [rat.coe_int_denom, nat.cast_one], exact one_ne_zero }, { intro H, rw [rat.coe_nat_num, ← coe_coe, nat.cast_eq_zero] at H, subst H, cases n0 }, { rw [rat.coe_nat_denom, nat.cast_one], exact one_ne_zero } end theorem exists_nat_one_div_lt {ε : α} (hε : 0 < ε) : ∃ n : ℕ, 1 / (n + 1: α) < ε := begin cases exists_nat_gt (1/ε) with n hn, use n, rw [div_lt_iff, ← div_lt_iff' hε], { apply hn.trans, simp [zero_lt_one] }, { exact n.cast_add_one_pos } end theorem exists_pos_rat_lt {x : α} (x0 : 0 < x) : ∃ q : ℚ, 0 < q ∧ (q : α) < x := by simpa only [rat.cast_pos] using exists_rat_btwn x0 end linear_ordered_field section variables [linear_ordered_field α] [floor_ring α] /-- `round` rounds a number to the nearest integer. `round (1 / 2) = 1` -/ def round (x : α) : ℤ := ⌊x + 1 / 2⌋ @[simp] lemma round_zero : round (0 : α) = 0 := floor_eq_iff.2 (by norm_num) @[simp] lemma round_one : round (1 : α) = 1 := floor_eq_iff.2 (by norm_num) lemma abs_sub_round (x : α) : abs (x - round x) ≤ 1 / 2 := begin rw [round, abs_sub_le_iff], have := floor_le (x + 1 / 2), have := lt_floor_add_one (x + 1 / 2), split; linarith end @[simp, norm_cast] theorem rat.cast_floor (x : ℚ) : ⌊(x:α)⌋ = ⌊x⌋ := floor_eq_iff.2 (by exact_mod_cast floor_eq_iff.1 (eq.refl ⌊x⌋)) @[simp, norm_cast] theorem rat.cast_ceil (x : ℚ) : ⌈(x:α)⌉ = ⌈x⌉ := by rw [ceil, ← rat.cast_neg, rat.cast_floor, ← ceil] @[simp, norm_cast] theorem rat.cast_round (x : ℚ) : round (x:α) = round x := have ((x + 1 / 2 : ℚ) : α) = x + 1 / 2, by simp, by rw [round, round, ← this, rat.cast_floor] end section variables [linear_ordered_field α] [archimedean α] theorem exists_rat_near (x : α) {ε : α} (ε0 : 0 < ε) : ∃ q : ℚ, abs (x - q) < ε := let ⟨q, h₁, h₂⟩ := exists_rat_btwn $ lt_trans ((sub_lt_self_iff x).2 ε0) ((lt_add_iff_pos_left x).2 ε0) in ⟨q, abs_sub_lt_iff.2 ⟨sub_lt.1 h₁, sub_lt_iff_lt_add.2 h₂⟩⟩ instance : archimedean ℚ := archimedean_iff_rat_le.2 $ λ q, ⟨q, by rw rat.cast_id⟩ end
a4cf43b8e9fa48e90bbe53afdb3629d729db4fcb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/widget/default.lean
2af47c231740bad3a0c41bb8a690af1adebae0ab
[]
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
456
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.widget.basic import Mathlib.Lean3Lib.init.meta.widget.interactive_expr import Mathlib.Lean3Lib.init.meta.widget.tactic_component import Mathlib.Lean3Lib.init.meta.widget.html_cmd import Mathlib.Lean3Lib.init.meta.widget.replace_save_info namespace Mathlib
aab4d6ba928c454eaa629c9aa02517e82ca981be
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/tools/super/equality.lean
f93fe50466616c627bb39504b55a132d8395db10
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,249
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state .utils open tactic monad expr list namespace super meta def try_unify_eq_l (c : clause) (i : nat) : tactic clause := do guard $ clause.literal.is_neg (clause.get_lit c i), qf ← clause.open_metan c c.num_quants, match is_eq (qf.1.get_lit i).formula with | none := failed | some (lhs, rhs) := do unify lhs rhs, ty ← infer_type lhs, univ ← infer_univ ty, refl ← return $ app_of_list (const ``eq.refl [univ]) [ty, lhs], opened ← clause.open_constn qf.1 i, clause.meta_closure qf.2 $ clause.close_constn (opened.1.inst refl) opened.2 end @[super.inf] meta def unify_eq_inf : inf_decl := inf_decl.mk 40 $ take given, sequence' $ do i ← given.selected, [inf_if_successful 0 given (do u ← try_unify_eq_l given.c i, return [u])] meta def has_refl_r (c : clause) : bool := list.bor $ do literal ← c.get_lits, guard literal.is_pos, match is_eq literal.formula with | some (lhs, rhs) := [decidable.to_bool (lhs = rhs)] | none := [] end meta def refl_r_pre : prover unit := preprocessing_rule $ take new, return $ filter (λc, ¬has_refl_r c.c) new end super
a8a89cc21d470c48e7de0e2c49a9fad48dd206aa
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/group/to_additive.lean
14945d3c407bd049c2a8b4256bea9bd706cc3fb7
[ "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,315
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov. -/ import tactic.transform_decl import tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. * Rewrite rules for the last part of the name that work in more cases. E.g., we can replace `monoid` with `add_monoid` etc. -/ namespace to_additive open tactic exceptional section performance_hack -- see Note [user attribute parameters] local attribute [semireducible] reflected local attribute [instance, priority 9000] private meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ @[user_attribute] private meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', do let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end, param ← aux_attr.get_param_untyped n', pure $ dict.insert n param.app_arg.const_name) mk_name_map, []⟩, parser := lean.parser.ident } end performance_hack /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments into `name` for the target and an optional doc string. -/ @[derive has_reflect, derive inhabited] structure value_type : Type := (tgt : name) (doc : option string) /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ meta def add_comm_prefix : bool → string → string | tt s := ("comm_" ++ s) | ff s := s /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ meta def tr : bool → list string → list string | is_comm ("one" :: "le" :: s) := add_comm_prefix is_comm "nonneg" :: tr ff s | is_comm ("one" :: "lt" :: s) := add_comm_prefix is_comm "pos" :: tr ff s | is_comm ("le" :: "one" :: s) := add_comm_prefix is_comm "nonpos" :: tr ff s | is_comm ("lt" :: "one" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("mul" :: s) := add_comm_prefix is_comm "add" :: tr ff s | is_comm ("inv" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("div" :: s) := add_comm_prefix is_comm "sub" :: tr ff s | is_comm ("one" :: s) := add_comm_prefix is_comm "zero" :: tr ff s | is_comm ("prod" :: s) := add_comm_prefix is_comm "sum" :: tr ff s | is_comm ("monoid" :: s) := ("add_" ++ add_comm_prefix is_comm "monoid") :: tr ff s | is_comm ("submonoid" :: s) := ("add_" ++ add_comm_prefix is_comm "submonoid") :: tr ff s | is_comm ("group" :: s) := ("add_" ++ add_comm_prefix is_comm "group") :: tr ff s | is_comm ("subgroup" :: s) := ("add_" ++ add_comm_prefix is_comm "subgroup") :: tr ff s | is_comm ("semigroup" :: s) := ("add_" ++ add_comm_prefix is_comm "semigroup") :: tr ff s | is_comm ("magma" :: s) := ("add_" ++ add_comm_prefix is_comm "magma") :: tr ff s | is_comm ("comm" :: s) := tr tt s | is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s) | tt [] := ["comm"] | ff [] := [] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens ''' $ λ s, string.intercalate (string.singleton '_') $ tr ff (s.split_on '_') /-- Return the provided target name or autogenerate one if one was not provided. -/ meta def target_name (src tgt : name) (dict : name_map name) : tactic name := (if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto) <|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++ "name, you may remove the explicit " ++ tgt_auto ++ " argument."), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself") else pure res) /-- the parser for the arguments to `to_additive` -/ meta def parser : lean.parser value_type := do tgt ← optional lean.parser.ident, e ← optional interactive.types.texpr, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨tgt.get_or_else name.anonymous, doc⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string: ``` @[to_additive add_foo "add_foo doc string"] /-- foo doc string -/ theorem foo := sorry ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. If the declaration to be transported has attributes which need to be copied to the additive version, then `to_additive` should come last: ``` @[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x ``` ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `comm_semigroup` to `add_comm_semigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`. Even when `to_additive` is unable to automatically generate the additive version of a declaration, it can be useful to apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first two cases `to_additive` double checks that the new name differs from the original one. -/ @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, tgt ← target_name src val.tgt dict, aux_attr.set src tgt tt, let dict := dict.insert src tgt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict src tgt [`reducible, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp], match val.doc with | some doc := add_doc_string tgt doc | none := skip end } add_tactic_doc { name := "to_additive", category := doc_category.attr, decl_names := [`to_additive.attr], tags := ["transport", "environment", "lemma derivation"] } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv
deb049a95a993d1411f335af27cb7865c53668f9
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/nonexhaustive.lean
2c8f0cc779fce01e87d9004beee985436574d517
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
284
lean
import data.vector open nat vector variable {A : Type} definition foo : Π {n : nat}, vector A n → nat, foo nil := 0, foo (a :: b :: v) := 0 set_option pp.implicit false definition foo : Π {n : nat}, vector A n → nat, foo nil := 0, foo (a :: b :: v) := 0
2d96660e277a23ce1c999c83eeb429d802d951e7
626e312b5c1cb2d88fca108f5933076012633192
/src/logic/basic.lean
3f3d9ca567d413aff0006fc1d0785c1e16202598
[ "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
59,741
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 -/ import tactic.doc_commands import tactic.reserved_notation /-! # Basic logic properties This file is one of the earliest imports in mathlib. ## Implementation notes Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". In the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ open function local attribute [instance, priority 10] classical.prop_decidable section miscellany /- We add the `inline` attribute to optimize VM computation using these declarations. For example, `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/ attribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable decidable.true implies.decidable not.decidable ne.decidable bool.decidable_eq decidable.to_bool attribute [simp] cast_eq cast_heq variables {α : Type*} {β : Type*} /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ @[reducible] def hidden {α : Sort*} {a : α} := a /-- Ex falso, the nondependent eliminator for the `empty` type. -/ def empty.elim {C : Sort*} : empty → C. instance : subsingleton empty := ⟨λa, a.elim⟩ instance subsingleton.prod {α β : Type*} [subsingleton α] [subsingleton β] : subsingleton (α × β) := ⟨by { intros a b, cases a, cases b, congr, }⟩ instance : decidable_eq empty := λa, a.elim instance sort.inhabited : inhabited (Sort*) := ⟨punit⟩ instance sort.inhabited' : inhabited (default (Sort*)) := ⟨punit.star⟩ instance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl (default _)⟩ instance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr (default _)⟩ @[priority 10] instance decidable_eq_of_subsingleton {α} [subsingleton α] : decidable_eq α | a b := is_true (subsingleton.elim a b) @[simp] lemma eq_iff_true_of_subsingleton {α : Sort*} [subsingleton α] (x y : α) : x = y ↔ true := by cc /-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/ lemma subsingleton_of_forall_eq {α : Sort*} (x : α) (h : ∀ y, y = x) : subsingleton α := ⟨λ a b, (h a).symm ▸ (h b).symm ▸ rfl⟩ lemma subsingleton_iff_forall_eq {α : Sort*} (x : α) : subsingleton α ↔ ∀ y, y = x := ⟨λ h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x⟩ -- TODO[gh-6025]: make this an instance once safe to do so lemma subtype.subsingleton (α : Sort*) [subsingleton α] (p : α → Prop) : subsingleton (subtype p) := ⟨λ ⟨x,_⟩ ⟨y,_⟩, have x = y, from subsingleton.elim _ _, by { cases this, refl }⟩ /-- Add an instance to "undo" coercion transitivity into a chain of coercions, because most simp lemmas are stated with respect to simple coercions and will not match when part of a chain. -/ @[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ] (a : α) : (a : γ) = (a : β) := rfl theorem coe_fn_coe_trans {α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl @[simp] theorem coe_fn_coe_base {α β} [has_coe α β] [has_coe_to_fun β] (x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl theorem coe_sort_coe_trans {α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl /-- Many structures such as bundled morphisms coerce to functions so that you can transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α` then you can write `e a` and this is elaborated as `⇑e a`. This type of coercion is implemented using the `has_coe_to_fun` type class. There is one important consideration: If a type coerces to another type which in turn coerces to a function, then it **must** implement `has_coe_to_fun` directly: ```lean structure sparkling_equiv (α β) extends α ≃ β -- if we add a `has_coe` instance, instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) := ⟨sparkling_equiv.to_equiv⟩ -- then a `has_coe_to_fun` instance **must** be added as well: instance {α β} : has_coe_to_fun (sparkling_equiv α β) := ⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩ ``` (Rationale: if we do not declare the direct coercion, then `⇑e a` is not in simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This often causes loops in the simplifier.) -/ library_note "function coercion" @[simp] theorem coe_sort_coe_base {α β} [has_coe α β] [has_coe_to_sort β] (x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl /-- `pempty` is the universe-polymorphic analogue of `empty`. -/ @[derive decidable_eq] inductive {u} pempty : Sort u /-- Ex falso, the nondependent eliminator for the `pempty` type. -/ def pempty.elim {C : Sort*} : pempty → C. instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩ @[simp] lemma not_nonempty_pempty : ¬ nonempty pempty := assume ⟨h⟩, h.elim @[simp] theorem forall_pempty {P : pempty → Prop} : (∀ x : pempty, P x) ↔ true := ⟨λ h, trivial, λ h x, by cases x⟩ @[simp] theorem exists_pempty {P : pempty → Prop} : (∃ x : pempty, P x) ↔ false := ⟨λ h, by { cases h with w, cases w }, false.elim⟩ lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂ | a _ rfl := heq.rfl lemma plift.down_inj {α : Sort*} : ∀ (a b : plift α), a.down = b.down → a = b | ⟨a⟩ ⟨b⟩ rfl := rfl -- missing [symm] attribute for ne in core. attribute [symm] ne.symm lemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩ @[simp] lemma eq_iff_eq_cancel_left {b c : α} : (∀ {a}, a = b ↔ a = c) ↔ (b = c) := ⟨λ h, by rw [← h], λ h a, by rw h⟩ @[simp] lemma eq_iff_eq_cancel_right {a b : α} : (∀ {c}, a = c ↔ b = c) ↔ (a = b) := ⟨λ h, by rw h, λ h a, by rw h⟩ /-- Wrapper for adding elementary propositions to the type class systems. Warning: this can easily be abused. See the rest of this docstring for details. Certain propositions should not be treated as a class globally, but sometimes it is very convenient to be able to use the type class system in specific circumstances. For example, `zmod p` is a field if and only if `p` is a prime number. In order to be able to find this field instance automatically by type class search, we have to turn `p.prime` into an instance implicit assumption. On the other hand, making `nat.prime` a class would require a major refactoring of the library, and it is questionable whether making `nat.prime` a class is desirable at all. The compromise is to add the assumption `[fact p.prime]` to `zmod.field`. In particular, this class is not intended for turning the type class system into an automated theorem prover for first order logic. -/ class fact (p : Prop) : Prop := (out [] : p) lemma fact.elim {p : Prop} (h : fact p) : p := h.1 lemma fact_iff {p : Prop} : fact p ↔ p := ⟨λ h, h.1, λ h, ⟨h⟩⟩ end miscellany /-! ### Declarations about propositional connectives -/ theorem false_ne_true : false ≠ true | h := h.symm ▸ trivial section propositional variables {a b c d : Prop} /-! ### Declarations about `implies` -/ instance : is_refl Prop iff := ⟨iff.refl⟩ instance : is_trans Prop iff := ⟨λ _ _ _, iff.trans⟩ theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩ @[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm @[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id theorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h theorem imp_false : (a → false) ↔ ¬ a := iff.rfl theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) := ⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩, λ h ha, ⟨h.left ha, h.right ha⟩⟩ @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb) theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) := iff_def.trans and.comm theorem imp_true_iff {α : Sort*} : (α → true) ↔ true := iff_true_intro $ λ_, trivial theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf, f ha, imp_intro⟩ /-! ### Declarations about `not` -/ /-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/ def not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 @[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp : ¬(a → b) → ¬¬a := mt not.elim theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p theorem dec_em' (p : Prop) [decidable p] : ¬p ∨ p := (dec_em p).swap theorem em (p : Prop) : p ∨ ¬p := classical.em _ theorem em' (p : Prop) : ¬p ∨ p := (em p).swap theorem or_not {p : Prop} : p ∨ ¬p := em _ section eq_or_ne variables {α : Sort*} (x y : α) theorem decidable.eq_or_ne [decidable (x = y)] : x = y ∨ x ≠ y := dec_em $ x = y theorem decidable.ne_or_eq [decidable (x = y)] : x ≠ y ∨ x = y := dec_em' $ x = y theorem eq_or_ne : x = y ∨ x ≠ y := em $ x = y theorem ne_or_eq : x ≠ y ∨ x = y := em' $ x = y end eq_or_ne theorem by_contradiction {p} : (¬p → false) → p := decidable.by_contradiction -- alias by_contradiction ← by_contra theorem by_contra {p} : (¬p → false) → p := decidable.by_contradiction /-- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `classical.choice` appears in the list. -/ library_note "decidable namespace" /-- As mathlib is primarily classical, if the type signature of a `def` or `lemma` does not require any `decidable` instances to state, it is preferable not to introduce any `decidable` instances that are needed in the proof as arguments, but rather to use the `classical` tactic as needed. In the other direction, when `decidable` instances do appear in the type signature, it is better to use explicitly introduced ones rather than allowing Lean to automatically infer classical ones, as these may cause instance mismatch errors later. -/ library_note "decidable arguments" -- See Note [decidable namespace] protected theorem decidable.not_not [decidable a] : ¬¬a ↔ a := iff.intro decidable.by_contradiction not_not_intro /-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`. The left-to-right direction, double negation elimination (DNE), is classically true but not constructively. -/ @[simp] theorem not_not : ¬¬a ↔ a := decidable.not_not theorem of_not_not : ¬¬a → a := by_contra -- See Note [decidable namespace] protected theorem decidable.of_not_imp [decidable a] (h : ¬ (a → b)) : a := decidable.by_contradiction (not_not_of_not_imp h) theorem of_not_imp : ¬ (a → b) → a := decidable.of_not_imp -- See Note [decidable namespace] protected theorem decidable.not_imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a := decidable.by_contradiction $ hb ∘ h theorem not.decidable_imp_symm [decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm theorem not.imp_symm : (¬a → b) → ¬b → a := not.decidable_imp_symm -- See Note [decidable namespace] protected theorem decidable.not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) := ⟨not.decidable_imp_symm, not.decidable_imp_symm⟩ theorem not_imp_comm : (¬a → b) ↔ (¬b → a) := decidable.not_imp_comm @[simp] theorem imp_not_self : (a → ¬a) ↔ ¬a := ⟨λ h ha, h ha ha, λ h _, h⟩ theorem decidable.not_imp_self [decidable a] : (¬a → a) ↔ a := by { have := @imp_not_self (¬a), rwa decidable.not_not at this } @[simp] theorem not_imp_self : (¬a → a) ↔ a := decidable.not_imp_self theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨swap, swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap /-! ### Declarations about `xor` -/ @[simp] theorem xor_true : xor true = not := funext $ λ a, by simp [xor] @[simp] theorem xor_false : xor false = id := funext $ λ a, by simp [xor] theorem xor_comm (a b) : xor a b = xor b a := by simp [xor, and_comm, or_comm] instance : is_commutative Prop xor := ⟨xor_comm⟩ @[simp] theorem xor_self (a : Prop) : xor a a = false := by simp [xor] /-! ### Declarations about `and` -/ theorem and_congr_left (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c := and.comm.trans $ (and_congr_right h).trans and.comm theorem and_congr_left' (h : a ↔ b) : a ∧ c ↔ b ∧ c := and_congr h iff.rfl theorem and_congr_right' (h : b ↔ c) : a ∧ b ↔ a ∧ c := and_congr iff.rfl h theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c := and.imp h id theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b := and.imp id h lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := by simp only [and.left_comm, and.comm] lemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp only [and.left_comm, and.comm] theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, h ha⟩) theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b := iff.intro and.right (λ hb, ⟨h hb, hb⟩) @[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) := ⟨λ h ha, (h.2 ha).2, and_iff_left_of_imp⟩ @[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) := ⟨λ h ha, (h.2 ha).1, and_iff_right_of_imp⟩ @[simp] lemma iff_self_and {p q : Prop} : (p ↔ p ∧ q) ↔ (p → q) := by rw [@iff.comm p, and_iff_left_iff_imp] @[simp] lemma iff_and_self {p q : Prop} : (p ↔ q ∧ p) ↔ (p → q) := by rw [and_comm, iff_self_and] @[simp] lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩ @[simp] lemma and.congr_left_iff : (a ∧ c ↔ b ∧ c) ↔ c → (a ↔ b) := by simp only [and.comm, ← and.congr_right_iff] @[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩ @[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩ /-! ### Declarations about `or` -/ theorem or_congr_left (h : a ↔ b) : a ∨ c ↔ b ∨ c := or_congr h iff.rfl theorem or_congr_right (h : b ↔ c) : a ∨ b ↔ a ∨ c := or_congr iff.rfl h theorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b] theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) := ⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩ theorem or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) := decidable.or_iff_not_imp_left -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) := or.comm.trans decidable.or_iff_not_imp_left theorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := decidable.or_iff_not_imp_right -- See Note [decidable namespace] protected theorem decidable.not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩ theorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := decidable.not_imp_not @[simp] theorem or_iff_left_iff_imp : (a ∨ b ↔ a) ↔ (b → a) := ⟨λ h hb, h.1 (or.inr hb), or_iff_left_of_imp⟩ @[simp] theorem or_iff_right_iff_imp : (a ∨ b ↔ b) ↔ (a → b) := by rw [or_comm, or_iff_left_iff_imp] /-! ### Declarations about distributivity -/ /-- `∧` distributes over `∨` (on the left). -/ theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := ⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha), or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩ /-- `∧` distributes over `∨` (on the right). -/ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm) /-- `∨` distributes over `∧` (on the left). -/ theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := ⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr), and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩ /-- `∨` distributes over `∧` (on the right). -/ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm) @[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b := ⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩ @[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b := ⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩ /-! Declarations about `iff` -/ theorem iff_of_true (ha : a) (hb : b) : a ↔ b := ⟨λ_, hb, λ _, ha⟩ theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b := ⟨ha.elim, hb.elim⟩ theorem iff_true_left (ha : a) : (a ↔ b) ↔ b := ⟨λ h, h.1 ha, iff_of_true ha⟩ theorem iff_true_right (ha : a) : (b ↔ a) ↔ b := iff.comm.trans (iff_true_left ha) theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b := ⟨λ h, mt h.2 ha, iff_of_false ha⟩ theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b := iff.comm.trans (iff_false_left ha) @[simp] lemma iff_mpr_iff_true_intro {P : Prop} (h : P) : iff.mpr (iff_true_intro h) true.intro = h := rfl -- See Note [decidable namespace] protected theorem decidable.not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem not_or_of_imp : (a → b) → ¬ a ∨ b := decidable.not_or_of_imp -- See Note [decidable namespace] protected theorem decidable.imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) := ⟨decidable.not_or_of_imp, or.neg_resolve_left⟩ theorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := decidable.imp_iff_not_or -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [decidable.imp_iff_not_or, or.comm, or.left_comm] theorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)] theorem imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib' theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩ h := hb $ h ha -- See Note [decidable namespace] protected theorem decidable.not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h, ⟨decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀ -- See Note [decidable namespace] protected theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h ha.elim theorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce _ _ theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id -- See Note [decidable namespace] protected theorem decidable.not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr decidable.not_imp_not decidable.not_imp_not theorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := decidable.not_iff_not -- See Note [decidable namespace] protected theorem decidable.not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr decidable.not_imp_comm imp_not_comm theorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := decidable.not_iff_comm -- See Note [decidable namespace] protected theorem decidable.not_iff : ∀ [decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) := by intro h; cases h; simp only [h, iff_true, iff_false] theorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := decidable.not_iff -- See Note [decidable namespace] protected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm decidable.not_imp_comm theorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := decidable.iff_not_comm -- See Note [decidable namespace] protected theorem decidable.iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by { split; intro h, { rw h; by_cases b; [left,right]; split; assumption }, { cases h with h h; cases h; split; intro; { contradiction <|> assumption } } } theorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := decidable.iff_iff_and_or_not_and_not lemma decidable.iff_iff_not_or_and_or_not [decidable a] [decidable b] : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := begin rw [iff_iff_implies_and_implies a b], simp only [decidable.imp_iff_not_or, or.comm] end lemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := decidable.iff_iff_not_or_and_or_not -- See Note [decidable namespace] protected theorem decidable.not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha, h.decidable_imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩ theorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := decidable.not_and_not_right /-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent. **Important**: this function should be used instead of `rw` on `decidable b`, because the kernel will get stuck reducing the usage of `propext` otherwise, and `dec_trivial` will not work. -/ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b := decidable_of_decidable_of_iff D h /-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent. This is the same as `decidable_of_iff` but the iff is flipped. -/ @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a := decidable_of_decidable_of_iff D h.symm /-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`. (This is sometimes taken as an alternate definition of decidability.) -/ def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a | tt h := is_true (h.1 rfl) | ff h := is_false (mt h.2 bool.ff_ne_tt) /-! ### De Morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb) -- See Note [decidable namespace] protected theorem decidable.not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩ -- See Note [decidable namespace] protected theorem decidable.not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩ /-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm /-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the conjunction of the negations. -/ theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩, λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, decidable.not_not] theorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not -- See Note [decidable namespace] protected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← decidable.not_and_distrib, decidable.not_not] theorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not end propositional /-! ### Declarations about equality -/ section equality variables {α : Sort*} {a b : α} @[simp] theorem heq_iff_eq : a == b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq := have p = q, from propext ⟨λ _, hq, λ _, hp⟩, by subst q; refl theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α} (h : a ∈ s) : b ∉ s → a ≠ b := mt $ λ e, e ▸ h lemma ne_of_apply_ne {α β : Sort*} (f : α → β) {x y : α} (h : f x ≠ f y) : x ≠ y := λ (w : x = y), h (congr_arg f w) theorem eq_equivalence : equivalence (@eq α) := ⟨eq.refl, @eq.symm _, @eq.trans _⟩ /-- Transport through trivial families is the identity. -/ @[simp] lemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') : (@eq.rec α a (λ a, β) y a' h) = y := by { cases h, refl, } @[simp] lemma eq_mp_eq_cast {α β : Sort*} (h : α = β) : eq.mp h = cast h := rfl @[simp] lemma eq_mpr_eq_cast {α β : Sort*} (h : α = β) : eq.mpr h = cast h.symm := rfl @[simp] lemma cast_cast : ∀ {α β γ : Sort*} (ha : α = β) (hb : β = γ) (a : α), cast hb (cast ha a) = cast (ha.trans hb) a | _ _ _ rfl rfl a := rfl @[simp] lemma congr_refl_left {α β : Sort*} (f : α → β) {a b : α} (h : a = b) : congr (eq.refl f) h = congr_arg f h := rfl @[simp] lemma congr_refl_right {α β : Sort*} {f g : α → β} (h : f = g) (a : α) : congr h (eq.refl a) = congr_fun h a := rfl @[simp] lemma congr_arg_refl {α β : Sort*} (f : α → β) (a : α) : congr_arg f (eq.refl a) = eq.refl (f a) := rfl @[simp] lemma congr_fun_rfl {α β : Sort*} (f : α → β) (a : α) : congr_fun (eq.refl f) a = eq.refl (f a) := rfl @[simp] lemma congr_fun_congr_arg {α β γ : Sort*} (f : α → β → γ) {a a' : α} (p : a = a') (b : β) : congr_fun (congr_arg f p) b = congr_arg (λ a, f a b) p := rfl lemma heq_of_cast_eq : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : cast e a = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.refl _) lemma cast_eq_iff_heq {α β : Sort*} {a : α} {a' : β} {e : α = β} : cast e a = a' ↔ a == a' := ⟨heq_of_cast_eq _, λ h, by cases h; refl⟩ lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) : @eq.rec α a C x b eq == y := by subst eq; exact h protected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : (x₁ = x₂) ↔ (y₁ = y₂) := by { subst h₁, subst h₂ } lemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h] lemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h] lemma congr_arg2 {α β γ : Type*} (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by { subst hx, subst hy } end equality /-! ### Declarations about quantifiers -/ section quantifiers variables {α : Sort*} {β : Sort*} {p q : α → Prop} {b : Prop} lemma forall_imp (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a := λ h' a, h a (h' a) lemma forall₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) : (∀ a b, p a b) ↔ (∀ a b, q a b) := forall_congr (λ a, forall_congr (h a)) lemma forall₃_congr {γ : Sort*} {p q : α → β → γ → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∀ a b c, p a b c) ↔ (∀ a b c, q a b c) := forall_congr (λ a, forall₂_congr (h a)) lemma forall₄_congr {γ δ : Sort*} {p q : α → β → γ → δ → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∀ a b c d, p a b c d) ↔ (∀ a b c d, q a b c d) := forall_congr (λ a, forall₃_congr (h a)) lemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a)) (hp : ∃ a, p a) : ∃ b, q b := exists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩) lemma exists₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) : (∃ a b, p a b) ↔ (∃ a b, q a b) := exists_congr (λ a, exists_congr (h a)) lemma exists₃_congr {γ : Sort*} {p q : α → β → γ → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∃ a b c, p a b c) ↔ (∃ a b c, q a b c) := exists_congr (λ a, exists₂_congr (h a)) lemma exists₄_congr {γ δ : Sort*} {p q : α → β → γ → δ → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∃ a b c d, p a b c d) ↔ (∃ a b c d, q a b c d) := exists_congr (λ a, exists₃_congr (h a)) theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y := ⟨swap, swap⟩ theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y := ⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩ @[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ /-- Extract an element from a existential statement, using `classical.some`. -/ -- This enables projection notation. @[reducible] noncomputable def Exists.some {p : α → Prop} (P : ∃ a, p a) : α := classical.some P /-- Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`. -/ lemma Exists.some_spec {p : α → Prop} (P : ∃ a, p a) : p (P.some) := classical.some_spec P --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_imp_of_exists_imp h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_imp_distrib.2 h @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x | ⟨x, hn⟩ h := hn (h x) -- See Note [decidable namespace] protected theorem decidable.not_forall {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.decidable_imp_symm $ λ nx x, nx.decidable_imp_symm $ λ h, ⟨x, h⟩, not_forall_of_exists_not⟩ @[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := decidable.not_forall -- See Note [decidable namespace] protected theorem decidable.not_forall_not [decidable (∃ x, p x)] : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := (@decidable.not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists theorem not_forall_not : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := decidable.not_forall_not -- See Note [decidable namespace] protected theorem decidable.not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := by simp [decidable.not_not] @[simp] theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := decidable.not_exists_not -- TODO: duplicate of a lemma in core theorem forall_true_iff : (α → true) ↔ true := implies_true_iff α -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true := iff_true_intro (λ _, of_iff_true (h _)) @[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true := forall_true_iff' $ λ _, forall_true_iff @[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} : (∀ a (b : β a), γ a b → true) ↔ true := forall_true_iff' $ λ _, forall_2_true_iff lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) @[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} : (∃! x, p x) ↔ ∃ x, p x := ⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩ @[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b := ⟨i.elim, λ hb x, hb⟩ @[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b := ⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩ theorem exists_unique_const (α : Sort*) [i : nonempty α] [subsingleton α] : (∃! x : α, b) ↔ b := by simp theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩ theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩), λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩ @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := by simp [and_comm] @[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩ @[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' := by simp [@eq_comm _ a'] -- this lemma is needed to simplify the output of `list.mem_cons_iff` @[simp] theorem forall_eq_or_imp {a' : α} : (∀ a, a = a' ∨ q a → p a) ↔ p a' ∧ ∀ a, q a → p a := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩ @[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' := ⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩ @[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' := (exists_congr $ by exact λ a, and.comm).trans exists_eq_left @[simp] theorem exists_eq_right_right {a' : α} : (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_eq_right_right' {a' : α} : (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_apply_eq_apply {α β : Type*} (f : α → β) (a' : α) : ∃ a, f a = f a' := ⟨a', rfl⟩ @[simp] theorem exists_apply_eq_apply' {α β : Type*} (f : α → β) (a' : α) : ∃ a, f a' = f a := ⟨a', rfl⟩ @[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) := ⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩ @[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} : (∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) := ⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩ @[simp] lemma exists_or_eq_left (y : α) (p : α → Prop) : ∃ (x : α), x = y ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ x = y := ⟨y, or.inr rfl⟩ @[simp] lemma exists_or_eq_left' (y : α) (p : α → Prop) : ∃ (x : α), y = x ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right' (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ y = x := ⟨y, or.inr rfl⟩ @[simp] theorem forall_apply_eq_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, f a = b → p b) ↔ (∀ a, p (f a)) := ⟨λ h a, h a (f a) rfl, λ h a b hab, hab ▸ h a⟩ @[simp] theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, f a = b → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_eq_apply_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, b = f a → p b) ↔ (∀ a, p (f a)) := by simp [@eq_comm _ _ (f _)] @[simp] theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, b = f a → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_apply_eq_imp_iff₂ {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ b, ∀ a, p a → f a = b → q b) ↔ ∀ a, p a → q (f a) := ⟨λ h a ha, h (f a) a ha rfl, λ h b a ha hb, hb ▸ h a ha⟩ @[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' := by simp [@eq_comm _ a'] theorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b := ⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩ theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x := h.imp_right $ λ h₂, h₂ x -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq, forall_or_of_or_forall⟩ theorem forall_or_distrib_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := decidable.forall_or_distrib_left -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := by simp [or_comm, decidable.forall_or_distrib_left] theorem forall_or_distrib_right {q : Prop} {p : α → Prop} : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := decidable.forall_or_distrib_right /-- A predicate holds everywhere on the image of a surjective functions iff it holds everywhere. -/ theorem forall_iff_forall_surj {α β : Type*} {f : α → β} (h : function.surjective f) {P : β → Prop} : (∀ a, P (f a)) ↔ ∀ b, P b := ⟨λ ha b, by cases h b with a hab; rw ←hab; exact ha a, λ hb a, hb $ f a⟩ @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩ theorem exists_unique_prop {p q : Prop} : (∃! h : p, q) ↔ p ∧ q := by simp @[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h @[simp] lemma exists_unique_false : ¬ (∃! (a : α), false) := assume ⟨a, h, h'⟩, h theorem Exists.fst {p : b → Prop} : Exists p → b | ⟨h, _⟩ := h theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst | ⟨_, h⟩ := h theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h := @exists_const (q h) p ⟨h⟩ theorem exists_unique_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃! h' : p, q h') ↔ q h := @exists_unique_const (q h) p ⟨h⟩ _ theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true := iff_true_intro $ λ h, hn.elim h theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') := mt Exists.fst @[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q ↔ ∃ h : p', q' (hp.2 h) := ⟨λ ⟨_, _⟩, ⟨hp.1 ‹_›, (hq _).1 ‹_›⟩, λ ⟨_, _⟩, ⟨_, (hq _).2 ‹_›⟩⟩ @[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q = ∃ h : p', q' (hp.2 h) := propext (exists_prop_congr hq _) @[simp] lemma exists_true_left (p : true → Prop) : (∃ x, p x) ↔ p true.intro := exists_prop_of_true _ @[simp] lemma exists_false_left (p : false → Prop) : ¬ ∃ x, p x := exists_prop_of_false not_false lemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := unique_of_exists_unique h py₁ py₂ @[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) ↔ ∀ h : p', q' (hp.2 h) := ⟨λ h1 h2, (hq _).1 (h1 (hp.2 _)), λ h1 h2, (hq _).2 (h1 (hp.1 h2))⟩ @[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) = ∀ h : p', q' (hp.2 h) := propext (forall_prop_congr hq _) @[simp] lemma forall_true_left (p : true → Prop) : (∀ x, p x) ↔ p true.intro := forall_prop_of_true _ @[simp] lemma forall_false_left (p : false → Prop) : (∀ x, p x) ↔ true := forall_prop_of_false not_false lemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h) (h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b := begin simp only [exists_unique_iff_exists] at h₂, apply h₂.elim, exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩) end lemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ y (hy : p y), q y hy → y = w) : ∃! x (hx : p x), q x hx := begin simp only [exists_unique_iff_exists], exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq) end lemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop} (h : ∃! x (hx : p x), q x hx) : ∃ x (hx : p x), q x hx := h.exists.imp (λ x hx, hx.exists) lemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx) {y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := begin simp only [exists_unique_iff_exists] at h, exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩ end end quantifiers /-! ### Classical lemmas -/ namespace classical variables {α : Sort*} {p : α → Prop} theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 /- use shortened names to avoid conflict when classical namespace is open. -/ noncomputable lemma dec (p : Prop) : decidable p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_pred (p : α → Prop) : decidable_pred p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_rel (p : α → α → Prop) : decidable_rel p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_eq (α : Sort*) : decidable_eq α := -- see Note [classical lemma] by apply_instance /-- We make decidability results that depends on `classical.choice` noncomputable lemmas. * We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode for them, and fail because it depends on `classical.choice`. * We make them lemmas, and not definitions, because otherwise later definitions will raise \"failed to generate bytecode\" errors when writing something like `letI := classical.dec_eq _`. Cf. <https://leanprover-community.github.io/archive/stream/113488-general/topic/noncomputable.20theorem.html> -/ library_note "classical lemma" /-- Construct a function from a default value `H0`, and a function to use if there exists a value satisfying the predicate. -/ @[elab_as_eliminator] noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C := if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0 lemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a} (q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) := hpq _ $ some_spec _ /-- A version of classical.indefinite_description which is definitionally equal to a pair -/ noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} := ⟨classical.some h, classical.some_spec h⟩ /-- A version of `by_contradiction` that uses types instead of propositions. -/ protected noncomputable def by_contradiction' {α : Sort*} (H : ¬ (α → false)) : α := classical.choice $ peirce _ false $ λ h, (H $ λ a, h ⟨a⟩).elim /-- `classical.by_contradiction'` is equivalent to lean's axiom `classical.choice`. -/ def choice_of_by_contradiction' {α : Sort*} (contra : ¬ (α → false) → α) : nonempty α → α := λ H, contra H.elim end classical /-- This function has the same type as `exists.rec_on`, and can be used to case on an equality, but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe using the axiom of choice. -/ @[elab_as_eliminator] noncomputable def {u} exists.classical_rec_on {α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C := H (classical.some h) (classical.some_spec h) /-! ### Declarations about bounded quantifiers -/ section bounded_quantifiers variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop} theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b | ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂ theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h := ⟨a, h₁, h₂⟩ theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) : (∀ x h, P x h) ↔ (∀ x h, Q x h) := forall_congr $ λ x, forall_congr (H x) theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) : (∃ x h, P x h) ↔ (∃ x h, Q x h) := exists_congr $ λ x, exists_congr (H x) theorem bex_eq_left {a : α} : (∃ x (_ : x = a), p x) ↔ p a := by simp only [exists_prop, exists_eq_left] theorem ball.imp_right (H : ∀ x h, (P x h → Q x h)) (h₁ : ∀ x h, P x h) (x h) : Q x h := H _ _ $ h₁ _ _ theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) : (∃ x h, P x h) → ∃ x h, Q x h | ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩ theorem ball.imp_left (H : ∀ x, p x → q x) (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x := h₁ _ $ H _ h theorem bex.imp_left (H : ∀ x, p x → q x) : (∃ x (_ : p x), r x) → ∃ x (_ : q x), r x | ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩ theorem ball_of_forall (h : ∀ x, p x) (x) : p x := h x theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x := h x $ H x theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x | ⟨x, hq⟩ := ⟨x, H x, hq⟩ theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x | ⟨x, _, hq⟩ := ⟨x, hq⟩ @[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) := by simp theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h := bex_imp_distrib theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h | ⟨x, h, hp⟩ al := hp $ al x h -- See Note [decidable namespace] protected theorem decidable.not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := ⟨not.decidable_imp_symm $ λ nx x h, nx.decidable_imp_symm $ λ h', ⟨x, h, h'⟩, not_ball_of_bex_not⟩ theorem not_ball : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := decidable.not_ball theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) := iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) := iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib theorem ball_or_left_distrib : (∀ x, p x ∨ q x → r x) ↔ (∀ x, p x → r x) ∧ (∀ x, q x → r x) := iff.trans (forall_congr $ λ x, or_imp_distrib) forall_and_distrib theorem bex_or_left_distrib : (∃ x (_ : p x ∨ q x), r x) ↔ (∃ x (_ : p x), r x) ∨ (∃ x (_ : q x), r x) := by simp only [exists_prop]; exact iff.trans (exists_congr $ λ x, or_and_distrib_right) exists_or_distrib end bounded_quantifiers namespace classical local attribute [instance] prop_decidable theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball end classical lemma ite_eq_iff {α} {p : Prop} [decidable p] {a b c : α} : (if p then a else b) = c ↔ p ∧ a = c ∨ ¬p ∧ b = c := by by_cases p; simp * @[simp] lemma ite_eq_left_iff {α} {p : Prop} [decidable p] {a b : α} : (if p then a else b) = a ↔ (¬p → b = a) := by by_cases p; simp * @[simp] lemma ite_eq_right_iff {α} {p : Prop} [decidable p] {a b : α} : (if p then a else b) = b ↔ (p → a = b) := by by_cases p; simp * lemma ite_eq_or_eq {α} {p : Prop} [decidable p] (a b : α) : ite p a b = a ∨ ite p a b = b := decidable.by_cases (λ h, or.inl (if_pos h)) (λ h, or.inr (if_neg h)) /-! ### Declarations about `nonempty` -/ section nonempty universe variables u v w variables {α : Type u} {β : Type v} {γ : α → Type w} attribute [simp] nonempty_of_inhabited @[priority 20] instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩ @[priority 20] instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩ lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α := iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩) @[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p := iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩) lemma not_nonempty_iff_imp_false {α : Sort*} : ¬ nonempty α ↔ α → false := ⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩ @[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_subtype {α : Sort u} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) := iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩) @[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_pprod {α : Sort u} {β : Sort v} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end) @[simp] lemma nonempty_psum {α : Sort u} {β : Sort v} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end) @[simp] lemma nonempty_psigma {α : Sort u} {β : α → Sort v} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_empty : ¬ nonempty empty := assume ⟨h⟩, h.elim @[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty_plift {α : Sort u} : nonempty (plift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty.forall {α : Sort u} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) := iff.intro (assume h a, h _) (assume h ⟨a⟩, h _) @[simp] lemma nonempty.exists {α : Sort u} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) := iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩) lemma classical.nonempty_pi {α : Sort u} {β : α → Sort v} : nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) := iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩) /-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued) `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in `core/init/classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ noncomputable def classical.inhabited_of_nonempty' {α : Sort u} [h : nonempty α] : inhabited α := ⟨classical.choice h⟩ /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def nonempty.some {α : Sort u} (h : nonempty α) : α := classical.choice h /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def classical.arbitrary (α : Sort u) [h : nonempty α] : α := classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/ lemma nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : nonempty α → nonempty β | ⟨h⟩ := ⟨f h⟩ protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ | ⟨x⟩ ⟨y⟩ := ⟨f x y⟩ protected lemma nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) : nonempty α ↔ nonempty β := ⟨nonempty.map f, nonempty.map g⟩ lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop} (f : inhabited α → p) : p := h.elim $ f ∘ inhabited.mk instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) := h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩ end nonempty lemma subsingleton_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : subsingleton α := ⟨λ x, false.elim $ not_nonempty_iff_imp_false.mp h x⟩ section ite /-- A `dite` whose results do not actually depend on the condition may be reduced to an `ite`. -/ @[simp] lemma dite_eq_ite (P : Prop) [decidable P] {α : Sort*} (x y : α) : dite P (λ h, x) (λ h, y) = ite P x y := rfl /-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/ lemma apply_dite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (λ h, f (x h)) (λ h, f (y h)) := by { by_cases h : P; simp [h] } /-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/ lemma apply_ite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x y : α) : f (ite P x y) = ite P (f x) (f y) := apply_dite f P (λ _, x) (λ _, y) /-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function applied to each of the branches. -/ lemma apply_dite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (λ h, f (a h) (c h)) (λ h, f (b h) (d h)) := by { by_cases h : P; simp [h] } /-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function applied to each of the branches. -/ lemma apply_ite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a b : α) (c d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) := apply_dite2 f P (λ _, a) (λ _, b) (λ _, c) (λ _, d) /-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α` is a `dite` that applies either branch to `x`. -/ lemma dite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P] (f : P → Π a, β a) (g : ¬ P → Π a, β a) (x : α) : (dite P f g) x = dite P (λ h, f h x) (λ h, g h x) := by { by_cases h : P; simp [h] } /-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α` is a `ite` that applies either branch to `x` -/ lemma ite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P] (f g : Π a, β a) (x : α) : (ite P f g) x = ite P (f x) (g x) := dite_apply P (λ _, f) (λ _, g) x /-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/ @[simp] lemma dite_not {α : Sort*} (P : Prop) [decidable P] (x : ¬ P → α) (y : ¬¬ P → α) : dite (¬ P) x y = dite P (λ h, y (not_not_intro h)) x := by { by_cases h : P; simp [h] } /-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/ @[simp] lemma ite_not {α : Sort*} (P : Prop) [decidable P] (x y : α) : ite (¬ P) x y = ite P y x := dite_not P (λ _, x) (λ _, y) lemma ite_and {α} {p q : Prop} [decidable p] [decidable q] {x y : α} : ite (p ∧ q) x y = ite p (ite q x y) y := by { by_cases hp : p; by_cases hq : q; simp [hp, hq] } end ite
afae24ac8e543ab71f137fe8008735625c9492b5
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/polynomial/eval.lean
757ea5ca229cf05ca28a4bc02eb6292de2274632
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,819
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.induction import data.polynomial.degree.basic import deprecated.ring /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : polynomial R} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by simp [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by rw [f.map_one, one_mul, pow_one] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := begin apply sum_single_index, simp, end @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw ←monomial_one_eq_X_pow, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [f.map_zero, zero_mul]) (λ _ _ _, by rw [f.map_add, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s • eval₂ g x p := begin simp only [eval₂, sum_smul_index, forall_const, zero_mul, g.map_zero, g.map_mul, mul_assoc], -- Why doesn't `rw [←finsupp.mul_sum]` work? convert (@finsupp.mul_sum _ _ _ _ _ (g s) p (λ i a, (g a * x ^ i))).symm, end instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n := nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] variables [semiring T] lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := begin classical, induction s using finset.induction with p hp s hs, simp, rw [sum_insert, eval₂_add, hs, sum_insert]; assumption, end lemma eval₂_mul_noncomm (hf : ∀ b a, f b * a = a * f b) : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin have f_zero : ∀ (a : ℕ), f 0 * x ^ a = 0, { intro, simp }, have f_add : ∀ (a : ℕ) (b₁ b₂ : R), f (b₁ + b₂) * x ^ a = f b₁ * x ^ a + f b₂ * x ^ a, { intros, rw [f.map_add, add_mul] }, simp_rw [eval₂, add_monoid_algebra.mul_def, finsupp.sum_mul _ p, finsupp.mul_sum _ q], rw sum_sum_index; try { assumption }, apply sum_congr rfl, assume i hi, dsimp only, rw sum_sum_index; try { assumption }, apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, is_semiring_hom.map_mul f, pow_add], { rw [mul_assoc, ←mul_assoc _ (x ^ i), hf _ (x ^ i), mul_assoc, mul_assoc] }, { apply f_zero } end lemma eval₂_list_prod_noncomm (ps : list (polynomial R)) (hf : ∀ b a, f b * a = a * f b): ps.prod.eval₂ f x = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps, { simp }, { simp [eval₂_mul_noncomm _ _ hf, ps_ih] {contextual := tt} } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (hf : ∀ b a, f b * a = a * f b) (x : S) : polynomial R →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ _ _, eval₂_mul_noncomm _ _ hf, map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ variables [comm_semiring S] variables (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin apply eval₂_mul_noncomm, simp [mul_comm] end lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S := ring_hom.of (eval₂ f x) @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = sum p (λ e a, a * x ^ e) := rfl @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} : (s • p).eval x = s • p.eval x := eval₂_smul (ring_hom.id _) _ _ lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin refine ext (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, congr, convert finsupp.sum_single _, end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← p.support.sum_hom (@C R _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : polynomial R) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : polynomial R) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C.comp f) X instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) := is_semiring_hom.comp _ _ @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, single_eq_C_mul_X], refl, end @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n := nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, map_add, ih, map_one, n.cast_succ] @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← p.support.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, f.map_mul], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map [semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f): function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] variables {f} lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp [hp] ... = f x * (p.map f).coeff p.nat_degree : by { congr, apply (coeff_map _ _).symm } ... = 0 : by simp [hfp], λ h, ext (λ n, trans (coeff_map f n) (h _)) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) variables (f) open is_semiring_hom -- If the rings were commutative, we could prove this just using `eval₂_mul`. -- TODO this proof is just a hack job on the proof of `eval₂_mul`, -- using that `X` is central. It should probably be golfed! @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := begin dunfold map, dunfold eval₂, rw [add_monoid_algebra.mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, (C.comp f).map_mul, pow_add], { simp [←mul_assoc], conv_lhs { rw ←@X_pow_mul_assoc _ _ _ _ i }, }, { simp, } }, { intro, simp, }, { intros, simp [add_mul], } }, { intro, simp, }, { intros, simp [add_mul], } end instance map.is_semiring_hom : is_semiring_hom (map f) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ _ _, eval₂_add _ _, map_mul := λ _ _, map_mul f, } lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (monoid_hom.of (map f)) @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := is_monoid_hom.map_pow (map f) _ _ lemma mem_map_range {p : polynomial S} : p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) := begin split, { rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ }, { intro h, rw p.as_sum_range, apply is_add_submonoid.finset_sum_mem, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [map_mul, map_C, hc, map_pow, map_X] } end lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := begin convert finsupp.sum_map_range_index _, { change map f p = map_range f _ p, ext, rw map_range_apply, exact coeff_map f a, }, { exact f.map_zero, }, { intro a, simp only [ring_hom.map_zero, zero_mul], }, end lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map f (ring_hom.id _) x end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ -- TODO: Here we need commutativity in both `S` and `T`? variables [comm_semiring S] [comm_semiring T] variables (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C], refl, }, { intros p q hp hq, simp only [hp, hq, eval₂_add, g.map_add] }, { intros n a ih, simp only [eval₂_mul, eval₂_C, eval₂_X_pow, g.map_mul, g.map_pow], refl, } end end hom_eval₂ end semiring section comm_semiring section eval variables [comm_semiring R] {p q : polynomial R} {x : R} @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] /-- Polynomial evaluation commutes with finset.prod -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := begin classical, apply finset.induction_on s, { simp only [finset.prod_empty, eval_one] }, { intros j s hj hpj, have h0 : ∏ i in insert j s, eval x (p i) = (eval x (p j)) * ∏ i in s, eval x (p i), { apply finset.prod_insert hj }, rw [h0, ← hpj, finset.prod_insert hj, eval_mul] }, end end eval section map variables [comm_semiring R] [comm_semiring S] (f : R →+* S) lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (monoid_hom.of (map f)) lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := eq.symm $ prod_hom _ _ lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := eq.symm $ sum_hom _ _ lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support := begin intros x, simp only [mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f, end lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp) (by simp {contextual := tt}) (by simp [pow_succ', ← mul_assoc, polynomial.comp] {contextual := tt}) end map end comm_semiring section ring variables [ring R] {p q r : polynomial R} -- @[simp] -- lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) := -- (C : R →+* _).map_int_cast n lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b instance map.is_ring_hom {S} [ring S] (f : R →+* S) : is_ring_hom (map f) := by apply is_ring_hom.of_semiring @[simp] lemma map_sub {S} [comm_ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {S} [comm_ring S] (f : R →+* S) : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ end ring section comm_ring variables [comm_ring R] {p q : polynomial R} instance eval₂.is_ring_hom {S} [comm_ring S] (f : R →+* S) {x : S} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _ end comm_ring end polynomial
fb6affb316622567ddd0a1f8f08bf3dada52e251
05d69962fb9deab19838de9bbcf33ebdbf8faa57
/sum.lean
c5cdffc74f3326b3e3a60a2687aa8a9866eeb408
[]
no_license
pj0y1/polynom
6eb7c96dbf34960be5721a232a67f7a592aedf7a
9e198cc9104017fae7774574f141197bb295ee66
refs/heads/master
1,611,193,417,139
1,501,472,138,000
1,501,472,138,000
64,856,946
0
0
null
null
null
null
UTF-8
Lean
false
false
7,432
lean
/-A concise version of m14.lean and m15.lean Containing theories of Sum exchange and Sum curry, Sum reduced -/ import data.set data.finset algebra.group_bigops import aux local attribute prod.has_decidable_eq[instance] open prod.ops function variables {A B C:Type}{a:A}{b:B} variables [deceqA: decidable_eq A][deceqB: decidable_eq B][c: semiring C] variables {f:A->B->C}{f': A×B -> C} namespace finset variables {s s₁:finset A}{t t₁:finset B} include deceqA deceqB c /-Sum can exchange-/ --originally l10 in m14.lean lemma exSum_aux1 :(∑ x∈∅,∑ y∈t, f x y) = ∑ y∈t, ∑ x∈∅, f x y := by rewrite [Sum_empty,Sum_zero] -- originally l11 in m14.lean lemma exSum_aux2 (H: a ∉ s):(∑ x∈(insert a s),∑ y∈t, f x y) = (∑ y∈t, f a y) + (∑ x∈s,∑y∈t, f x y):= by rewrite [(Sum_insert_of_not_mem _ H)] -- originally l12 in m14.lean lemma exSum_aux3 (H: a∉ s): (∑ y∈t,∑x∈(insert a s), f x y)= ∑ y∈t,(f a y + ∑ x∈s, f x y) := Sum_ext (take y, assume h, by rewrite (Sum_insert_of_not_mem _ H)) -- originally t4 in m14.lean theorem Sum_exchange : (∑ x∈s,∑ y∈t, f x y) = ∑ y∈t, ∑ x∈s, f x y := finset.induction_on s exSum_aux1 (λ a s0 nin h, by rewrite[(exSum_aux2 nin),(exSum_aux3 nin),Sum_add,h] ) /- Sum can have curried/uncurried form -/ -- originally t1 in m14.lean lemma Sum_uncurry_singleton: (∑ x ∈ '{a}, ∑ y ∈ '{b}, f x y )= ∑ z ∈ '{a}*'{b}, (uncurry f) z := by rewrite [(Sum_singleton a _)] -- originally curry_l1 in m14.lean lemma Sum_uncurry_empty_left: (∑ x∈∅*t, (uncurry f) x) = ∑ x∈∅,∑ y∈t, f x y := by rewrite [(empty_product t), Sum_empty] -- originally subgoal2 in m14.lean lemma Sum_uncurry_empty_right : (∑x∈s*∅, (uncurry f) x) = ∑ x∈s,∑y∈∅, f x y := by rewrite [product_empty,Sum_empty,Sum_zero] -- originally sup1 in m14.lean lemma Sum_uncurry_aux1 (h: t∩t₁ = ∅):(∑ x∈s*(t∪t₁), (uncurry f) x) = (∑ x∈s*t, (uncurry f) x) + (∑ x∈s*t₁, (uncurry f ) x):= by rewrite [product.union_right_distrib, (Sum_union _ (product.disjoint_of_disjoint_right h))] -- originally sup2 in m14.lean lemma Sum_uncurry_aux2 (h:t∩t₁ = ∅): (∑x∈s, ∑y∈t∪t₁, f x y) = ∑ x∈s, (∑ y∈t, f x y) + (∑y∈t₁, f x y) := Sum_ext (take x, assume hx, by rewrite (Sum_union _ h)) -- originally sup3 in m14.lean lemma Sum_uncurry_aux3 (h:t∩t₁ = ∅): (∑ x∈s, (∑ y∈t, f x y) + (∑y∈t₁, f x y)) = (∑ x∈s,∑y∈t, f x y) + ∑ x∈s, ∑y∈t₁, f x y := by rewrite Sum_add -- originally subgoal1 in m14.lean lemma Sum_uncurry_aux4 : (∑ x∈'{a}*t, (uncurry f) x) = ∑ x∈'{a},∑y∈t, f x y := finset.induction_on t Sum_uncurry_empty_right (λ x t0 xnin h, have h1:'{x}∩t0 = ∅, from singleton_inter_of_not_mem xnin, by rewrite [(insert_eq x t0),(Sum_uncurry_aux2 h1),(Sum_uncurry_aux1 h1), (Sum_uncurry_aux3 h1),h,Sum_uncurry_singleton]) -- originally sup4 in m14.lean lemma Sum_uncurry_aux5 (h:s∩s₁ = ∅): (∑ x∈(s∪s₁)*t, (uncurry f) x) = (∑ x∈s*t,(uncurry f) x) + (∑x∈s₁*t,(uncurry f) x) := by rewrite [product.union_left_distrib, (Sum_union _ (product.disjoint_of_disjoint_left h))] -- originally sup5 in m14.lean lemma Sum_uncurry_aux6 (h:s∩s₁ = ∅): (∑ x∈s∪s₁, ∑y∈t, f x y) = (∑ x∈s, ∑ y∈t, f x y) + (∑x∈s₁, ∑y∈t, f x y) := by rewrite (Sum_union _ h) -- origianlly final_goal in m14.lean theorem Sum_uncurry : (∑ x∈s*t, (uncurry f) x) = ∑ x∈s, ∑ y∈t, f x y := finset.induction_on s Sum_uncurry_empty_left (λu s0 unin h, have '{u}∩s0 = ∅, from singleton_inter_of_not_mem unin, by rewrite [(insert_eq u s0),(Sum_uncurry_aux5 this), (Sum_uncurry_aux6 this),Sum_uncurry_aux4,h]) theorem Sum_curry : (∑ x∈s*t, f' x) = ∑x∈s, ∑y∈t, (curry f') x y := by rewrite [-(uncurry_curry f'),Sum_uncurry] end finset namespace set variables {s s₁: set A}{t:set B}[fins : finite s][fint: finite t] variables {g:A -> B -> C}{k: A -> C} section open [notation]finset include fins fint c lemma exSum_aux1 : (∑ x∈s, ∑y∈ t, f x y) = ∑ x∈ (to_finset s), ∑y∈(to_finset t), f x y := by rewrite Sum_def lemma exSum_aux2 : (∑ y∈t, ∑ x∈s, f x y) = ∑ y∈(to_finset t), ∑x∈(to_finset s), f x y := by rewrite Sum_def include deceqA deceqB theorem Sum_exchange : (∑ x∈ s, ∑y∈ t,f x y) = ∑ x∈t, ∑ y∈s, f y x := by rewrite [exSum_aux1,exSum_aux2,finset.Sum_exchange] lemma Sum_uncurry_aux1 :(∑ x∈s*t, (uncurry f) x) = ∑ x∈(to_finset s)*(to_finset t), (uncurry f) x := have finite (product s t), from !finite_product, by rewrite [Sum_def,to_finset_product] lemma Sum_uncurry_aux2 : (∑ x∈s,∑y∈t, f x y) = ∑ x∈(to_finset s),∑ y∈(to_finset t), f x y:= by rewrite Sum_def theorem Sum_uncurry:(∑ x∈ s*t, (uncurry f) x) = ∑ x∈s,∑y∈t, f x y:= by rewrite [Sum_uncurry_aux1, Sum_uncurry_aux2, finset.Sum_uncurry] theorem Sum_curry: (∑ x∈ s*t, f' x) = ∑x∈s,∑y∈t, (curry f') x y := by rewrite [-(uncurry_curry f'),Sum_uncurry] theorem eq_sum_of_eq_fun (h:∀ x y, f x y = g x y): (∑ x∈s,∑y∈t, f x y)=∑x∈s,∑y∈t, g x y := have f = g, from funext (λx, funext (λ y, h x y)), by rewrite this end /- Properties of reduced set of Sum: originally in m15.lean -/ section open classical include c lemma eq_zero_of_inter_empty(h: s∩s₁ = ∅): (∑x∈s, (ite (s₁ x) 1 0)*(k x)) = ∑ x∈s, (0:C) := Sum_ext(λ x hin, have x∉s₁, from proof suppose x∈s₁, show false, by rewrite [-(mem_empty_eq x),-h]; apply mem_inter hin this qed, have (ite (s₁ x) (1:C) 0) = 0, from if_neg this, by rewrite [this];simp) include fins lemma Sum_reduced_aux1:(∑x∈s, k x)=(∑x∈s∩s₁,k x)+∑x∈s\s₁, k x := have finite (s∩s₁), from finite_subset (inter_subset_left s s₁), have finite (s\s₁), from finite_subset (diff_subset s s₁), have (s∩s₁)∩(s\s₁)=∅, from inter_inter_diff_empty, by rewrite [(@inter_union_diff_cancel A s₁ s)at{1},(Sum_union _ this)] omit fins lemma Sum_reduced_aux2(h:s⊆s₁): (∑x∈s,(ite (s₁ x) 1 0)*(k x)) = ∑x∈s, k x := Sum_ext(λ x hin, have x∈s₁, from mem_of_subset_of_mem h hin, have (ite (s₁ x) (1:C) 0) = 1, from if_pos this, by rewrite [this];apply semiring.one_mul) include fins theorem Sum_reduced: (∑x∈s, (ite (s₁ x) 1 0)*(k x))=∑x∈s∩s₁, k x := by rewrite [(@Sum_reduced_aux1 A C _ s s₁ _ _), (eq_zero_of_inter_empty (@diff_inter_self_empty A s₁ s)), Sum_zero, (Sum_reduced_aux2 (inter_subset_right s s₁))];apply semiring.add_zero theorem Sum_reduced_flex (h:∀x, x∈s\s₁ -> k x = 0): (∑x∈s, k x) = ∑x∈s∩s₁, k x := have (∑x∈s\s₁, k x) =∑x∈s\s₁, 0, by apply Sum_ext;intro x hx; apply (h x hx), have (∑x∈s\s₁, k x) = 0, by rewrite [this,Sum_zero], by rewrite [(@Sum_reduced_aux1 A C _ s s₁ _ _),this];simp check @Sum_reduced_flex end end set
9015c5e3fc21b35275c44a5fffb6845b1f548bff
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/order/lattice_extra.lean
011040f783e81498e2105c3ca9671f0a2e22681e
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,861
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Some additional typeclass instances: * A set with decidable linear order and top and bottom elements is a bounded distributive lattice * If we take a set with decidable linear order and adjoin top and bottom elements, we again get a bounded distributive lattice * A sup-semilattice becomes a monoid under the sup operation. * Dually, an inf-semilattice becomes a monoid under the inf operation. -/ import order.bounded_lattice namespace lattice open lattice instance bounded_distrib_lattice_of_decidable_linear_order {α : Type*} [decidable_linear_order α] (top : α) (le_top : ∀ a, a ≤ top) (bot : α) (bot_le : ∀ a, bot ≤ a) : bounded_distrib_lattice α := { top := top, bot := bot, le_top := le_top, bot_le := bot_le, .. (lattice.distrib_lattice_of_decidable_linear_order) } instance wtb_bdl_of_dlo (α : Type*) [decidable_linear_order α] : bounded_distrib_lattice (with_top (with_bot α)) := @lattice.bounded_distrib_lattice_of_decidable_linear_order (with_top (with_bot α)) _ (has_top.top _) (@lattice.le_top _ _) (has_bot.bot _) (@lattice.bot_le _ _) instance inf_monoid {α : Type*} [semilattice_inf_top α] : comm_monoid α := { mul := has_inf.inf, one := has_top.top α, one_mul := @top_inf_eq α _, mul_one := @inf_top_eq α _, mul_comm := @inf_comm α _, mul_assoc := @inf_assoc α _, } instance sup_monoid {α : Type*} [semilattice_sup_bot α] : comm_monoid α := { mul := has_sup.sup, one := has_bot.bot α, one_mul := @bot_sup_eq α _, mul_one := @sup_bot_eq α _, mul_comm := @sup_comm α _, mul_assoc := @sup_assoc α _, } end lattice
4f0f36425c5449056ffee73d262374b27fb35be5
4e3bf8e2b29061457a887ac8889e88fa5aa0e34c
/lean/love13_rational_and_real_numbers_demo.lean
05523ef1633f362ea1dfe503177d252c927c383e
[]
no_license
mukeshtiwari/logical_verification_2019
9f964c067a71f65eb8884743273fbeef99e6503d
16f62717f55ed5b7b87e03ae0134791a9bef9b9a
refs/heads/master
1,619,158,844,208
1,585,139,500,000
1,585,139,500,000
249,906,380
0
0
null
1,585,118,728,000
1,585,118,727,000
null
UTF-8
Lean
false
false
8,814
lean
/- LoVe Demo 13: Rational and Real Numbers -/ import .lovelib namespace LoVe set_option pp.beta true /- Rational Numbers -/ structure fraction := (num : ℤ) (denom : ℤ) (denom_ne_zero : denom ≠ 0) export fraction (num denom denom_ne_zero) instance fraction.setoid : setoid fraction := { r := λa b, num a * denom b = num b * denom a, iseqv := begin apply and.intro, { intros a, refl }, apply and.intro, { intros a b h, cc }, { intros a b c eq_ab eq_bc, apply eq_of_mul_eq_mul_right (denom_ne_zero b), cc } end } lemma fraction.setoid_iff (a b : fraction) : a ≈ b ↔ num a * denom b = num b * denom a := by refl def myℚ : Type := quotient fraction.setoid def fraction.of_int (z : ℤ) : fraction := { num := z, denom := 1, denom_ne_zero := by simp } instance fraction.has_zero : has_zero fraction := { zero := fraction.of_int 0 } instance myℚ.has_zero : has_zero myℚ := { zero := ⟦0⟧ } instance fraction.has_one : has_one fraction := { one := fraction.of_int 1 } instance myℚ.has_one : has_one myℚ := { one := ⟦1⟧ } instance fraction.has_add : has_add fraction := { add := λa b : fraction, { num := num a * denom b + num b * denom a, denom := denom a * denom b, denom_ne_zero := begin apply mul_ne_zero, { exact (denom_ne_zero a) }, { exact (denom_ne_zero b) } end } } lemma fraction.add_num (a b : fraction) : num (a + b) = num a * denom b + num b * denom a := by refl lemma fraction.add_denom (a b : fraction) : denom (a + b) = denom a * denom b := by refl lemma fraction.add_equiv_add {a b c d : fraction} (hac : a ≈ c) (hbd : b ≈ d) : a + b ≈ c + d := begin simp [fraction.setoid_iff] at hac hbd, simp [fraction.setoid_iff], simp [fraction.add_num, fraction.add_denom], calc (num a * denom b + num b * denom a) * (denom c * denom d) = num a * denom c * denom b * denom d + num b * denom d * denom a * denom c : by simp[add_mul]; ac_refl ... = num c * denom a * denom b * denom d + num d * denom b * denom a * denom c : by simp [hbd, hac] ... = (num c * denom d + num d * denom c) * (denom a * denom b) : by simp[add_mul]; ac_refl end instance myℚ.has_add : has_add myℚ := { add := quotient.lift₂ (λa b, ⟦a + b⟧) begin intros a b c d hac hbd, apply quotient.sound, exact fraction.add_equiv_add hac hbd end } instance fraction.has_neg : has_neg fraction := { neg := λa, { num := - num a, denom := denom a, denom_ne_zero := denom_ne_zero a } } lemma fraction.neg_num (a : fraction) : num (- a) = - num a := by refl lemma fraction.neg_denom (a : fraction) : denom (- a) = denom a := by refl lemma fraction.setoid_neg {a b : fraction} (hab : a ≈ b) : - a ≈ - b := begin simp [fraction.setoid_iff] at hab ⊢, simp [fraction.neg_num, fraction.neg_denom], exact hab end instance myℚ.has_neg : has_neg myℚ := { neg := quotient.lift (λa, ⟦- a⟧) begin intros a b hab, apply quotient.sound, exact fraction.setoid_neg hab end } instance fraction.has_mul : has_mul fraction := { mul := λa b, { num := num a * num b, denom := denom a * denom b, denom_ne_zero := mul_ne_zero (denom_ne_zero a) (denom_ne_zero b) } } lemma fraction.mul_num (a b : fraction) : num (a * b) = num a * num b := by refl lemma fraction.mul_denom (a b : fraction) : denom (a * b) = denom a * denom b := by refl lemma fraction.setoid_mul {a b c d : fraction} (hac : a ≈ c) (hbd : b ≈ d) : a * b ≈ c * d := begin simp [fraction.setoid_iff] at hac hbd ⊢, simp [fraction.mul_num, fraction.mul_denom], cc end instance myℚ.has_mul : has_mul myℚ := { mul := quotient.lift₂ (λa b, ⟦a * b⟧) begin intros a b c d hac hbd, apply quotient.sound, exact fraction.setoid_mul hac hbd end } instance fraction.has_inv : has_inv fraction := { inv := λa, if ha : num a = 0 then 0 else { num := denom a, denom := num a, denom_ne_zero := ha } } lemma fraction.inv_def (a : fraction) (ha : num a ≠ 0) : a⁻¹ = { num := denom a, denom := num a, denom_ne_zero := ha } := dif_neg ha lemma fraction.inv_zero (a : fraction) (ha : num a = 0) : a⁻¹ = 0 := dif_pos ha lemma fraction.inv_num (a : fraction) (ha : num a ≠ 0) : num (a⁻¹) = denom a := by rw [fraction.inv_def a ha] lemma fraction.inv_denom (a : fraction) (ha : num a ≠ 0) : denom (a⁻¹) = num a := by rw [fraction.inv_def a ha] lemma fraction.setoid_inv {a b : fraction} (hac : a ≈ b) : a⁻¹ ≈ b⁻¹ := begin by_cases ha : num a = 0, { by_cases hb : num b = 0, { simp [ha, hb, fraction.inv_zero] at hac ⊢ }, { simp [ha, hb, fraction.setoid_iff, denom_ne_zero] at hac, cc } }, { by_cases hb : num b = 0, { simp [fraction.setoid_iff, hb, denom_ne_zero] at hac, cc }, { simp [fraction.setoid_iff, ha, hb, fraction.inv_num, fraction.inv_denom] at hac ⊢, cc } } end instance myℚ.has_inv : has_inv myℚ := { inv := quotient.lift (λa, ⟦a⁻¹⟧) begin intros a b hab, apply quotient.sound, exact fraction.setoid_inv hab end } /- Real Numbers -/ -- Definition of Cauchy sequences def is_cau_seq (f : ℕ → ℚ) : Prop := ∀ε > 0, ∃N, ∀m ≥ N, abs (f N - f m) < ε -- Type for Cauchy sequences def cau_seq : Type := {f : ℕ → ℚ // is_cau_seq f} def to_seq (f : cau_seq) : ℕ → ℚ := subtype.val f -- The quotient relation on Cauchy sequences instance cau_seq.setoid : setoid cau_seq := { r := λf g, ∀ε > 0, ∃N, ∀m ≥ N, abs (to_seq f m - to_seq g m) < ε, iseqv := begin apply and.intro, { intros f ε hε, use 0, intros m hm, simp, exact hε }, apply and.intro, { intros f g hfg ε hε, cases hfg ε hε with N hN, use N, intros m hm, rw [abs_sub], apply hN m hm }, { intros f g h hfg hgh ε hε, cases hfg (ε / 2) (half_pos hε) with N₁ hN₁, cases hgh (ε / 2) (half_pos hε) with N₂ hN₂, use (max N₁ N₂), intros m hm, calc abs (to_seq f m - to_seq h m) ≤ abs (to_seq f m - to_seq g m) + abs (to_seq g m - to_seq h m) : by apply abs_sub_le ... < ε / 2 + ε / 2 : add_lt_add (hN₁ m (le_of_max_le_left hm)) (hN₂ m (le_of_max_le_right hm)) ... = ε : by simp } end } lemma cau_seq.setoid_iff (f g : cau_seq) : f ≈ g ↔ ∀ε > 0, ∃N, ∀m ≥ N, abs (to_seq f m - to_seq g m) < ε := by refl def myℝ : Type := quotient cau_seq.setoid -- Constant Cauchy sequences def cau_seq.const (q : ℚ) : cau_seq := subtype.mk (λn, q) begin rw is_cau_seq, intros ε hε, use 0, simp, exact hε end instance myℝ.has_zero : has_zero myℝ := { zero := ⟦cau_seq.const 0⟧ } instance myℝ.has_one : has_one myℝ := { one := ⟦cau_seq.const 1⟧ } instance cau_seq.has_add : has_add cau_seq := { add := λf g, subtype.mk (λn, to_seq f n + to_seq g n) sorry } -- We omit the proof that the addition of two Cauchy sequences -- is again a Cauchy sequence. lemma cau_seq.add_equiv_add {f₁ f₂ g₁ g₂ : cau_seq} (hf : f₁ ≈ f₂) (hg : g₁ ≈ g₂) : f₁ + g₁ ≈ f₂ + g₂ := begin rw [cau_seq.setoid_iff], intros ε₀ hε₀, rw [cau_seq.setoid_iff] at hf hg, cases hf (ε₀ / 2) (half_pos hε₀) with Nf hNf, cases hg (ε₀ / 2) (half_pos hε₀) with Ng hNg, use max Nf Ng, intros m hm, calc abs (to_seq (f₁ + g₁) m - to_seq (f₂ + g₂) m) = abs ((to_seq f₁ m + to_seq g₁ m) - (to_seq f₂ m + to_seq g₂ m)) : by refl ... = abs ((to_seq f₁ m - to_seq f₂ m) + (to_seq g₁ m - to_seq g₂ m)) : by simp ... ≤ abs (to_seq f₁ m - to_seq f₂ m) + abs (to_seq g₁ m - to_seq g₂ m) : by apply abs_add ... < ε₀ / 2 + ε₀ / 2 : add_lt_add (hNf m (le_of_max_le_left hm)) (hNg m (le_of_max_le_right hm)) ... = ε₀ : by simp end instance myℝ.has_add : has_add myℝ := { add := quotient.lift₂ (λa b, ⟦a + b⟧) begin intros a b c d hac hbd, apply quotient.sound, exact cau_seq.add_equiv_add hac hbd, end } lemma id_not_cau_seq : ¬ is_cau_seq (λn : ℕ, (n : ℚ)) := begin rw is_cau_seq, intro h, cases h 1 zero_lt_one with i hi, have := hi (i + 1), simp at this, linarith end end LoVe
b8f2f5613c74563b8339a1efe0910538183faf60
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/bench/binarytrees.lean
91b1361f33720bd7f4ea973fb744b15c9f0bb559
[ "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
1,631
lean
inductive Tree | nil | node (l r : Tree) instance : Inhabited Tree := ⟨.nil⟩ -- This function has an extra argument to suppress the -- common sub-expression elimination optimization partial def make' (n d : UInt32) : Tree := if d = 0 then .node .nil .nil else .node (make' n (d - 1)) (make' (n + 1) (d - 1)) -- build a tree def make (d : UInt32) := make' d d def check : Tree → UInt32 | .nil => 0 | .node l r => 1 + check l + check r def minN := 4 def out (s : String) (n : Nat) (t : UInt32) : IO Unit := IO.println s!"{s} of depth {n}\t check: {t}" -- allocate and check lots of trees partial def sumT (d i t : UInt32) : UInt32 := if i = 0 then t else let a := check (make d) sumT d (i-1) (t + a) -- generate many trees partial def depth (d m : Nat) : List (Nat × Nat × Task UInt32) := if d ≤ m then let n := 2 ^ (m - d + minN) (n, d, Task.spawn (fun _ => sumT (.ofNat d) (.ofNat n) 0)) :: depth (d+2) m else [] def main : List String → IO UInt32 | [s] => do let n := s.toNat! let maxN := Nat.max (minN + 2) n let stretchN := maxN + 1 -- stretch memory tree let c := check (make $ UInt32.ofNat stretchN) out "stretch tree" stretchN c -- allocate a long lived tree let long := make $ UInt32.ofNat maxN -- allocate, walk, and deallocate many bottom-up binary trees let vs := (depth minN maxN) -- `using` (parList $ evalTuple3 r0 r0 rseq) vs.forM (fun (m, d, i) => out s!"{m}\t trees" d i.get) -- confirm the long-lived binary tree still exists out "long lived tree" maxN (check long) return 0 | _ => return 1
b76af19782e37e3a04fec14256c2c22d69bc6fca
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0502.lean
023f174c12322416d65382a48685db21a2b99a97
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
136
lean
open classical theorem dne {p : Prop} (h : ¬¬p) : p := or.elim (em p) (assume hp : p, hp) (assume hnp : ¬p, absurd hnp h)
a11e975c99ebe92e383d91b110060b04c8ae2348
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/nat_trans.hlean
e430ab2c139ffab6fcbc546cc6ff884f43fa6754
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
7,492
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer -/ import .functor.basic open eq category functor is_trunc equiv sigma.ops sigma is_equiv function pi funext iso structure nat_trans {C : Precategory} {D : Precategory} (F G : C ⇒ D) : Type := (natural_map : Π (a : C), hom (F a) (G a)) (naturality : Π {a b : C} (f : hom a b), G f ∘ natural_map a = natural_map b ∘ F f) namespace nat_trans infixl ` ⟹ `:25 := nat_trans -- \==> variables {B C D E : Precategory} {F G H I : C ⇒ D} {F' G' : D ⇒ E} {F'' G'' : E ⇒ B} {J : C ⇒ C} attribute natural_map [coercion] protected definition compose [constructor] (η : G ⟹ H) (θ : F ⟹ G) : F ⟹ H := nat_trans.mk (λ a, η a ∘ θ a) (λ a b f, abstract calc H f ∘ (η a ∘ θ a) = (H f ∘ η a) ∘ θ a : by rewrite assoc ... = (η b ∘ G f) ∘ θ a : by rewrite naturality ... = η b ∘ (G f ∘ θ a) : by rewrite assoc ... = η b ∘ (θ b ∘ F f) : by rewrite naturality ... = (η b ∘ θ b) ∘ F f : by rewrite assoc end) infixr ` ∘n `:60 := nat_trans.compose definition compose_def (η : G ⟹ H) (θ : F ⟹ G) (c : C) : (η ∘n θ) c = η c ∘ θ c := idp protected definition id [reducible] [constructor] {F : C ⇒ D} : nat_trans F F := mk (λa, id) (λa b f, !id_right ⬝ !id_left⁻¹) protected definition ID [reducible] [constructor] (F : C ⇒ D) : nat_trans F F := (@nat_trans.id C D F) notation 1 := nat_trans.id definition constant_nat_trans [constructor] (C : Precategory) {D : Precategory} {d d' : D} (g : d ⟶ d') : constant_functor C d ⟹ constant_functor C d' := mk (λc, g) (λc c' f, !id_comp_eq_comp_id) definition nat_trans_mk_eq {η₁ η₂ : Π (a : C), hom (F a) (G a)} (nat₁ : Π (a b : C) (f : hom a b), G f ∘ η₁ a = η₁ b ∘ F f) (nat₂ : Π (a b : C) (f : hom a b), G f ∘ η₂ a = η₂ b ∘ F f) (p : η₁ ~ η₂) : nat_trans.mk η₁ nat₁ = nat_trans.mk η₂ nat₂ := apd011 nat_trans.mk (eq_of_homotopy p) !is_hprop.elim definition nat_trans_eq {η₁ η₂ : F ⟹ G} : natural_map η₁ ~ natural_map η₂ → η₁ = η₂ := by induction η₁; induction η₂; apply nat_trans_mk_eq protected definition assoc (η₃ : H ⟹ I) (η₂ : G ⟹ H) (η₁ : F ⟹ G) : η₃ ∘n (η₂ ∘n η₁) = (η₃ ∘n η₂) ∘n η₁ := nat_trans_eq (λa, !assoc) protected definition id_left (η : F ⟹ G) : 1 ∘n η = η := nat_trans_eq (λa, !id_left) protected definition id_right (η : F ⟹ G) : η ∘n 1 = η := nat_trans_eq (λa, !id_right) protected definition sigma_char (F G : C ⇒ D) : (Σ (η : Π (a : C), hom (F a) (G a)), Π (a b : C) (f : hom a b), G f ∘ η a = η b ∘ F f) ≃ (F ⟹ G) := begin fapply equiv.mk, -- TODO(Leo): investigate why we need to use rexact in the following line {intro S, apply nat_trans.mk, rexact (S.2)}, fapply adjointify, intro H, fapply sigma.mk, intro a, exact (H a), intro a b f, exact (naturality H f), intro η, apply nat_trans_eq, intro a, apply idp, intro S, fapply sigma_eq, { apply eq_of_homotopy, intro a, apply idp}, { apply is_hprop.elimo} end definition is_hset_nat_trans [instance] : is_hset (F ⟹ G) := by apply is_trunc_is_equiv_closed; apply (equiv.to_is_equiv !nat_trans.sigma_char) definition change_natural_map [constructor] (η : F ⟹ G) (f : Π (a : C), F a ⟶ G a) (p : Πa, η a = f a) : F ⟹ G := nat_trans.mk f (λa b g, p a ▸ p b ▸ naturality η g) definition nat_trans_functor_compose [constructor] (η : G ⟹ H) (F : E ⇒ C) : G ∘f F ⟹ H ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_compose [constructor] (F : D ⇒ E) (η : G ⟹ H) : F ∘f G ⟹ F ∘f H := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (H f) ∘ F (η a) = F (H f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ G f) : by rewrite (naturality η f) ... = F (η b) ∘ F (G f) : by rewrite respect_comp) definition nat_trans_id_functor_compose [constructor] (η : J ⟹ 1) (F : E ⇒ C) : J ∘f F ⟹ F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition id_nat_trans_functor_compose [constructor] (η : 1 ⟹ J) (F : E ⇒ C) : F ⟹ J ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_id_compose [constructor] (F : C ⇒ D) (η : J ⟹ 1) : F ∘f J ⟹ F := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F f ∘ F (η a) = F (f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ J f) : by rewrite (naturality η f) ... = F (η b) ∘ F (J f) : by rewrite respect_comp) definition functor_id_nat_trans_compose [constructor] (F : C ⇒ D) (η : 1 ⟹ J) : F ⟹ F ∘f J := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (J f) ∘ F (η a) = F (J f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ f) : by rewrite (naturality η f) ... = F (η b) ∘ F f : by rewrite respect_comp) infixr ` ∘nf ` :62 := nat_trans_functor_compose infixr ` ∘fn ` :62 := functor_nat_trans_compose infixr ` ∘n1f `:62 := nat_trans_id_functor_compose infixr ` ∘1nf `:62 := id_nat_trans_functor_compose infixr ` ∘f1n `:62 := functor_id_nat_trans_compose infixr ` ∘fn1 `:62 := functor_nat_trans_id_compose definition nf_fn_eq_fn_nf_pt (η : F ⟹ G) (θ : F' ⟹ G') (c : C) : (θ (G c)) ∘ (F' (η c)) = (G' (η c)) ∘ (θ (F c)) := (naturality θ (η c))⁻¹ variable (F') definition nf_fn_eq_fn_nf_pt' (η : F ⟹ G) (θ : F'' ⟹ G'') (c : C) : (θ (F' (G c))) ∘ (F'' (F' (η c))) = (G'' (F' (η c))) ∘ (θ (F' (F c))) := (naturality θ (F' (η c)))⁻¹ variable {F'} definition nf_fn_eq_fn_nf (η : F ⟹ G) (θ : F' ⟹ G') : (θ ∘nf G) ∘n (F' ∘fn η) = (G' ∘fn η) ∘n (θ ∘nf F) := nat_trans_eq (λ c, nf_fn_eq_fn_nf_pt η θ c) definition fn_n_distrib (F' : D ⇒ E) (η : G ⟹ H) (θ : F ⟹ G) : F' ∘fn (η ∘n θ) = (F' ∘fn η) ∘n (F' ∘fn θ) := nat_trans_eq (λc, by apply respect_comp) definition n_nf_distrib (η : G ⟹ H) (θ : F ⟹ G) (F' : B ⇒ C) : (η ∘n θ) ∘nf F' = (η ∘nf F') ∘n (θ ∘nf F') := nat_trans_eq (λc, idp) definition fn_id (F' : D ⇒ E) : F' ∘fn nat_trans.ID F = 1 := nat_trans_eq (λc, by apply respect_id) definition id_nf (F' : B ⇒ C) : nat_trans.ID F ∘nf F' = 1 := nat_trans_eq (λc, idp) definition id_fn (η : G ⟹ H) (c : C) : (1 ∘fn η) c = η c := idp definition nf_id (η : G ⟹ H) (c : C) : (η ∘nf 1) c = η c := idp definition nat_trans_of_eq [reducible] [constructor] (p : F = G) : F ⟹ G := nat_trans.mk (λc, hom_of_eq (ap010 to_fun_ob p c)) (λa b f, eq.rec_on p (!id_right ⬝ !id_left⁻¹)) definition compose_rev [unfold_full] (θ : F ⟹ G) (η : G ⟹ H) : F ⟹ H := η ∘n θ end nat_trans attribute nat_trans.compose_rev [trans] attribute nat_trans.id [refl]
144274a4595653ebf9dc9c138d1ddc3550fe84c4
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/e18.lean
82174ed3dcc47e6150042999a571fd37393d97c0
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
474
lean
inductive nat : Type := zero : nat, succ : nat → nat inductive list (A : Type) : Type := nil {} : list A, cons : A → list A → list A inductive int : Type := of_nat : nat → int, neg : nat → int coercion int.of_nat constants n m : nat constants i j : int constant l : list nat namespace list end list open list check cons i (cons i nil) check cons n (cons n nil) check cons i (cons n nil) check cons n (cons i nil) check cons n (cons i (cons m (cons j nil)))
650eeecfd7d13a3b60b28d6b2144d9897eb7c454
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/sym/card.lean
d52f37ab7dfa56d18012cfc0b9c177457dd64f97
[ "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
4,191
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import algebra.big_operators.basic import data.fintype.card import data.sym.sym2 /-! # Stars and bars In this file, we prove the case `n = 2` of stars and bars. ## Informal statement If we have `n` objects to put in `k` boxes, we can do so in exactly `(n + k - 1).choose n` ways. ## Formal statement We can identify the `k` boxes with the elements of a fintype `α` of card `k`. Then placing `n` elements in those boxes corresponds to choosing how many of each element of `α` appear in a multiset of card `n`. `sym α n` being the subtype of `multiset α` of multisets of card `n`, writing stars and bars using types gives ```lean -- TODO: this lemma is not yet proven lemma stars_and_bars {α : Type*} [fintype α] (n : ℕ) : card (sym α n) = (card α + n - 1).choose (card α) := sorry ``` ## TODO Prove the general case of stars and bars. ## Tags stars and bars -/ open finset fintype namespace sym2 variables {α : Type*} [decidable_eq α] /-- The `diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.card`. -/ lemma card_image_diag (s : finset α) : (s.diag.image quotient.mk).card = s.card := begin rw [card_image_of_inj_on, diag_card], rintro ⟨x₀, x₁⟩ hx _ _ h, cases quotient.eq.1 h, { refl }, { simp only [mem_coe, mem_diag] at hx, rw hx.2 } end lemma two_mul_card_image_off_diag (s : finset α) : 2 * (s.off_diag.image quotient.mk).card = s.off_diag.card := begin rw [card_eq_sum_card_fiberwise (λ x, mem_image_of_mem _ : ∀ x ∈ s.off_diag, quotient.mk x ∈ s.off_diag.image quotient.mk), sum_const_nat (quotient.ind _), mul_comm], rintro ⟨x, y⟩ hxy, simp_rw [mem_image, exists_prop, mem_off_diag, quotient.eq] at hxy, obtain ⟨a, ⟨ha₁, ha₂, ha⟩, h⟩ := hxy, obtain ⟨hx, hy, hxy⟩ : x ∈ s ∧ y ∈ s ∧ x ≠ y, { cases h; have := ha.symm; exact ⟨‹_›, ‹_›, ‹_›⟩ }, have hxy' : y ≠ x := hxy.symm, have : s.off_diag.filter (λ z, ⟦z⟧ = ⟦(x, y)⟧) = ({(x, y), (y, x)} : finset _), { ext ⟨x₁, y₁⟩, rw [mem_filter, mem_insert, mem_singleton, sym2.eq_iff, prod.mk.inj_iff, prod.mk.inj_iff, and_iff_right_iff_imp], rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩); rw mem_off_diag; exact ⟨‹_›, ‹_›, ‹_›⟩ }, -- hxy' is used here rw [this, card_insert_of_not_mem, card_singleton], simp only [not_and, prod.mk.inj_iff, mem_singleton], exact λ _, hxy', end /-- The `off_diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.off_diag.card / 2`. This is because every element `⟦(x, y)⟧` of `sym2 α` not on the diagonal comes from exactly two pairs: `(x, y)` and `(y, x)`. -/ lemma card_image_off_diag (s : finset α) : (s.off_diag.image quotient.mk).card = s.card.choose 2 := by rw [nat.choose_two_right, mul_tsub, mul_one, ←off_diag_card, nat.div_eq_of_eq_mul_right zero_lt_two (two_mul_card_image_off_diag s).symm] lemma card_subtype_diag [fintype α] : card {a : sym2 α // a.is_diag} = card α := begin convert card_image_diag (univ : finset α), rw [fintype.card_of_subtype, ←filter_image_quotient_mk_is_diag], rintro x, rw [mem_filter, univ_product_univ, mem_image], obtain ⟨a, ha⟩ := quotient.exists_rep x, exact and_iff_right ⟨a, mem_univ _, ha⟩, end lemma card_subtype_not_diag [fintype α] : card {a : sym2 α // ¬a.is_diag} = (card α).choose 2 := begin convert card_image_off_diag (univ : finset α), rw [fintype.card_of_subtype, ←filter_image_quotient_mk_not_is_diag], rintro x, rw [mem_filter, univ_product_univ, mem_image], obtain ⟨a, ha⟩ := quotient.exists_rep x, exact and_iff_right ⟨a, mem_univ _, ha⟩, end protected lemma card [fintype α] : card (sym2 α) = card α * (card α + 1) / 2 := by rw [←fintype.card_congr (@equiv.sum_compl _ is_diag (sym2.is_diag.decidable_pred α)), fintype.card_sum, card_subtype_diag, card_subtype_not_diag, nat.choose_two_right, add_comm, ←nat.triangle_succ, nat.succ_sub_one, mul_comm] end sym2
07c882ee8268a82e7e82c11092caa6d35a8242eb
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/cond_tac.lean
dbdd8682091602f6ad1922358769235231a1914f
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
1,229
lean
import tactic (* simple_tac = Cond(function(env, ios, s) local gs = s:goals() local n, g = gs:head() local r = g:conclusion():is_and() print ("Cond result: " .. tostring(r)) return r end, Then(apply_tac("and_intro"), assumption_tac()), Then(apply_tac("or_introl"), assumption_tac())) simple2_tac = When(function(env, ios, s) local gs = s:goals() local n, g = gs:head() local r = g:conclusion():is_and() print ("When result: " .. tostring(r)) return r end, apply_tac("and_intro")) *) theorem T1 (a b c : Bool) : a -> b -> c -> a ∧ b. (* simple_tac *) done theorem T2 (a b : Bool) : a -> a ∨ b. (* simple_tac *) done definition x := 10 theorem T3 : x + 20 +2 >= 2*x. (* eval_tac() *) (* trivial_tac() *) done theorem T4 (a b c : Bool) : a -> b -> c -> a ∧ b. (* simple2_tac *) exact done theorem T5 (a b c : Bool) : a -> b -> c -> a ∨ b. (* simple2_tac *) apply or_introl exact done
cf274be7c8a405765b6ca87d14ee35b38e14e014
b5d93c72e090448754596aaf1204dca77e00841f
/src/export_json.lean
3717e5e3eb859043ebbc2c5413a58690ff080932
[]
no_license
gebner/doc-gen
b9edb38b3da9ec87f284fc891d00be0616b44f3b
80716270e92c25912ad1b6a742df1953e36374e3
refs/heads/master
1,606,264,147,578
1,576,502,548,000
1,576,502,548,000
228,408,636
0
0
null
1,576,507,505,000
1,576,507,505,000
null
UTF-8
Lean
false
false
9,536
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.core system.io data.string.defs tactic.interactive data.list.sort import all /-! Used to generate a json file for html docs. The json file is a list of maps, where each map has the structure { name: string, args : list string, type: string, doc_string: string, filename: string, line: int, attributes: list string, kind: string, structure_fields: list (list string), constructors: list (list string) } The lists in structure_fields and constructors are assumed to contain two strings each. Include this file somewhere in mathlib, e.g. in the `scripts` directory. Make sure mathlib is precompiled, with `all.lean` generated by `mk_all.sh`. Usage: `lean --run export_json.lean` creates `json_export.txt` in the current directory. -/ open tactic io io.fs /-- The information collected from each declaration -/ structure decl_info := (name : name) (args : list (bool × string)) -- tt means implicit (type : string) (doc_string : option string) (filename : string) (line : ℕ) (attributes : list string) -- not all attributes, we have a hardcoded list to check (kind : string) -- def, thm, cnst, ax (structure_fields : list (string × string)) -- name and type of fields of a constructor (constructors : list (string × string)) -- name and type of constructors of an inductive type structure module_doc_info := (filename : string) (line : ℕ) (content : string) meta def escape_quotes (s : string) : string := s.fold "" (λ s x, s ++ if x = '"' then '\\'.to_string ++ '"'.to_string else x.to_string) meta def print_arg : bool × string → string | (b, s) := let bstr := if b then "true" else "false" in "{" ++ (to_string $ format!"\"arg\":{repr s}, \"implicit\":{bstr}") ++ "}" meta def decl_info.to_format : decl_info → format | ⟨name, args, type, doc_string, filename, line, attributes, kind, structure_fields, constructors⟩ := let doc_string := doc_string.get_or_else "", args := args.map print_arg, attributes := attributes.map repr, structure_fields := structure_fields.map (λ ⟨n, t⟩, format!"[\"{to_string n}\", {repr t}]"), constructors := constructors.map (λ ⟨n, t⟩, format!"[\"{to_string n}\", {repr t}]") in "{" ++ format!"\"name\":\"{to_string name}\", \"args\":{args}, \"type\":{repr type}, \"doc_string\":{repr doc_string}, " ++ format!"\"filename\":\"{filename}\",\"line\":{line}, \"attributes\":{attributes}, " ++ format!" \"kind\":{repr kind}, \"structure_fields\":{structure_fields}, \"constructors\":{constructors}" ++ "}" section open tactic.interactive -- tt means implicit private meta def format_binders : list name × binder_info × expr → tactic (bool × format) | (ns, binder_info.default, t) := prod.mk ff <$> pformat!"({format_names ns} : {t})" | (ns, binder_info.implicit, t) := prod.mk tt <$> pformat!"{{{format_names ns} : {t}}" | (ns, binder_info.strict_implicit, t) := prod.mk tt <$> pformat!"⦃{format_names ns} : {t}⦄" | ([n], binder_info.inst_implicit, t) := prod.mk tt <$> if "_".is_prefix_of n.to_string then pformat!"[{t}]" else pformat!"[{format_names [n]} : {t}]" | (ns, binder_info.inst_implicit, t) := prod.mk tt <$> pformat!"[{format_names ns} : {t}]" | (ns, binder_info.aux_decl, t) := prod.mk tt <$> pformat!"({format_names ns} : {t})" meta def binder_info.is_inst_implicit : binder_info → bool | binder_info.inst_implicit := tt | _ := ff meta def count_named_intros : expr → tactic ℕ | e@(expr.pi _ bi _ _) := do ([_], b) ← mk_local_pisn e 1, v ← count_named_intros b, return $ if v = 0 ∧ e.is_arrow ∧ ¬ bi.is_inst_implicit then v else v + 1 | _ := return 0 /- meta def count_named_intros : expr → ℕ | e@(expr.pi _ _ _ b) := let v := count_named_intros b in if v = 0 ∧ e.is_arrow then v else v + 1 | _ := 0 -/ -- tt means implicit meta def get_args_and_type (e : expr) : tactic (list (bool × string) × string) := prod.fst <$> solve_aux e ( do count_named_intros e >>= intron, cxt ← local_context >>= tactic.interactive.compact_decl, cxt' ← cxt.mmap (λ t, do ft ← format_binders t, return (ft.1, to_string ft.2)), tgt ← target >>= pp, return (cxt', to_string tgt)) end /-- The attributes we check for -/ meta def attribute_list := [`simp, `squash_cast, `move_cast, `elim_cast, `nolint, `ext, `instance] meta def attributes_of (n : name) : tactic (list string) := list.map to_string <$> attribute_list.mfilter (λ attr, succeeds $ has_attribute attr n) meta def declaration.kind : declaration → string | (declaration.defn a a_1 a_2 a_3 a_4 a_5) := "def" | (declaration.thm a a_1 a_2 a_3) := "thm" | (declaration.cnst a a_1 a_2 a_3) := "cnst" | (declaration.ax a a_1 a_2) := "ax" -- does this not exist already? I'm confused. meta def expr.instantiate_pis : list expr → expr → expr | (e'::es) (expr.pi n bi t e) := expr.instantiate_pis es (e.instantiate_var e') | _ e := e -- assumes proj_name exists meta def get_proj_type (struct_name proj_name : name) : tactic string := do (locs, _) ← mk_const struct_name >>= infer_type >>= mk_local_pis, proj_tp ← mk_const proj_name >>= infer_type, (_, t) ← mk_local_pisn (proj_tp.instantiate_pis locs) 1, to_string <$> pp t meta def mk_structure_fields (decl : name) (e : environment) : tactic (list (string × string)) := match e.is_structure decl, e.structure_fields_full decl with | tt, some proj_names := proj_names.mmap $ λ n, do tp ← get_proj_type decl n, return (to_string n, to_string tp) | _, _ := return [] end -- this is used as a hack in get_constructor_type to avoid printing `Type ?`. meta def mk_const_with_params (d : declaration) : expr := let lvls := d.univ_params.map level.param in expr.const d.to_name lvls meta def get_constructor_type (type_name constructor_name : name) : tactic string := do d ← get_decl type_name, (locs, _) ← infer_type (mk_const_with_params d) >>= mk_local_pis, proj_tp ← mk_const constructor_name >>= infer_type, do t ← pis locs (proj_tp.instantiate_pis locs), --.abstract_locals (locs.map expr.local_uniq_name), to_string <$> pp t meta def mk_constructors (decl : name) (e : environment): tactic (list (string × string)) := if (¬ e.is_inductive decl) ∨ (e.is_structure decl) then return [] else do d ← get_decl decl, ns ← get_constructors_for (mk_const_with_params d), ns.mmap $ λ n, do tp ← get_constructor_type decl n, return (to_string n, to_string tp) /-- extracts `decl_info` from `d`. Should return `none` instead of failing. -/ meta def process_decl (d : declaration) : tactic (option decl_info) := do ff ← d.in_current_file | return none, e ← get_env, let decl_name := d.to_name, if decl_name.is_internal ∨ d.is_auto_generated e then return none else do some filename ← return (e.decl_olean decl_name) | return none, some ⟨line, _⟩ ← return (e.decl_pos decl_name) | return none, doc_string ← (some <$> doc_string decl_name) <|> return none, (args, type) ← get_args_and_type d.type, -- type ← escape_quotes <$> to_string <$> pp d.type, attributes ← attributes_of decl_name, structure_fields ← mk_structure_fields decl_name e, constructors ← mk_constructors decl_name e, return $ some ⟨decl_name, args, type, doc_string, filename, line, attributes, d.kind, structure_fields, constructors⟩ meta def run_on_dcl_list (e : environment) (ens : list name) (handle : handle) (is_first : bool) : io unit := ens.mfoldl (λ is_first d_name, do d ← run_tactic (e.get d_name), odi ← run_tactic (process_decl d), match odi with | some di := do when (bnot is_first) (put_str_ln handle ","), put_str_ln handle $ to_string di.to_format, return ff | none := return is_first end) is_first >> return () meta def itersplit {α} : list α → ℕ → list (list α) | l 0 := [l] | l 1 := let (l1, l2) := l.split in [l1, l2] | l (k+2) := let (l1, l2) := l.split in itersplit l1 (k+1) ++ itersplit l2 (k+1) meta def write_module_doc_pair : pos × string → string | (⟨line, _⟩, doc) := "{\"line\":" ++ to_string line ++ ", \"doc\" :" ++ repr doc ++ "}" meta def write_olean_docs : tactic (list string) := do docs ← olean_doc_strings, return (docs.foldl (λ rest p, match p with | (none, _) := rest | (_, []) := rest | (some filename, l) := let new := "\"" ++ filename ++ "\":" ++ to_string (l.map write_module_doc_pair) in new::rest end) []) /-- Using `environment.mfold` is much cleaner. Unfortunately this led to a segfault, I think because of a stack overflow. Converting the environment to a list of declarations and folding over that led to "deep recursion detected". Instead, we split that list into 8 smaller lists and process them one by one. More investigation is needed. -/ meta def export_json (filename : string) : io unit := do handle ← mk_file_handle filename mode.write, put_str_ln handle "{ \"decls\":[", e ← run_tactic get_env, let ens := environment.get_decl_names e, let enss := itersplit ens 3, enss.mfoldl (λ is_first l, do run_on_dcl_list e l handle is_first, return ff) tt, put_str_ln handle "],", ods ← run_tactic write_olean_docs, put_str_ln handle $ "\"mod_docs\": {" ++ string.join (ods.intersperse ",\n") ++ "}}", close handle meta def main : io unit := export_json "json_export.txt"
3e53548e4205d0bbb63f762047568d7f190bf49e
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1231.lean
304993c3d2dfade596c1944c589feb1580d774cc
[]
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
256
lean
variables {α : Type*} (P : α → Prop) example (h : ¬ ∃ x, P x) : ∀ x, ¬ P x := sorry example (h : ∀ x, ¬ P x) : ¬ ∃ x, P x := sorry example (h : ¬ ∀ x, P x) : ∃ x, ¬ P x := sorry example (h : ∃ x, ¬ P x) : ¬ ∀ x, P x := sorry
991752e80dcc49892e4c538f4747c67c35a6805e
dfb46c403bb47bae8bc79d998f700de3141215f2
/TBA/Eulerian/List.lean
2c0f8daa2eee9e7067d41a3b2e21f6b63ce289ba
[]
no_license
JerrySommerfield/tba-2021
82ac01e8274e0a3e9fc681ef00961ed9535526c6
4f6ea59fd216ea54bf0c4367c4f5ea1bcc3534a9
refs/heads/master
1,685,282,562,160
1,623,763,805,000
1,623,764,287,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,778
lean
import TBA.Eulerian.Nat open BEq Nat List Decidable namespace Eq protected theorem symm_iff {a b : α} : b = a ↔ a = b := ⟨Eq.symm, Eq.symm⟩ end Eq namespace List @[simp] theorem length_append {as bs : List α} : length (as ++ bs) = length as + length bs := match as with | [] => by simp | a :: as => by simp [Nat.succ_add, length_append] theorem length_zero_iff_nil {as : List α} : length as = 0 ↔ as = [] := ⟨fun e => by cases as; rfl; simp [length_cons] at e, fun e => by rw [e]; rfl⟩ theorem length_cons_ne_zero {as : List α} {a : α} : length (a :: as) ≠ 0 := by rw [List.length_cons]; exact Nat.succNeZero _ -- Some lemmas about filters @[simp] theorem filter_nil {p : α → Bool} : filter p [] = [] := by simp [filter, filterAux, reverse, reverseAux] theorem cons_eq_append (a : α) (as : List α) : a :: as = [a] ++ as := rfl theorem reverseAux_append {rs as : List α} : reverseAux rs as = reverseAux rs [] ++ as := match rs with | [] => rfl | r :: rs => by simp only [reverseAux] rw [reverseAux_append, reverseAux_append (as := [r]), cons_eq_append r as, append_assoc] theorem filterAux_aux {p : α → Bool} (as : List α) : (rs : List α) → filterAux p as rs = rs.reverse ++ (filterAux p as []) := match as with | [] => by intros; simp [filterAux, reverse, reverseAux]; | a :: as => by intro rs simp only [filterAux] cases p a case false => simp [filterAux_aux as rs] case true => rw [filterAux_aux as (a :: rs), filterAux_aux as [a]] simp only [reverse, reverseAux, List.append, List.cons_append, List.nil_append] rw [reverseAux_append, cons_eq_append _ (filterAux p as []), append_assoc] theorem filter_cons (a : α) (as : List α) : filter p (a :: as) = if p a then a :: filter p as else filter p as := by simp only [filter, filterAux] cases p a simp rw [filterAux_aux]; simp [reverse, reverseAux] @[simp] theorem filter_append {as bs : List α} {p : α → Bool} : filter p (as ++ bs) = filter p as ++ filter p bs := by induction as with | nil => simp | cons a as ih => rw [filter_cons, cons_append, filter_cons] cases p a <;> simp [ih] -- A membership predicate inductive Mem : α → List α → Prop where | head (a : α) (as : List α) : Mem a (a::as) | tail (a b : α) (bs : List α) : Mem a bs → Mem a (b::bs) infix:50 " ∈ " => Mem @[simp] theorem beq_refl [DecidableEq α] : ((a : α) == a) = true := decideEqTrue rfl @[simp] theorem beq_neq [DecidableEq α] {a b : α} (h : ¬ a = b) : (a == b) = false := decideEqFalse h theorem length_erase_mem [DecidableEq α] {a : α} {as : List α} (h : a ∈ as) : length (List.erase as a) + 1 = length as := match a, as, h with | _, _, Mem.head a bs => by simp [List.erase] | _, _, Mem.tail a b bs h => by simp only [List.erase] match b == a with | true => simp | false => { simp only [length_cons]; rw [←length_erase_mem h] } theorem mem_singleton [DecidableEq α] {a b : α} (h : a ∈ [b]) : a = b := by cases h with | head h => rfl | tail _ _ _ h => cases h def mem_of_nonzero_length [DecidableEq α] {as : List α} : (h : length as > 0) → { a // a ∈ as } := match as with | [] => by { simp only [length_nil]; intro fa; cases fa } | a :: as => by { intros; apply Subtype.mk; apply Mem.head } theorem mem_append {as bs : List α} : ∀ a, a ∈ (as ++ bs) → a ∈ as ∨ a ∈ bs := match as with | [] => by intros; apply Or.inr; assumption | a :: as => by simp only [List.cons_append] intros a h cases h with | head h => apply Or.inl; apply Mem.head | tail _ _ _ h => cases mem_append (as := as) (bs := bs) a h case inl => apply Or.inl; apply Mem.tail; assumption case inr => apply Or.inr; assumption theorem mem_of_mem_filter {as : List α} {a : α} {p : α → Bool} : a ∈ filter p as → a ∈ as := match as with | [] => by intros; assumption | a' :: as => by rw [filter_cons]; cases p a' case false => intro h; apply Mem.tail; apply mem_of_mem_filter h case true => intro h cases h with | head => apply Mem.head | tail _ _ _ h => apply Mem.tail; apply mem_of_mem_filter h theorem mem_filter_of_prop {as : List α} {a : α} {p : α → Bool} (ha : a ∈ as) (hpa : p a = true) : a ∈ filter p as := by induction ha with | head a as => rw [filter_cons, hpa]; simp; apply Mem.head | tail a b as ha' ih => rw [filter_cons] cases hpb : p b case false => simp; exact ih hpa case true => simp; apply Mem.tail; exact ih hpa theorem filterProp_of_mem {as : List α} {p : α → Bool} {a : α} : a ∈ filter p as → p a = true := match as with | [] => by intro h; cases h | a' :: as => by rw [filter_cons]; byCases hpa : p a' case inr => simp [hpa]; exact filterProp_of_mem case inl => simp [hpa]; intro h; cases h; assumption; apply filterProp_of_mem; assumption theorem mem_split {a : α} {as : List α} (h : a ∈ as) : ∃ s t, as = s ++ a :: t := match a, as, h with | _, _, Mem.head a bs => ⟨[], ⟨bs, rfl⟩⟩ | _, _, Mem.tail a b bs h => match bs, mem_split h with | _, ⟨s, ⟨t, rfl⟩⟩ => ⟨b::s, ⟨t, List.cons_append .. ▸ rfl⟩⟩ -- Couting elements section Count variable [DecidableEq α] (as bs as' bs' : List α) (a b : α) def count : Nat := (as.filter $ fun b => b == a).length @[simp] theorem count_empty : count [] a = 0 := by simp [count] @[simp] theorem count_self_cons : (a :: as).count a = Nat.succ (as.count a) := by simp [count, filter_cons] theorem count_neq_cons {as} {a b : α} (h : ¬ b = a) : (b :: as).count a = as.count a := by simp [count, filter_cons, h] @[simp] theorem count_append : (as ++ bs).count a = as.count a + bs.count a := by simp [count] --set_option trace.Meta.Tactic.simp true theorem count_erase {as : List α} {a b : α} : (as.erase a).count b = if (a == b) then (as.count b) - 1 else as.count b := match as with | [] => by simp only [List.erase]; cases (a == b) <;> simp | a' :: as => by simp only [List.erase] byCases h : a' = a case inl => cases h simp only [beq_refl] byCases h' : a = b case inl => cases h'; simp only [beq_refl, Lean.Simp.ite_True, Nat.succ_sub_succ, count_self_cons]; apply Nat.sub_zero case inr => rw [beq_neq h']; simp [count_neq_cons h'] case inr => rw [beq_neq h] byCases h' : a' = b case inl => cases h'; simp [count_erase (as := as), beq_neq (Ne.symm h)] case inr => simp [count_neq_cons h', count_neq_cons h', count_erase] theorem count_le_cons : as.count a ≤ (b :: as).count a := by byCases h : (b = a) case inl => cases h; simp [count_self_cons, Nat.leSucc] case inr => rw [count_neq_cons h]; simp [Nat.leRefl] theorem mem_nonzeroCount {as : List α} {a : α}: a ∈ as ↔ as.count a > 0 := by apply Iff.intro case mp => intro h induction h with | head a => simp [Nat.zeroLtSucc] | tail _ _ _ h ih => apply Nat.ltOfLtOfLe ih; apply count_le_cons case mpr => intro h let ⟨a', ha'⟩ := mem_of_nonzero_length h let foo := filterProp_of_mem ha' cases ofDecideEqTrue foo apply mem_of_mem_filter ha' -- Erasing elements from lists theorem erase_comm {as : List α} : (as.erase a).erase b = (as.erase b).erase a := match as with | [] => rfl | a' :: as => by byCases h : a' = a case inl => cases h; simp only [List.erase] byCases h' : b = a case inl => cases h'; simp case inr => rw [beq_neq (Ne.symm h')]; simp [List.erase] case inr => simp only [List.erase] rw [beq_neq h] byCases h' : a' = b case inl => cases h'; simp [List.erase] case inr => simp [List.erase, beq_neq h', beq_neq h, erase_comm (as := as)] theorem filter_erase_false {as : List α} {a : α} {p : α → Bool} (h : p a = false) : filter p (as.erase a) = filter p as := match as with | [] => by simp [List.erase] | b :: as => by simp only [List.erase, filter_cons] byCases h' : b = a case inl => cases h'; simp [h] case inr => simp [h', filter_cons]; rw [filter_erase_false h] theorem filter_erase_true {as : List α} {a : α} {p : α → Bool} (hpa : p a = true) : filter p (as.erase a) = (filter p as).erase a := match as with | [] => rfl | b :: as => by simp byCases h : b = a case inl => cases h; simp [List.erase, filter_cons, hpa] case inr => simp only [List.erase, beq_neq h, filter_cons] cases hpb : p b case false => exact filter_erase_true hpa case true => rw [filter_erase_true hpa]; simp [List.erase, h] def eraseAll (as bs : List α) : List α := match bs with | [] => as | b :: bs => eraseAll (as.erase b) bs infixl:55 " -l " => eraseAll theorem erase_eraseAll {as bs : List α} {a : α} : (as.erase a) -l bs = (as -l bs).erase a := match bs with | [] => rfl | b :: bs => by simp only [eraseAll]; rw [←erase_eraseAll, erase_comm] @[simp] theorem count_eraseAll (as bs : List α) (a : α) : (as -l bs).count a = as.count a - bs.count a := match bs with | [] => rfl | b :: bs => by simp only [eraseAll]; rw [erase_eraseAll]; simp byCases hba : b = a; case inl => cases hba; rw [count_self_cons, count_erase, count_eraseAll as bs a, beq_refl]; rfl case inr => rw [count_erase, beq_neq hba, count_eraseAll as bs a, count_neq_cons]; repeat simp_all -- Lists which are permutations of each other, and sublists modulo permutation def isPermEqvTo : Prop := ∀ a, as.count a = bs.count a infixl:50 " ≃ " => isPermEqvTo -- Type as \simeq def isPermSubOf : Prop := ∀ a, as.count a ≤ bs.count a infixl:50 " ⊆ " => isPermSubOf -- Type as \sub theorem permSubOfEraseSub : (as -l bs) ⊆ as := fun a => by simp [Nat.subLe] theorem mem_of_mem_eraseAll {as bs : List α} {a : α} : a ∈ (as -l bs) → a ∈ as := by rw [mem_nonzeroCount, mem_nonzeroCount, count_eraseAll] intro h; exact Nat.ltOfLtOfLe h (Nat.subLe _ _) theorem permSubEraseAllLength {as bs : List α} : bs ⊆ as → length (as -l bs) = length as - length bs := match bs with | [] => fun _ => rfl | b :: bs => fun hsub => by simp only [eraseAll, length_cons] have hbas : b ∈ as := by have hb := hsub b rw [count_self_cons] at hb rw [mem_nonzeroCount] exact Nat.ltOfLeOfLt (zeroLe _) (ltOfSuccLe hb) have hsub' : bs.isPermSubOf (as.erase b) := fun c => by have hc := hsub c byCases h : b = c case inl => cases h rw [count_self_cons] at hc rw [count_erase] simp [leOfSuccLeSucc (Nat.leTrans hc leSuccSubOne)] case inr => rw [count_neq_cons h] at hc apply Nat.leTrans hc rw [count_erase, beq_neq h] simp [Nat.leRefl] rw [permSubEraseAllLength hsub', ←length_erase_mem hbas, Nat.succ_sub_succ] theorem permSubExtend {as bs : List α} {b} (hsub : bs ⊆ as) (ha : b ∈ (as -l bs)) : (b :: bs) ⊆ as := by intro a rw [mem_nonzeroCount, count_eraseAll, ←zeroLtIffSub] at ha byCases h : b = a case inl => cases h; simp; assumption case inr => rw [count_neq_cons h]; apply hsub def permSubObtainComplement {as bs : List α} (hsub : bs ⊆ as) (hlength : bs.length < as.length) : { e // e ∈ as -l bs} := by have hl : (as -l bs).length > 0 := by rw [permSubEraseAllLength hsub, ←zeroLtIffSub]; assumption revert hl; cases as -l bs case nil => simp only [length_nil]; intro hl'; cases hl' case cons => intros; exact ⟨_, Mem.head _ _⟩ theorem permSubEqvClosed {as bs bs' : List α} (heqv : bs ≃ bs') (hsub : bs ⊆ as) : bs' ⊆ as := fun a => by rw [←heqv a]; exact hsub a theorem permSubSingleton {as : List α} {a : α} : a ∈ as → [a] ⊆ as := by intros ha b rw [mem_nonzeroCount] at ha byCases h : a = b case inl => cases h; simp [count_self_cons]; assumption case inr => rw [count_neq_cons h]; simp [Nat.zeroLe] theorem permEqvRotate : (as ++ bs) ≃ (bs ++ as) := fun a => by simp [Nat.add_comm]; theorem permEqvRefl {as : List α} : as ≃ as := fun a => rfl theorem permEqvTrans {as bs cs : List α} (h : as ≃ bs) (h' : bs ≃ cs) : as ≃ cs := fun a => Eq.trans (h a) (h' a) theorem permEqvSymm {as bs : List α} (h : as ≃ bs) : bs ≃ as := fun a => by simp [Nat.add_comm, h a] theorem permEqvToEraseAppend {as bs : List α} (ps : bs ⊆ as) : as ≃ ((as -l bs) ++ bs) := fun a => by simp only [count_append, count_eraseAll]; rw [←Nat.le_subAdd (ps a)] theorem permEqvToEraseCons {as : List α} {a : α} (h : a ∈ as) : as ≃ (a :: (as.erase a)) := by exact permEqvTrans (permEqvToEraseAppend (permSubSingleton h)) (permEqvRotate _ _) theorem permEqvCons {as bs : List α} {a : α} (h : as ≃ bs) : (a :: as) ≃ (a :: bs) := by intro b byCases hba : (a = b) case inl => cases hba; simp [count_self_cons, h a]; case inr => rw [count_neq_cons hba, count_neq_cons hba, h b] theorem permSubEraseOfpermEqvCons {as bs : List α} {a : α} (h : (a :: as) ⊆ bs) : as ⊆ (bs.erase a) := fun b => by let ha := h a byCases h' : a = b case inl => cases h' rw [count_erase] rw [count_self_cons] at ha simp [Nat.leOfSuccLeSucc (Nat.leTrans ha leSuccSubOne)] case inr => let hb := h b rw [count_neq_cons h'] at hb rw [count_erase, beq_neq h'] exact hb theorem permEqvOfPermSub {as bs : List α} : as ⊆ bs → as.length = bs.length → as ≃ bs := match as with | [] => fun hsub hl => by rw [length_nil, Eq.symm_iff, length_zero_iff_nil] at hl rw [hl]; intro b; rfl | a :: as => fun hsub hl => by have habs : a ∈ bs := by rw [mem_nonzeroCount] let hsuba := hsub a simp only [count_self_cons] at hsuba exact Nat.ltOfLtOfLe (Nat.zeroLtSucc _) hsuba have hsub' : as.isPermSubOf (bs.erase a) := permSubEraseOfpermEqvCons hsub have hl' : as.length = (bs.erase a).length := by apply Nat.add_right_cancel (m := 1) rw [length_erase_mem habs, ←hl, length_cons] have hp : bs.isPermEqvTo (a :: (bs.erase a)) := permEqvToEraseCons habs exact permEqvTrans (permEqvCons (permEqvOfPermSub hsub' hl')) (permEqvSymm hp) theorem permEqvMemClosed {as bs : List α} {a : α} (hp : as ≃ bs) : a ∈ as → a ∈ bs := by rw [mem_nonzeroCount, mem_nonzeroCount, hp a]; intros; assumption theorem permEqvEraseOfpermEqvCons {as bs : List α} {a : α} (h : (a :: as) ≃ bs) : as ≃ (bs.erase a) := fun a' => by let ha := h a byCases h' : a = a' case inl => cases h' rw [count_erase] simp only [beq_refl, Lean.Simp.ite_True] rw [←ha, count_self_cons, succ_sub_succ, Nat.sub_zero] case inr => let ha' := h a' rw [count_neq_cons h'] at ha' rw [count_erase, beq_neq h'] exact ha' theorem permEqvLength {as bs : List α} : as ≃ bs → as.length = bs.length := match as with | [] => match bs with | [] => fun _ => rfl | b :: bs => fun h => by let hb := h b simp only [count] at hb; rw [filter_cons, beq_refl] at hb simp at hb | a :: as => fun h => by let ha := h a rw [count_self_cons] at ha rw [length_cons, permEqvLength (permEqvEraseOfpermEqvCons h)] exact length_erase_mem (mem_nonzeroCount.mpr (Nat.ltOfLtOfEq (Nat.zeroLtSucc (count as a)) ha)) theorem permEqv_filter_erase_true {as : List α} {a : α} {p : α → Bool} (hpa : p a = true) (ha : a ∈ as) : (a :: filter p (List.erase as a)) ≃ (filter p as) := by intro b byCases h : a = b case inl => cases h rw [count_self_cons, filter_erase_true hpa, count_erase] simp only [beq_refl, Lean.Simp.ite_True] have h' : 1 ≤ count (filter p as) a := by apply Nat.succLeOfLt apply mem_nonzeroCount.mp apply mem_filter_of_prop ha hpa exact Eq.symm (le_subAdd h') case inr => rw [count_neq_cons h, filter_erase_true hpa, count_erase, beq_neq h] simp theorem permEqvFilter {as bs : List α} (p : α → Bool) : as ≃ bs → (filter p as) ≃ (filter p bs) := match as with | [] => by intro h rw [length_zero_iff_nil.mp $ Eq.symm (permEqvLength h)] exact permEqvRefl | a :: as => by intro h rw [filter_cons] have h' := permEqvFilter p (permEqvEraseOfpermEqvCons h) cases hpa : p a with | true => simp only [beq_refl, Lean.Simp.ite_True] apply permEqvTrans (permEqvCons h') have ha : a ∈ bs := by rw [mem_nonzeroCount, ←h a]; simp [zeroLtSucc] exact permEqv_filter_erase_true (as := bs) hpa ha | false => refine permEqvTrans h' ?_ rw [filter_erase_false hpa] exact permEqvRefl end Count end List
3d5aef3de341b4b95d2aea3e0d755a8358700d34
947b78d97130d56365ae2ec264df196ce769371a
/src/Init/Control/Id.lean
20107fd0bd946591f83867a6e2933b01b45b5fe8
[ "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
780
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich The identity Monad. -/ prelude import Init.Control.MonadLift import Init.Control.MonadRun universe u def Id (type : Type u) : Type u := type @[inline] def Id.pure {α : Type u} (x : α) : Id α := x @[inline] def Id.bind {α β : Type u} (x : Id α) (f : α → Id β) : Id β := f x @[inline] def Id.map {α β : Type u} (f : α → β) (x : Id α) : Id β := f x instance Id.hasBind : HasBind Id := { bind := @Id.bind } instance Id.monad : Monad Id := { pure := @Id.pure, bind := @Id.bind, map := @Id.map } @[inline] def Id.run {α : Type u} (x : Id α) : α := x instance : MonadRun id Id := ⟨@Id.run⟩
3e212f4a7d4485a4770def77c7debbfe61e1a482
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/format.lean
a55e7cc091548ea2dd05c4a3a36fd92a76ca1884
[ "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
4,718
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.options universe variables u v inductive format.color | red | green | orange | blue | pink | cyan | grey meta constant format : Type meta constant format.line : format meta constant format.space : format meta constant format.nil : format meta constant format.compose : format → format → format meta constant format.nest : nat → format → format meta constant format.highlight : format → color → format meta constant format.group : format → format meta constant format.of_string : string → format meta constant format.of_nat : nat → format meta constant format.flatten : format → format meta constant format.to_string : format → options → string meta constant format.of_options : options → format meta constant format.is_nil : format → bool meta constant trace_fmt {α : Type u} : format → (unit → α) → α meta instance : inhabited format := ⟨format.space⟩ meta instance : has_append format := ⟨format.compose⟩ meta instance : has_to_string format := ⟨λ f, format.to_string f options.mk⟩ meta class has_to_format (α : Type u) := (to_format : α → format) meta instance : has_to_format format := ⟨id⟩ meta def to_fmt {α : Type u} [has_to_format α] : α → format := has_to_format.to_format meta instance nat_to_format : has_coe nat format := ⟨format.of_nat⟩ meta instance string_to_format : has_coe string format := ⟨format.of_string⟩ open format list meta def format.indent (f : format) (n : nat) : format := nest n (line ++ f) meta def format.when {α : Type u} [has_to_format α] : bool → α → format | tt a := to_fmt a | ff a := nil meta instance : has_to_format options := ⟨λ o, format.of_options o⟩ meta instance : has_to_format bool := ⟨λ b, if b then of_string "tt" else of_string "ff"⟩ meta instance {p : Prop} : has_to_format (decidable p) := ⟨λ b : decidable p, @ite p b _ (of_string "tt") (of_string "ff")⟩ meta instance : has_to_format string := ⟨λ s, format.of_string s⟩ meta instance : has_to_format nat := ⟨λ n, format.of_nat n⟩ meta instance : has_to_format char := ⟨λ c : char, format.of_string [c]⟩ meta def list.to_format_aux {α : Type u} [has_to_format α] : bool → list α → format | b [] := to_fmt "" | tt (x::xs) := to_fmt x ++ list.to_format_aux ff xs | ff (x::xs) := to_fmt "," ++ line ++ to_fmt x ++ list.to_format_aux ff xs meta def list.to_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | (x::xs) := to_fmt "[" ++ group (nest 1 (list.to_format_aux tt (x::xs))) ++ to_fmt "]" meta instance {α : Type u} [has_to_format α] : has_to_format (list α) := ⟨list.to_format⟩ attribute [instance] string.has_to_format meta instance : has_to_format name := ⟨λ n, to_fmt (to_string n)⟩ meta instance : has_to_format unit := ⟨λ u, to_fmt "()"⟩ meta instance {α : Type u} [has_to_format α] : has_to_format (option α) := ⟨λ o, option.cases_on o (to_fmt "none") (λ a, to_fmt "(some " ++ nest 6 (to_fmt a) ++ to_fmt ")")⟩ meta instance sum_has_to_format {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (sum α β) := ⟨λ s, sum.cases_on s (λ a, to_fmt "(inl " ++ nest 5 (to_fmt a) ++ to_fmt ")") (λ b, to_fmt "(inr " ++ nest 5 (to_fmt b) ++ to_fmt ")")⟩ open prod meta instance {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (prod α β) := ⟨λ p, group (nest 1 (to_fmt "(" ++ to_fmt p.1 ++ to_fmt "," ++ line ++ to_fmt p.2 ++ to_fmt ")"))⟩ open sigma meta instance {α : Type u} {β : α → Type v} [has_to_format α] [s : ∀ x, has_to_format (β x)] : has_to_format (sigma β) := ⟨λ p, group (nest 1 (to_fmt "⟨" ++ to_fmt p.1 ++ to_fmt "," ++ line ++ to_fmt p.2 ++ to_fmt "⟩"))⟩ open subtype meta instance {α : Type u} {p : α → Prop} [has_to_format α] : has_to_format (subtype p) := ⟨λ s, to_fmt (elt_of s)⟩ meta def format.bracket : string → string → format → format | o c f := to_fmt o ++ nest (utf8_length o) f ++ to_fmt c meta def format.paren (f : format) : format := format.bracket "(" ")" f meta def format.cbrace (f : format) : format := format.bracket "{" "}" f meta def format.sbracket (f : format) : format := format.bracket "[" "]" f meta def format.dcbrace (f : format) : format := to_fmt "⦃" ++ nest 1 f ++ to_fmt "⦄"
2eb9ff586ca2ba24afb34c809e9a73ab8af820d7
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/matchNoPostponing.lean
69c32a9eef45f8ffe00714c76f7123978b1ef06f
[ "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
485
lean
new_frontend /- In the following example, type of `x` and `y` could be any type `α` s.t. `[HasOfNat α]`. It relies on `SyntheticMVarKind.withDefault` to set `α := Nat`. Moreover, we must commit to `α := Nat` before we try to build de `matcher` since `mkMatcher` assumes `matchType` does not contain metavariables. We accomplish that by invoking `synthesizeSyntheticMVarsNoPostponing` at `elabMatch`. -/ def foo : IO Unit := do let (x, y) ← pure (0, 0); IO.println x
9f05e310ed2fae2a8dcda51112b913297ad67c00
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/ord_continuous.lean
efa28ab5c5ef830043d62badae746e65c5ffb52f
[ "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
8,036
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, Johannes Hölzl -/ import order.conditionally_complete_lattice import logic.function.iterate import order.rel_iso /-! # Order continuity We say that a function is *left order continuous* if it sends all least upper bounds to least upper bounds. The order dual notion is called *right order continuity*. For monotone functions `ℝ → ℝ` these notions correspond to the usual left and right continuity. We prove some basic lemmas (`map_sup`, `map_Sup` etc) and prove that an `rel_iso` is both left and right order continuous. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open set function /-! ### Definitions -/ /-- A function `f` between preorders is left order continuous if it preserves all suprema. We define it using `is_lub` instead of `Sup` so that the proof works both for complete lattices and conditionally complete lattices. -/ def left_ord_continuous [preorder α] [preorder β] (f : α → β) := ∀ ⦃s : set α⦄ ⦃x⦄, is_lub s x → is_lub (f '' s) (f x) /-- A function `f` between preorders is right order continuous if it preserves all infima. We define it using `is_glb` instead of `Inf` so that the proof works both for complete lattices and conditionally complete lattices. -/ def right_ord_continuous [preorder α] [preorder β] (f : α → β) := ∀ ⦃s : set α⦄ ⦃x⦄, is_glb s x → is_glb (f '' s) (f x) namespace left_ord_continuous section preorder variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} protected lemma id : left_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h variable {α} protected lemma order_dual (hf : left_ord_continuous f) : @right_ord_continuous (order_dual α) (order_dual β) _ _ f := hf lemma map_is_greatest (hf : left_ord_continuous f) {s : set α} {x : α} (h : is_greatest s x): is_greatest (f '' s) (f x) := ⟨mem_image_of_mem f h.1, (hf h.is_lub).1⟩ lemma mono (hf : left_ord_continuous f) : monotone f := λ a₁ a₂ h, have is_greatest {a₁, a₂} a₂ := ⟨or.inr rfl, by simp [*]⟩, (hf.map_is_greatest this).2 $ mem_image_of_mem _ (or.inl rfl) lemma comp (hg : left_ord_continuous g) (hf : left_ord_continuous f) : left_ord_continuous (g ∘ f) := λ s x h, by simpa only [image_image] using hg (hf h) protected lemma iterate {f : α → α} (hf : left_ord_continuous f) (n : ℕ) : left_ord_continuous (f^[n]) := nat.rec_on n (left_ord_continuous.id α) $ λ n ihn, ihn.comp hf end preorder section semilattice_sup variables [semilattice_sup α] [semilattice_sup β] {f : α → β} lemma map_sup (hf : left_ord_continuous f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (hf is_lub_pair).unique $ by simp only [image_pair, is_lub_pair] lemma le_iff (hf : left_ord_continuous f) (h : injective f) {x y} : f x ≤ f y ↔ x ≤ y := by simp only [← sup_eq_right, ← hf.map_sup, h.eq_iff] lemma lt_iff (hf : left_ord_continuous f) (h : injective f) {x y} : f x < f y ↔ x < y := by simp only [lt_iff_le_not_le, hf.le_iff h] variable (f) /-- Convert an injective left order continuous function to an order embedding. -/ def to_order_embedding (hf : left_ord_continuous f) (h : injective f) : α ↪o β := ⟨⟨f, h⟩, λ x y, (hf.le_iff h).symm⟩ variable {f} @[simp] lemma coe_to_order_embedding (hf : left_ord_continuous f) (h : injective f) : ⇑(hf.to_order_embedding f h) = f := rfl end semilattice_sup section complete_lattice variables [complete_lattice α] [complete_lattice β] {f : α → β} lemma map_Sup' (hf : left_ord_continuous f) (s : set α) : f (Sup s) = Sup (f '' s) := (hf $ is_lub_Sup s).Sup_eq.symm lemma map_Sup (hf : left_ord_continuous f) (s : set α) : f (Sup s) = ⨆ x ∈ s, f x := by rw [hf.map_Sup', Sup_image] lemma map_supr (hf : left_ord_continuous f) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [supr, hf.map_Sup', ← range_comp] end complete_lattice section conditionally_complete_lattice variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {f : α → β} lemma map_cSup (hf : left_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_above s) : f (Sup s) = Sup (f '' s) := ((hf $ is_lub_cSup sne sbdd).cSup_eq $ sne.image f).symm lemma map_csupr (hf : left_ord_continuous f) {g : ι → α} (hg : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by simp only [supr, hf.map_cSup (range_nonempty _) hg, ← range_comp] end conditionally_complete_lattice end left_ord_continuous namespace right_ord_continuous section preorder variables (α) [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} protected lemma id : right_ord_continuous (id : α → α) := λ s x h, by simpa only [image_id] using h variable {α} protected lemma order_dual (hf : right_ord_continuous f) : @left_ord_continuous (order_dual α) (order_dual β) _ _ f := hf lemma map_is_least (hf : right_ord_continuous f) {s : set α} {x : α} (h : is_least s x): is_least (f '' s) (f x) := hf.order_dual.map_is_greatest h lemma mono (hf : right_ord_continuous f) : monotone f := hf.order_dual.mono.order_dual lemma comp (hg : right_ord_continuous g) (hf : right_ord_continuous f) : right_ord_continuous (g ∘ f) := hg.order_dual.comp hf.order_dual protected lemma iterate {f : α → α} (hf : right_ord_continuous f) (n : ℕ) : right_ord_continuous (f^[n]) := hf.order_dual.iterate n end preorder section semilattice_inf variables [semilattice_inf α] [semilattice_inf β] {f : α → β} lemma map_inf (hf : right_ord_continuous f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := hf.order_dual.map_sup x y lemma le_iff (hf : right_ord_continuous f) (h : injective f) {x y} : f x ≤ f y ↔ x ≤ y := hf.order_dual.le_iff h lemma lt_iff (hf : right_ord_continuous f) (h : injective f) {x y} : f x < f y ↔ x < y := hf.order_dual.lt_iff h variable (f) /-- Convert an injective left order continuous function to a `order_embedding`. -/ def to_order_embedding (hf : right_ord_continuous f) (h : injective f) : α ↪o β := ⟨⟨f, h⟩, λ x y, (hf.le_iff h).symm⟩ variable {f} @[simp] lemma coe_to_order_embedding (hf : right_ord_continuous f) (h : injective f) : ⇑(hf.to_order_embedding f h) = f := rfl end semilattice_inf section complete_lattice variables [complete_lattice α] [complete_lattice β] {f : α → β} lemma map_Inf' (hf : right_ord_continuous f) (s : set α) : f (Inf s) = Inf (f '' s) := hf.order_dual.map_Sup' s lemma map_Inf (hf : right_ord_continuous f) (s : set α) : f (Inf s) = ⨅ x ∈ s, f x := hf.order_dual.map_Sup s lemma map_infi (hf : right_ord_continuous f) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.order_dual.map_supr g end complete_lattice section conditionally_complete_lattice variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {f : α → β} lemma map_cInf (hf : right_ord_continuous f) {s : set α} (sne : s.nonempty) (sbdd : bdd_below s) : f (Inf s) = Inf (f '' s) := hf.order_dual.map_cSup sne sbdd lemma map_cinfi (hf : right_ord_continuous f) {g : ι → α} (hg : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := hf.order_dual.map_csupr hg end conditionally_complete_lattice end right_ord_continuous namespace order_iso section preorder variables [preorder α] [preorder β] (e : α ≃o β) {s : set α} {x : α} protected lemma left_ord_continuous : left_ord_continuous e := λ s x hx, ⟨monotone.mem_upper_bounds_image (λ x y, e.map_rel_iff.1) hx.1, λ y hy, e.rel_symm_apply.1 $ (is_lub_le_iff hx).2 $ λ x' hx', e.rel_symm_apply.2 $ hy $ mem_image_of_mem _ hx'⟩ protected lemma right_ord_continuous : right_ord_continuous e := order_iso.left_ord_continuous e.dual end preorder end order_iso
28941aed866e13f4f1432bf6fe2e59eab23187d6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/continuous_functions.lean
ffe25ebd56aa3d179350b64214d586bd6827f7df
[]
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
13,280
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.module import Mathlib.topology.continuous_map import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Algebraic structures over continuous functions In this file we define instances of algebraic structures over continuous functions. Instances are present both in the case of the subtype of continuous functions and the type of continuous bundled functions. Both implementations have advantages and disadvantages, but many experienced people in Zulip have expressed a preference towards continuous bundled maps, so when there is no particular reason to use the subtype, continuous bundled functions should be used for the sake of uniformity. -/ namespace continuous_functions protected instance set_of.has_coe_to_fun {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] : has_coe_to_fun ↥(set_of fun (f : α → β) => continuous f) := has_coe_to_fun.mk (fun (x : ↥(set_of fun (f : α → β) => continuous f)) => α → β) subtype.val end continuous_functions namespace continuous_map protected instance has_mul {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [Mul β] [has_continuous_mul β] : Mul (continuous_map α β) := { mul := fun (f g : continuous_map α β) => mk (⇑f * ⇑g) } protected instance has_one {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [HasOne β] : HasOne (continuous_map α β) := { one := const 1 } end continuous_map /-! ### Group stucture In this section we show that continuous functions valued in a topological group inherit the structure of a group. -/ protected instance continuous_submonoid (α : Type u_1) (β : Type u_2) [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : is_submonoid (set_of fun (f : α → β) => continuous f) := is_submonoid.mk continuous_const fun (f g : α → β) (fc : f ∈ set_of fun (f : α → β) => continuous f) (gc : g ∈ set_of fun (f : α → β) => continuous f) => continuous.comp has_continuous_mul.continuous_mul (continuous.prod_mk fc gc) protected instance continuous_add_subgroup (α : Type u_1) (β : Type u_2) [topological_space α] [topological_space β] [add_group β] [topological_add_group β] : is_add_subgroup (set_of fun (f : α → β) => continuous f) := is_add_subgroup.mk fun (f : (i : α) → (fun (ᾰ : α) => β) i) (fc : f ∈ set_of fun (f : α → β) => continuous f) => continuous.comp continuous_neg fc protected instance continuous_monoid {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid ↥(set_of fun (f : α → β) => continuous f) := subtype.monoid protected instance continuous_group {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [group β] [topological_group β] : group ↥(set_of fun (f : α → β) => continuous f) := subtype.group protected instance continuous_add_comm_group {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [add_comm_group β] [topological_add_group β] : add_comm_group ↥(set_of fun (f : α → β) => continuous f) := subtype.add_comm_group protected instance continuous_map_semigroup {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [semigroup β] [has_continuous_mul β] : semigroup (continuous_map α β) := semigroup.mk Mul.mul sorry protected instance continuous_map_add_monoid {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [add_monoid β] [has_continuous_add β] : add_monoid (continuous_map α β) := add_monoid.mk add_semigroup.add sorry 0 sorry sorry protected instance continuous_map_add_comm_monoid {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [add_comm_monoid β] [has_continuous_add β] : add_comm_monoid (continuous_map α β) := add_comm_monoid.mk add_semigroup.add sorry 0 sorry sorry sorry protected instance continuous_map_group {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [group β] [topological_group β] : group (continuous_map α β) := group.mk monoid.mul sorry monoid.one sorry sorry (fun (f : continuous_map α β) => continuous_map.mk fun (x : α) => coe_fn f x⁻¹) (div_inv_monoid.div._default monoid.mul sorry monoid.one sorry sorry fun (f : continuous_map α β) => continuous_map.mk fun (x : α) => coe_fn f x⁻¹) sorry protected instance continuous_map_add_comm_group {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [add_comm_group β] [topological_add_group β] : add_comm_group (continuous_map α β) := add_comm_group.mk add_group.add sorry add_group.zero sorry sorry add_group.neg add_group.sub sorry sorry /-! ### Ring stucture In this section we show that continuous functions valued in a topological ring `R` inherit the structure of a ring. -/ protected instance continuous_subring (α : Type u_1) (R : Type u_2) [topological_space α] [topological_space R] [ring R] [topological_ring R] : is_subring (set_of fun (f : α → R) => continuous f) := is_subring.mk protected instance continuous_ring {α : Type u_1} {R : Type u_2} [topological_space α] [topological_space R] [ring R] [topological_ring R] : ring ↥(set_of fun (f : α → R) => continuous f) := subtype.ring protected instance continuous_comm_ring {α : Type u_1} {R : Type u_2} [topological_space α] [topological_space R] [comm_ring R] [topological_ring R] : comm_ring ↥(set_of fun (f : α → R) => continuous f) := subtype.comm_ring protected instance continuous_map_semiring {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] : semiring (continuous_map α β) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry monoid.mul sorry monoid.one sorry sorry sorry sorry sorry sorry protected instance continuous_map_ring {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [ring β] [topological_ring β] : ring (continuous_map α β) := ring.mk semiring.add sorry semiring.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry protected instance continuous_map_comm_ring {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] [comm_ring β] [topological_ring β] : comm_ring (continuous_map α β) := comm_ring.mk semiring.add sorry semiring.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry sorry /-! ### Semiodule stucture In this section we show that continuous functions valued in a topological semimodule `M` over a topological semiring `R` inherit the structure of a semimodule. -/ protected instance continuous_has_scalar {α : Type u_1} [topological_space α] {R : Type u_2} [semiring R] [topological_space R] {M : Type u_3} [topological_space M] [add_comm_group M] [semimodule R M] [topological_semimodule R M] : has_scalar R ↥(set_of fun (f : α → M) => continuous f) := has_scalar.mk fun (r : R) (f : ↥(set_of fun (f : α → M) => continuous f)) => { val := r • ⇑f, property := sorry } protected instance continuous_semimodule {α : Type u_1} [topological_space α] {R : Type u_2} [semiring R] [topological_space R] {M : Type u_3} [topological_space M] [add_comm_group M] [topological_add_group M] [semimodule R M] [topological_semimodule R M] : semimodule R ↥(set_of fun (f : α → M) => continuous f) := semimodule.of_core (semimodule.core.mk (has_scalar.mk has_scalar.smul) sorry sorry sorry sorry) protected instance continuous_map_has_scalar {α : Type u_1} [topological_space α] {R : Type u_2} [semiring R] [topological_space R] {M : Type u_3} [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] : has_scalar R (continuous_map α M) := has_scalar.mk fun (r : R) (f : continuous_map α M) => continuous_map.mk (r • ⇑f) protected instance continuous_map_semimodule {α : Type u_1} [topological_space α] {R : Type u_2} [semiring R] [topological_space R] {M : Type u_3} [topological_space M] [add_comm_monoid M] [has_continuous_add M] [semimodule R M] [topological_semimodule R M] : semimodule R (continuous_map α M) := semimodule.mk sorry sorry /-! ### 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 `topological_semimodule` and a `topological_semiring` (by now we require `topological_ring`: see TODO below).-/ /-- Continuous constant functions as a `ring_hom`. -/ def continuous.C {α : Type u_1} [topological_space α] {R : Type u_2} [comm_semiring R] {A : Type u_3} [topological_space A] [ring A] [algebra R A] [topological_ring A] : R →+* ↥(set_of fun (f : α → A) => continuous f) := ring_hom.mk (fun (c : R) => { val := fun (x : α) => coe_fn (algebra_map R A) c, property := sorry }) sorry sorry sorry sorry protected instance set_of.algebra {α : Type u_1} [topological_space α] {R : Type u_2} [comm_semiring R] {A : Type u_3} [topological_space A] [ring A] [algebra R A] [topological_ring A] [topological_space R] [topological_semimodule R A] : algebra R ↥(set_of fun (f : α → A) => continuous f) := algebra.mk continuous.C sorry sorry /- TODO: We are assuming `A` to be a ring and not a semiring just because there is not yet an instance of semiring. In turn, we do not want to define yet an instance of semiring because there is no `is_subsemiring` but only `subsemiring`, and it will make sense to change this when the whole file will have no more `is_subobject`s but only `subobject`s. It does not make sense to change it yet in this direction as `subring` does not exist yet, so everything is being blocked by `subring`: afterwards everything will need to be updated to the new conventions of Mathlib. Then the instance of `topological_ring` can also be removed, as it is below for `continuous_map`. -/ /-- Continuous constant functions as a `ring_hom`. -/ def continuous_map.C {α : Type u_1} [topological_space α] {R : Type u_2} [comm_semiring R] {A : Type u_3} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] : R →+* continuous_map α A := ring_hom.mk (fun (c : R) => continuous_map.mk fun (x : α) => coe_fn (algebra_map R A) c) sorry sorry sorry sorry protected instance continuous_map_algebra {α : Type u_1} [topological_space α] {R : Type u_2} [comm_semiring R] {A : Type u_3} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] [topological_space R] [topological_semimodule R A] : algebra R (continuous_map α A) := algebra.mk continuous_map.C sorry sorry /-! ### 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 `M`. -/ protected instance continuous_has_scalar' {α : Type u_1} [topological_space α] {R : Type u_2} [semiring R] [topological_space R] {M : Type u_3} [topological_space M] [add_comm_group M] [semimodule R M] [topological_semimodule R M] : has_scalar ↥(set_of fun (f : α → R) => continuous f) ↥(set_of fun (f : α → M) => continuous f) := has_scalar.mk fun (f : ↥(set_of fun (f : α → R) => continuous f)) (g : ↥(set_of fun (f : α → M) => continuous f)) => { val := fun (x : α) => coe_fn f x • coe_fn g x, property := sorry } protected instance continuous_module' {α : Type u_1} [topological_space α] (R : Type u_2) [ring R] [topological_space R] [topological_ring R] (M : Type u_3) [topological_space M] [add_comm_group M] [topological_add_group M] [module R M] [topological_module R M] : module ↥(set_of fun (f : α → R) => continuous f) ↥(set_of fun (f : α → M) => continuous f) := semimodule.of_core (semimodule.core.mk (has_scalar.mk has_scalar.smul) sorry sorry sorry sorry) protected instance continuous_map_has_scalar' {α : Type u_1} [topological_space α] {R : Type u_2} [semiring R] [topological_space R] {M : Type u_3} [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] : has_scalar (continuous_map α R) (continuous_map α M) := has_scalar.mk fun (f : continuous_map α R) (g : continuous_map α M) => continuous_map.mk fun (x : α) => coe_fn f x • coe_fn g x protected instance continuous_map_module' {α : Type u_1} [topological_space α] (R : Type u_2) [ring R] [topological_space R] [topological_ring R] (M : Type u_3) [topological_space M] [add_comm_monoid M] [has_continuous_add M] [semimodule R M] [topological_semimodule R M] : semimodule (continuous_map α R) (continuous_map α M) := semimodule.mk sorry sorry
2eb18f4e97bf1816120ed1948b69d4632e7d028a
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/geo/sieves.lean
c392d8760434973eb7a7c24f39a29ffe15f36e06
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
8,087
lean
import category_theory.comma import algebra.category.CommRing import .global import .ideals import .Omega import data.opposite import ring_theory.ideals import .src.sieve import .src.grothendieck open category_theory open opposite universes u local notation `Ring` := CommRing.{u} local notation `Aff` := Ringᵒᵖ local notation `Set` := Type u --- The goals is to define Zariski topology on Aff := Ringᵒᵖ --- We use the definition on Topos theory ! --- Starting we ideal lemma namespace ideals lemma set_image_S_subset_set_image_span_S (A B : Ring )(f : A ⟶ B) (S : set A) : set.image f S ⊆ set.image f (ideal.span S) := begin apply set.image_subset, exact ideal.subset_span , end lemma ideal.map_span_eq_span_image(A B : Ring )(f : A ⟶ B) (S : set A): ideal.span (set.image f S) = ideal.map f (ideal.span S) := begin apply le_antisymm, exact ideal.span_mono (set_image_S_subset_set_image_span_S A B f S), exact ideal.map_le_iff_le_comap.2 (ideal.span_le.2 (set.image_subset_iff.1 (ideal.subset_span))), end -- idée -- Profiter de ⊤ lemma top_ideal_map (A B : Ring)(f : A ⟶ B)(S : set A) : ideal.span S = ⊤ → ideal.span (set.image f S) = ⊤ := λ certif, begin rw ideal.map_span_eq_span_image, rw certif, exact ideal.map_top f, end lemma one_ideal_map {A B : Ring}(f : A ⟶ B)(S : set A) : (1 : A) ∈ ideal.span S → (1 : B) ∈ ideal.span( set.image f S) := λ P, begin have hyp : f 1 ∈ ideal.span (set.image f S), rw ideal.map_span_eq_span_image, apply ideal.mem_map_of_mem, exact P, rw f.map_one at hyp, assumption, end end ideals open ideals namespace Pre_sieves structure Presieves (X : Aff) := (S : set (X.unop)) (co_maximality : (1 : X.unop) ∈ ideal.span S) @[ext] lemma ext (X : Aff) (P Q : Presieves X) : P.S = Q.S → P = Q := begin intros h1, cases P, cases Q, congr ; try { assumption }, end def pull_back{X Y : Aff}(f : Y ⟶ X) : Presieves(X) → Presieves(Y) := λ P, begin exact {S := set.image f.unop P.S, co_maximality := one_ideal_map f.unop P.S P.co_maximality}, end lemma pull_back_ext {X Y : Aff}(f : Y ⟶ X)(P : Presieves X): (pull_back f P).S = set.image f.unop P.S := rfl /- Test for a Presieves to be eq to pull-back. -/ theorem pull_back_eq {X Y : Aff}(f : Y ⟶ X)(P : Presieves X)(Q_Y : Presieves Y) : pull_back f P = Q_Y ↔ set.image f.unop P.S = Q_Y.S := begin split, intros, subst a, rw pull_back_ext, intros, apply ext, rw pull_back_ext, assumption, end /- Direct image of a presieves. -/ lemma inverse_image_ideal (A B : Ring)(f : A ⟶ B)(S : set B) : ideal.span (set.preimage f S) ≤ ideal.comap f (ideal.span S) := begin rw ideal.span_le, -- span S \leq I ↔ S ≤ I apply set.preimage_mono ideal.subset_span, end def direct_image (X Y : Aff) (P : Presieves Y) (h : Y ⟶ X) : Presieves(X) := begin -- inverse image -- h : R(X) ⟶ R(Y) and P : set R(Y) with 1 ∈ ideal.span P.S -- i take : P' := { comap h S } have hyp : (1 : X.unop) ∈ ideal.span (set.preimage h.unop (ideal.span(P.S))), apply ideal.subset_span, rw set.mem_preimage, have F : (has_hom.hom.unop h) 1 = (1 : Y.unop), exact h.unop.map_one, have j : (1 : Y.unop) ∈ ideal.span P.S, exact P.co_maximality, rw ← F at j, assumption, have hyp2 : (ideal.span (set.preimage h.unop (ideal.span(P.S))) : set X.unop) = set.preimage h.unop (ideal.span(P.S)), -- exact {S := set.preimage h.unop P.S, co_maximality := hyp}, end end Pre_sieves open Pre_sieves def sieves_of (X : Aff) (P : Presieves X) := { f : over X |∃ s : P.S, ∃ u : unop f.left, ((f.hom s.val * u ) : unop f.left ) = 1 } -- Ici le plus simple va être de faire appel à units ! -- lemma mem_sieves (X : Aff) (P : Presieves X)(f : over X) : ( ∃ s : P.S, ∃ u : unop f.left, ((f.hom s.val * u ) : unop f.left ) = 1) → f ∈ (sieves_of X P) := λ hyp, hyp lemma sieves_mem {X : Aff} {P : Presieves X}{f : over X} : f ∈ (sieves_of X P) → (∃ s : P.S,∃ u : unop f.left, ((f.hom s.val * u ) : unop f.left ) = 1) := λ hyp,hyp def subs (X : Aff) (P : Presieves X) : ∀ (f : over X) (hyp : f ∈ (sieves_of X P)) (Z : Aff) (g : Z ⟶ f.left), (over.mk (g ≫ f.hom)) ∈ (sieves_of X P) := begin intros, apply mem_sieves, rw over.mk_hom, rcases hyp with ⟨s,u, hyp_su⟩, use s, use g u, show g.unop( f.hom(s.val)) * g.unop (u) = (1 : unop Z), rw ← g.unop.map_mul (f.hom s.val) u,rw hyp_su, exact g.unop.map_one, end def Aff_sieves (X : Aff )(P : Presieves X) : sieve(X) := {arrows := sieves_of X P,subs := subs X P} def Aff_sieves_arrow (X : Aff )(P : Presieves X) : (Aff_sieves X P).arrows = sieves_of X P := rfl /- Fondamental theorem : le faire mieux avec Aff_sieves ! -/ theorem pull_back_stability{X Y: Aff}(h : Y ⟶ X) (S : Presieves X)(f : over Y) : (over.mk (f.hom ≫ h)) ∈ Aff_sieves X S → f ∈ (Aff_sieves Y (pull_back h S)) := λ fh_hyp, begin rcases sieves_mem fh_hyp with s, apply mem_sieves, use h.unop s, rw pull_back_ext, exact set.mem_image_of_mem h.unop s.property, exact h_1, end theorem pull_back_stability'{X Y: Aff}(h : Y ⟶ X) (S : Presieves X)(f : over Y) : f ∈ (Aff_sieves Y (pull_back h S)) → (over.mk (f.hom ≫ h)) ∈ Aff_sieves X S := λ fh_hyp, begin rcases sieves_mem fh_hyp with hs, apply mem_sieves, cases set.mem_image_iff_bex.1 hs.property with s hyp_s, use s, rcases hyp_s with hyp_hs, exact hyp_hs, rcases hyp_s with hyp_hs, rw ← hyp_s_h at h_1, exact h_1, end /- Zariski -/ def Zariski_topology( X : Aff) := {S : sieve X | ∃ P : Presieves X, S = Aff_sieves X P} lemma mem_Zariski ( X : Aff) (S : sieve X) : S ∈ Zariski_topology( X) → ∃ P : Presieves X, S = Aff_sieves X P := λ SS, begin cases SS with a t, use a, exact t, end lemma mem_Zariski_ ( X : Aff) (S : sieve X) : (∃ P : Presieves X, S = Aff_sieves X P) → S ∈ Zariski_topology( X) := λ hyp, hyp def Zariski_of (X : Aff) : Presieves X → Zariski_topology(X) := λ S,begin use Aff_sieves X S, unfold Zariski_topology, split, show Aff_sieves X S = Aff_sieves X S, exact rfl, end -- But : prouver que Zariski Topology is grothendieck topology ! -- Il nous faut parler du sieves max def max'(X : Aff) : sieve X := Zariski_of (X) ({S := {(1 : unop X)}, co_maximality := begin apply ideal.subset_span, exact set.mem_singleton 1, end }) lemma max_is_max(X : Aff) : max'(X) = ⊤ := begin ext f, split,intros, trivial, intros hyp, apply mem_sieves, use 1,exact set.mem_singleton 1,use 1,rw mul_one, exact f.hom.unop.map_one, end lemma pull_back_comp (X Y : Aff) (P : Presieves X) (h : Y ⟶ X) : sieve.pullback (Aff_sieves X P) h = Aff_sieves Y (pull_back h P) := begin ext f, split, intros hyp,apply pull_back_stability, rw ← sieve.pullback_def2 h,exact hyp, intros, show f ∈ sieve.pullback (Aff_sieves X P) h, rw sieve.pullback_def2 h, apply pull_back_stability',exact a, end #print grothendieck def stab' (X Y : Aff) (S ∈ Zariski_topology X) (h : Y ⟶ X) : sieve.pullback S h ∈ Zariski_topology(Y) := begin apply mem_Zariski_ Y, cases H with P Hyp, use pull_back h P, subst Hyp , exact pull_back_comp X Y P h , end -- il nous faut étudier un peu les choses ! -- Par exemple l'hypothèse : (f : over X), sieve.pullback R f.fom ∈ Zariski(f.left) -- f : Z → X, il existe (S(Z) set Z) tel que sieve.pullback R f.hom = Ring sieve S(Z) -- g Z' → Z, g f ∈ R ↔ ∃ s_Z g s_Z inversible def trans' (X : Aff)(S ∈ Zariski_topology X)(R : sieve X) : (∀(f : over X), f ∈ S → sieve.pullback R f.hom ∈ Zariski_topology(f.left)) → (R ∈ Zariski_topology(X)) := begin sorry, end
c06711156f8c1716230a2430fe4dd0f675aef18e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/power_series/basic.lean
cebc6b129f80978df34ea12303b211f9498e21d1
[ "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
76,108
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp.interval import data.mv_polynomial.basic import data.polynomial.algebra_map import data.polynomial.coeff import linear_algebra.std_basis import ring_theory.ideal.local_ring import ring_theory.multiplicity import tactic.linarith /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m < n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators polynomial /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (mv_power_series σ A) := pi.module _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) : monomial R n = linear_map.std_basis R _ n := by convert rfl -- unify the `decidable` arguments lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same R _ n a lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne R _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one [decidable_eq σ] : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : add_monoid_with_one (mv_power_series σ R) := { nat_cast := λ n, monomial R 0 n, nat_cast_zero := by simp [nat.cast], nat_cast_succ := by simp [nat.cast, monomial_zero_one], one := 1, .. mv_power_series.add_monoid } instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, add_tsub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, add_tsub_cancel_right], exact le_add_left le_rfl end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.add_monoid_with_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, tsub_add_cancel_of_le h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, add_tsub_cancel_right] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X [decidable_eq σ] (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by simp only [coeff_X, single_left_inj one_ne_zero] @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_monomial_mul, if_neg this] end variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map _ @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma smul_eq_C_mul (f : mv_power_series σ R) (a : R) : a • f = C σ R a * f := by { ext, simp } lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [mv_power_series.X] end map section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.module } theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) := begin change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _, simp, end instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], inhabit σ, refine ⟨X default, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, not_forall], refine ⟨finsupp.single default 1, _⟩, simp [algebra_map_apply, coeff_C], end⟩⟩ end algebra section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := ∑ m in finset.Iio n, mv_polynomial.monomial m (coeff R m φ) lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc_fun n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc_fun, mv_polynomial.coeff_sum] variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := by { ext, simp [coeff_trunc_fun] }, map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc R n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, coeff_trunc_fun] @[simp] lemma trunc_one (hnn : n ≠ 0) : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, simp }, { symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), }, { symmetry, rw mv_polynomial.coeff_one, refine if_neg _, rintro rfl, apply H, exact ne.bot_lt hnn, } end @[simp] lemma trunc_C (hnn : n ≠ 0) (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, exact ne.bot_lt hnn, end end trunc section comm_semiring variable [comm_semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [add_tsub_cancel_left, finsupp.add_apply, finsupp.tsub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, rw [coe_add, coe_add, pi.add_apply, pi.add_apply, add_tsub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using tsub_add_cancel_of_le H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, begin rw inv.aux, convert rfl -- unify `decidable` instances end /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : Rˣ) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal, { rw [finsupp.mem_antidiagonal, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul, mul_neg, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_rfl), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance [local_ring R] : local_ring (mv_power_series σ R) := local_ring.of_is_unit_or_is_unit_one_sub_self $ by { intro φ, rcases local_ring.is_unit_or_is_unit_one_sub_self (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit, rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp] lemma zero_inv : (0 : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_zero] @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul_cancel (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv_cancel h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul_cancel _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv_cancel _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] @[simp] protected lemma mul_inv_rev (φ ψ : mv_power_series σ k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := begin by_cases h : constant_coeff σ k (φ * ψ) = 0, { rw inv_eq_zero.mpr h, simp only [map_mul, mul_eq_zero] at h, -- we don't have `no_zero_divisors (mw_power_series σ k)` yet, cases h; simp [inv_eq_zero.mpr h] }, { rw [mv_power_series.inv_eq_iff_mul_eq_one h], simp only [not_or_distrib, map_mul, mul_eq_zero] at h, rw [←mul_assoc, mul_assoc _⁻¹, mv_power_series.inv_mul_cancel _ h.left, mul_one, mv_power_series.inv_mul_cancel _ h.right] } end instance : inv_one_class (mv_power_series σ k) := { inv_one := by { rw [mv_power_series.inv_eq_iff_mul_eq_one, mul_one], simp }, ..mv_power_series.has_one, ..mv_power_series.has_inv } @[simp] lemma C_inv (r : k) : (C σ k r)⁻¹ = C σ k r⁻¹ := begin rcases eq_or_ne r 0 with rfl|hr, { simp }, rw [mv_power_series.inv_eq_iff_mul_eq_one, ←map_mul, inv_mul_cancel hr, map_one], simpa using hr end @[simp] lemma X_inv (s : σ) : (X s : mv_power_series σ k)⁻¹ = 0 := by rw [inv_eq_zero, constant_coeff_X] @[simp] lemma smul_inv (r : k) (φ : mv_power_series σ k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := by simp [smul_eq_C_mul, mul_comm] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : mv_polynomial σ R) /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ lemma coe_def : (φ : mv_power_series σ R) = λ n, coeff n φ := rfl @[simp, norm_cast] lemma coeff_coe (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : mv_polynomial σ R) : mv_power_series σ R) = bit0 (φ : mv_power_series σ R) := coe_add _ _ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : mv_polynomial σ R) : mv_power_series σ R) = bit1 (φ : mv_power_series σ R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ variables (σ R) lemma coe_injective : function.injective (coe : mv_polynomial σ R → mv_power_series σ R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {σ R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : mv_power_series σ R) = ψ ↔ φ = ψ := (coe_injective σ R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : mv_power_series σ R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : mv_power_series σ R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp, norm_cast] lemma coe_pow (n : ℕ) : ((φ ^ n : mv_polynomial σ R) : mv_power_series σ R) = (φ : mv_power_series σ R) ^ n := coe_to_mv_power_series.ring_hom.map_pow _ _ variables (φ ψ) @[simp] lemma coe_to_mv_power_series.ring_hom_apply : coe_to_mv_power_series.ring_hom φ = φ := rfl section algebra variables (A : Type*) [comm_semiring A] [algebra R A] lemma algebra_map_apply (r : R) : algebra_map R (mv_polynomial σ A) r = C (algebra_map R A r) := rfl /-- The coercion from multivariable polynomials to multivariable power series as an algebra homomorphism. -/ def coe_to_mv_power_series.alg_hom : mv_polynomial σ R →ₐ[R] mv_power_series σ A := { commutes' := λ r, by simp [algebra_map_apply, mv_power_series.algebra_map_apply], ..(mv_power_series.map σ (algebra_map R A)).comp coe_to_mv_power_series.ring_hom} @[simp] lemma coe_to_mv_power_series.alg_hom_apply : (coe_to_mv_power_series.alg_hom A φ) = mv_power_series.map σ (algebra_map R A) ↑φ := rfl end algebra end mv_polynomial namespace mv_power_series variables {σ R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : mv_power_series σ R) instance algebra_mv_polynomial : algebra (mv_polynomial σ R) (mv_power_series σ A) := ring_hom.to_algebra (mv_polynomial.coe_to_mv_power_series.alg_hom A).to_ring_hom instance algebra_mv_power_series : algebra (mv_power_series σ R) (mv_power_series σ A) := (map σ (algebra_map R A)).to_algebra variables (A) lemma algebra_map_apply' (p : mv_polynomial σ R): algebra_map (mv_polynomial σ R) (mv_power_series σ A) p = map σ (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (mv_power_series σ R) (mv_power_series σ A) f = map σ (algebra_map R A) f := rfl end mv_power_series /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_smul R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance {A} [semiring A] [comm_semiring R] [algebra R A] : algebra R (power_series A) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by simp only [finsupp.unique_single_eq_iff] lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] @[simp] lemma X_ne_zero [nontrivial R] : (X : power_series R) ≠ 0 := λ H, by simpa only [coeff_one_X, one_ne_zero, map_zero] using congr_arg (coeff R 1) H lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := coeff_C n 1 lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul {S : Type*} [semiring S] [module R S] (n : ℕ) (φ : power_series S) (a : R) : coeff S n (a • φ) = a • coeff S n φ := rfl lemma smul_eq_C_mul (f : power_series R) (a : R) : a • f = C R a * f := by { ext, simp } @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) : coeff R (n + 1) (X * φ) = coeff R n φ := begin simp only [coeff, finsupp.single_add, add_comm n 1], convert φ.coeff_add_monomial_mul (single () 1) (single () n) _, rw one_mul, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp -- The following section duplicates the api of `data.polynomial.coeff` and should attempt to keep -- up to date with that section lemma coeff_C_mul_X_pow (x : R) (k n : ℕ) : coeff R n (C R x * X ^ k : power_series R) = if n = k then x else 0 := by simp [X_pow_eq, coeff_monomial] @[simp] theorem coeff_mul_X_pow (p : power_series R) (n d : ℕ) : coeff R (d + n) (p * X ^ n) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (d, n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end @[simp] theorem coeff_X_pow_mul (p : power_series R) (n d : ℕ) : coeff R (d + n) (X ^ n * p) = coeff R d p := begin rw [coeff_mul, finset.sum_eq_single (n,d), coeff_X_pow, if_pos rfl, one_mul], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, zero_mul], rintro rfl, apply h2, rw [finset.nat.mem_antidiagonal, add_comm, add_right_cancel_iff] at h1, subst h1 }, { rw add_comm, exact λ h1, (h1 (finset.nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : power_series R) (n d : ℕ) : coeff R d (p * X ^ n) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ((le_of_add_le_right (finset.nat.mem_antidiagonal.mp hx).le).trans_lt $ not_le.mp h).ne } end lemma coeff_X_pow_mul' (p : power_series R) (n d : ℕ) : coeff R d (X ^ n * p) = ite (n ≤ d) (coeff R (d - n) p) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_X_pow_mul], simp, }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, zero_mul], have := finset.nat.mem_antidiagonal.mp hx, rw add_comm at this, exact ((le_of_add_le_right this.le).trans_lt $ not_le.mp h).ne } end end /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h /-- Split off the constant coefficient. -/ lemma eq_shift_mul_X_add_const (φ : power_series R) : φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, mul_zero, ring_hom.map_mul], }, { simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end /-- Split off the constant coefficient. -/ lemma eq_X_mul_shift_add_const (φ : power_series R) : φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, zero_mul, ring_hom.map_mul], }, { simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl @[simp] lemma map_C (r : R) : map f (C _ r) = C _ (f r) := by { ext, simp [coeff_C, apply_ite f] } @[simp] lemma map_X : map f X = X := by { ext, simp [coeff_X, apply_ite f] } end map end semiring section comm_semiring variables [comm_semiring R] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end open finset nat /-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/ noncomputable def rescale (a : R) : power_series R →+* power_series R := { to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f), map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], }, map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one], split_ifs, { rw [h, pow_zero], }, refl, }, map_add' := by { intros, ext, exact mul_add _ _ _, }, map_mul' := λ f g, by { ext, rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum], apply sum_congr rfl, simp only [coeff_mk, prod.forall, nat.mem_antidiagonal], intros b c H, rw [←H, pow_add, mul_mul_mul_comm] }, } @[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) : coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _ @[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) := begin ext, simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk, power_series.coeff_mk _ _, coeff_C], split_ifs, { simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], }, { rw [zero_pow' n h, zero_mul], }, end lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) := by simp @[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) := by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul, ring_hom.coe_mk], } lemma rescale_mk (f : ℕ → R) (a : R) : rescale a (mk f) = mk (λ n : ℕ, a^n * (f n)) := by { ext, rw [coeff_rescale, coeff_mk, coeff_mk], } lemma rescale_rescale (f : power_series R) (a b : R) : rescale b (rescale a f) = rescale (a * b) f := begin ext, repeat { rw coeff_rescale, }, rw [mul_pow, mul_comm _ (b^n), mul_assoc], end lemma rescale_mul (a b : R) : rescale (a * b) = (rescale b).comp (rescale a) := by { ext, simp [← rescale_rescale], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : R[X] := ∑ m in Ico 0 n, polynomial.monomial m (coeff R m φ) lemma coeff_trunc (m) (n) (φ : power_series R) : (trunc n φ).coeff m = if m < n then coeff R m φ else 0 := by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff] @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc (n + 1) (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, rintro rfl, apply H, exact nat.zero_lt_succ _ } end @[simp] lemma trunc_C (n) (a : R) : trunc (n + 1) (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : Rˣ) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : Rˣ) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : Rˣ) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : Rˣ) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h /-- Two ways of removing the constant coefficient of a power series are the same. -/ lemma sub_const_eq_shift_mul_X (φ : power_series R) : φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X := sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ) lemma sub_const_eq_X_mul_shift (φ : power_series R) : φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) := sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ) end ring section comm_ring variables {A : Type*} [comm_ring A] @[simp] lemma rescale_X (a : A) : rescale a X = C A a * X := begin ext, simp only [coeff_rescale, coeff_C_mul, coeff_X], split_ifs with h; simp [h], end lemma rescale_neg_one_X : rescale (-1 : A) X = -X := by rw [rescale_X, map_neg, map_one, neg_one_mul] /-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/ noncomputable def eval_neg_hom : power_series A →+* power_series A := rescale (-1 : A) @[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X := rescale_neg_one_X end comm_ring section domain variables [ring R] [is_domain R] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, obtain rfl := le_antisymm hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : is_domain (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nontrivial, } end domain section is_domain variables [comm_ring R] [is_domain R] /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) := begin intros p q h, rw power_series.ext_iff at *, intros n, specialize h n, rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h, apply h.resolve_right, intro h', exact ha (pow_eq_zero h'), end end is_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl theorem algebra_map_apply {r : R} : algebra_map R (power_series A) r = C A (algebra_map R A r) := mv_power_series.algebra_map_apply instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) := mv_power_series.subalgebra.nontrivial end algebra section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp] lemma zero_inv : (0 : power_series k)⁻¹ = 0 := mv_power_series.zero_inv @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv_cancel φ h @[simp] protected lemma inv_mul_cancel (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul_cancel φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h @[simp] protected lemma mul_inv_rev (φ ψ : power_series k) : (φ * ψ)⁻¹ = ψ⁻¹ * φ⁻¹ := mv_power_series.mul_inv_rev _ _ instance : inv_one_class (power_series k) := mv_power_series.inv_one_class @[simp] lemma C_inv (r : k) : (C k r)⁻¹ = C k r⁻¹ := mv_power_series.C_inv _ @[simp] lemma X_inv : (X : power_series k)⁻¹ = 0 := mv_power_series.X_inv _ @[simp] lemma smul_inv (r : k) (φ : power_series k) : (r • φ)⁻¹ = r⁻¹ • φ⁻¹ := mv_power_series.smul_inv _ _ end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [semiring R] {φ : power_series R} lemma exists_coeff_ne_zero_iff_ne_zero : (∃ (n : ℕ), coeff R n φ ≠ 0) ↔ φ ≠ 0 := begin refine not_iff_not.mp _, push_neg, simp [power_series.ext_iff] end /-- The order of a formal power series `φ` is the greatest `n : part_enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ def order (φ : power_series R) : part_enat := if h : φ = 0 then ⊤ else nat.find (exists_coeff_ne_zero_iff_ne_zero.mpr h) /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := dif_pos rfl lemma order_finite_iff_ne_zero : (order φ).dom ↔ φ ≠ 0 := begin simp only [order], split, { split_ifs with h h; intro H, { contrapose! H, simpa [←part.eq_none_iff'] }, { exact h } }, { intro h, simp [h] } end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin simp only [order, order_finite_iff_ne_zero.mp h, not_false_iff, dif_neg, part_enat.get_coe'], generalize_proofs h, exact nat.find_spec h end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have := exists.intro n h, rw [order, dif_neg], { simp only [part_enat.coe_le_coe, nat.find_le_iff], exact ⟨n, le_rfl, h⟩ }, { exact exists_coeff_ne_zero_iff_ne_zero.mp ⟨n, h⟩ } end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ h } /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := part_enat.dom_of_le_coe H.le, rw [← part_enat.coe_get this, part_enat.coe_lt_coe] at H, exact coeff_order this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : part_enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using part_enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (part_enat.coe_lt_top i) }, { apply nat_le_order, simpa only [part_enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin rcases eq_or_ne φ 0 with rfl|hφ, { simpa using (part_enat.coe_ne_top _).symm }, simp [order, dif_neg hφ, nat.find_eq_iff] end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : part_enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using part_enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact part_enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (part_enat.coe_lt_top i) } }, { simpa [part_enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := begin refine le_order _ _ _, simp [coeff_of_lt_order] {contextual := tt} end private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_rfl, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw ←hi at H, rw [(coeff _ _).map_add, coeff_of_lt_order i H, add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order i hi, coeff_of_lt_order i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← nat.cast_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [part_enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [part_enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] /-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product with any other power series is `0`. -/ lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) : coeff R n (φ * ψ) = 0 := begin suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0, rw [this, finset.sum_const_zero], rw [coeff_mul], apply finset.sum_congr rfl (λ x hx, _), refine mul_eq_zero_of_right (coeff R x.fst φ) (coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)), rw finset.nat.mem_antidiagonal at hx, norm_cast, linarith, end lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R} (n : ℕ) (h : ↑n < ψ.order) : coeff R n (φ * (1 - ψ)) = coeff R n φ := by simp [coeff_mul_of_lt_order h, mul_sub] lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι) (φ : power_series R) (f : ι → power_series R) : (∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ := begin apply finset.induction_on s, { simp }, { intros a s ha ih t, simp only [finset.mem_insert, forall_eq_or_imp] at t, rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1], exact ih t.2 }, end -- TODO: link with `X_pow_dvd_iff` lemma X_pow_order_dvd (h : (order φ).dom) : X ^ ((order φ).get h) ∣ φ := begin refine ⟨power_series.mk (λ n, coeff R (n + (order φ).get h) φ), _⟩, ext n, simp only [coeff_mul, coeff_X_pow, coeff_mk, boole_mul, finset.sum_ite, finset.nat.filter_fst_eq_antidiagonal, finset.sum_const_zero, add_zero], split_ifs with hn hn, { simp [tsub_add_cancel_of_le hn] }, { simp only [finset.sum_empty], refine coeff_of_lt_order _ _, simpa [part_enat.coe_lt_iff] using λ _, hn } end lemma order_eq_multiplicity_X {R : Type*} [comm_semiring R] (φ : power_series R) : order φ = multiplicity X φ := begin rcases eq_or_ne φ 0 with rfl|hφ, { simp }, induction ho : order φ using part_enat.cases_on with n, { simpa [hφ] using ho }, have hn : φ.order.get (order_finite_iff_ne_zero.mpr hφ) = n, { simp [ho] }, rw ←hn, refine le_antisymm (le_multiplicity_of_pow_dvd $ X_pow_order_dvd (order_finite_iff_ne_zero.mpr hφ)) (part_enat.find_le _ _ _), rintro ⟨ψ, H⟩, have := congr_arg (coeff R n) H, rw [mul_comm, coeff_mul_of_lt_order, ←hn] at this, { exact coeff_order _ this }, { rw [X_pow_eq, order_monomial], split_ifs, { exact part_enat.coe_lt_top _ }, { rw [←hn, part_enat.coe_lt_coe], exact nat.lt_succ_self _ } } end end order_basic section order_zero_ne_one variables [semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_is_domain -- TODO: generalize to `[semiring R] [no_zero_divisors R]` variables [comm_ring R] [is_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := begin simp_rw [order_eq_multiplicity_X], exact multiplicity.mul X_prime end end order_is_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] (φ ψ : R[X]) /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe R[X] (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ lemma coe_def : (φ : power_series R) = power_series.mk (coeff φ) := rfl @[simp, norm_cast] lemma coeff_coe (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] } @[simp, norm_cast] lemma coe_zero : ((0 : R[X]) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R[X]) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add : ((φ + ψ : R[X]) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul : ((φ * ψ : R[X]) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : R[X]) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_bit0 : ((bit0 φ : R[X]) : power_series R) = bit0 (φ : power_series R) := coe_add φ φ @[simp, norm_cast] lemma coe_bit1 : ((bit1 φ : R[X]) : power_series R) = bit1 (φ : power_series R) := by rw [bit1, bit1, coe_add, coe_one, coe_bit0] @[simp, norm_cast] lemma coe_X : ((X : R[X]) : power_series R) = power_series.X := coe_monomial _ _ @[simp] lemma constant_coeff_coe : power_series.constant_coeff R φ = φ.coeff 0 := rfl variables (R) lemma coe_injective : function.injective (coe : R[X] → power_series R) := λ x y h, by { ext, simp_rw [←coeff_coe, h] } variables {R φ ψ} @[simp, norm_cast] lemma coe_inj : (φ : power_series R) = ψ ↔ φ = ψ := (coe_injective R).eq_iff @[simp] lemma coe_eq_zero_iff : (φ : power_series R) = 0 ↔ φ = 0 := by rw [←coe_zero, coe_inj] @[simp] lemma coe_eq_one_iff : (φ : power_series R) = 1 ↔ φ = 1 := by rw [←coe_one, coe_inj] variables (φ ψ) /-- The coercion from polynomials to power series as a ring homomorphism. -/ def coe_to_power_series.ring_hom : R[X] →+* power_series R := { to_fun := (coe : R[X] → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } @[simp] lemma coe_to_power_series.ring_hom_apply : coe_to_power_series.ring_hom φ = φ := rfl @[simp, norm_cast] lemma coe_pow (n : ℕ): ((φ ^ n : R[X]) : power_series R) = (φ : power_series R) ^ n := coe_to_power_series.ring_hom.map_pow _ _ variables (A : Type*) [semiring A] [algebra R A] /-- The coercion from polynomials to power series as an algebra homomorphism. -/ def coe_to_power_series.alg_hom : R[X] →ₐ[R] power_series A := { commutes' := λ r, by simp [algebra_map_apply, power_series.algebra_map_apply], ..(power_series.map (algebra_map R A)).comp coe_to_power_series.ring_hom } @[simp] lemma coe_to_power_series.alg_hom_apply : (coe_to_power_series.alg_hom A φ) = power_series.map (algebra_map R A) ↑φ := rfl end polynomial namespace power_series variables {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (f : power_series R) instance algebra_polynomial : algebra R[X] (power_series A) := ring_hom.to_algebra (polynomial.coe_to_power_series.alg_hom A).to_ring_hom instance algebra_power_series : algebra (power_series R) (power_series A) := (map (algebra_map R A)).to_algebra @[priority 100] -- see Note [lower instance priority] instance algebra_polynomial' {A : Type*} [comm_semiring A] [algebra R A[X]] : algebra R (power_series A) := ring_hom.to_algebra $ polynomial.coe_to_power_series.ring_hom.comp (algebra_map R A[X]) variables (A) lemma algebra_map_apply' (p : R[X]) : algebra_map R[X] (power_series A) p = map (algebra_map R A) p := rfl lemma algebra_map_apply'' : algebra_map (power_series R) (power_series A) f = map (algebra_map R A) f := rfl end power_series