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
3faf39bc5622c8d549882ebbc2c3484f884102c2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/polynomial/content.lean
121e7934aa49896044f047661749bba393813a29
[ "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
18,077
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.gcd_monoid.finset import data.polynomial.field_division import data.polynomial.erase_lead import data.polynomial.cancel_leads /-! # GCD structures on polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Definitions and basic results about polynomials over GCD domains, particularly their contents and primitive polynomials. ## Main Definitions Let `p : R[X]`. - `p.content` is the `gcd` of the coefficients of `p`. - `p.is_primitive` indicates that `p.content = 1`. ## Main Results - `polynomial.content_mul`: If `p q : R[X]`, then `(p * q).content = p.content * q.content`. - `polynomial.normalized_gcd_monoid`: The polynomial ring of a GCD domain is itself a GCD domain. -/ namespace polynomial open_locale polynomial section primitive variables {R : Type*} [comm_semiring R] /-- A polynomial is primitive when the only constant polynomials dividing it are units -/ def is_primitive (p : R[X]) : Prop := ∀ (r : R), C r ∣ p → is_unit r lemma is_primitive_iff_is_unit_of_C_dvd {p : R[X]} : p.is_primitive ↔ ∀ (r : R), C r ∣ p → is_unit r := iff.rfl @[simp] lemma is_primitive_one : is_primitive (1 : R[X]) := λ r h, is_unit_C.mp (is_unit_of_dvd_one (C r) h) lemma monic.is_primitive {p : R[X]} (hp : p.monic) : p.is_primitive := begin rintros r ⟨q, h⟩, exact is_unit_of_mul_eq_one r (q.coeff p.nat_degree) (by rwa [←coeff_C_mul, ←h]), end lemma is_primitive.ne_zero [nontrivial R] {p : R[X]} (hp : p.is_primitive) : p ≠ 0 := begin rintro rfl, exact (hp 0 (dvd_zero (C 0))).ne_zero rfl, end lemma is_primitive_of_dvd {p q : R[X]} (hp : is_primitive p) (hq : q ∣ p) : is_primitive q := λ a ha, is_primitive_iff_is_unit_of_C_dvd.mp hp a (dvd_trans ha hq) end primitive variables {R : Type*} [comm_ring R] [is_domain R] section normalized_gcd_monoid variable [normalized_gcd_monoid R] /-- `p.content` is the `gcd` of the coefficients of `p`. -/ def content (p : R[X]) : R := (p.support).gcd p.coeff lemma content_dvd_coeff {p : R[X]} (n : ℕ) : p.content ∣ p.coeff n := begin by_cases h : n ∈ p.support, { apply finset.gcd_dvd h }, rw [mem_support_iff, not_not] at h, rw h, apply dvd_zero, end @[simp] lemma content_C {r : R} : (C r).content = normalize r := begin rw content, by_cases h0 : r = 0, { simp [h0] }, have h : (C r).support = {0} := support_monomial _ h0, simp [h], end @[simp] lemma content_zero : content (0 : R[X]) = 0 := by rw [← C_0, content_C, normalize_zero] @[simp] lemma content_one : content (1 : R[X]) = 1 := by rw [← C_1, content_C, normalize_one] lemma content_X_mul {p : R[X]} : content (X * p) = content p := begin rw [content, content, finset.gcd_def, finset.gcd_def], refine congr rfl _, have h : (X * p).support = p.support.map ⟨nat.succ, nat.succ_injective⟩, { ext a, simp only [exists_prop, finset.mem_map, function.embedding.coe_fn_mk, ne.def, mem_support_iff], cases a, { simp [coeff_X_mul_zero, nat.succ_ne_zero] }, rw [mul_comm, coeff_mul_X], split, { intro h, use a, simp [h] }, { rintros ⟨b, ⟨h1, h2⟩⟩, rw ← nat.succ_injective h2, apply h1 } }, rw h, simp only [finset.map_val, function.comp_app, function.embedding.coe_fn_mk, multiset.map_map], refine congr (congr rfl _) rfl, ext a, rw mul_comm, simp [coeff_mul_X], end @[simp] lemma content_X_pow {k : ℕ} : content ((X : R[X]) ^ k) = 1 := begin induction k with k hi, { simp }, rw [pow_succ, content_X_mul, hi] end @[simp] lemma content_X : content (X : R[X]) = 1 := by { rw [← mul_one X, content_X_mul, content_one] } lemma content_C_mul (r : R) (p : R[X]) : (C r * p).content = normalize r * p.content := begin by_cases h0 : r = 0, { simp [h0] }, rw content, rw content, rw ← finset.gcd_mul_left, refine congr (congr rfl _) _; ext; simp [h0, mem_support_iff] end @[simp] lemma content_monomial {r : R} {k : ℕ} : content (monomial k r) = normalize r := by rw [← C_mul_X_pow_eq_monomial, content_C_mul, content_X_pow, mul_one] lemma content_eq_zero_iff {p : R[X]} : content p = 0 ↔ p = 0 := begin rw [content, finset.gcd_eq_zero_iff], split; intro h, { ext n, by_cases h0 : n ∈ p.support, { rw [h n h0, coeff_zero], }, { rw mem_support_iff at h0, push_neg at h0, simp [h0] } }, { intros x h0, simp [h] } end @[simp] lemma normalize_content {p : R[X]} : normalize p.content = p.content := finset.normalize_gcd lemma content_eq_gcd_range_of_lt (p : R[X]) (n : ℕ) (h : p.nat_degree < n) : p.content = (finset.range n).gcd p.coeff := begin apply dvd_antisymm_of_normalize_eq normalize_content finset.normalize_gcd, { rw finset.dvd_gcd_iff, intros i hi, apply content_dvd_coeff _ }, { apply finset.gcd_mono, intro i, simp only [nat.lt_succ_iff, mem_support_iff, ne.def, finset.mem_range], contrapose!, intro h1, apply coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le h h1), } end lemma content_eq_gcd_range_succ (p : R[X]) : p.content = (finset.range p.nat_degree.succ).gcd p.coeff := content_eq_gcd_range_of_lt _ _ (nat.lt_succ_self _) lemma content_eq_gcd_leading_coeff_content_erase_lead (p : R[X]) : p.content = gcd_monoid.gcd p.leading_coeff (erase_lead p).content := begin by_cases h : p = 0, { simp [h] }, rw [← leading_coeff_eq_zero, leading_coeff, ← ne.def, ← mem_support_iff] at h, rw [content, ← finset.insert_erase h, finset.gcd_insert, leading_coeff, content, erase_lead_support], refine congr rfl (finset.gcd_congr rfl (λ i hi, _)), rw finset.mem_erase at hi, rw [erase_lead_coeff, if_neg hi.1], end lemma dvd_content_iff_C_dvd {p : R[X]} {r : R} : r ∣ p.content ↔ C r ∣ p := begin rw C_dvd_iff_dvd_coeff, split, { intros h i, apply h.trans (content_dvd_coeff _) }, { intro h, rw [content, finset.dvd_gcd_iff], intros i hi, apply h i } end lemma C_content_dvd (p : R[X]) : C p.content ∣ p := dvd_content_iff_C_dvd.1 dvd_rfl lemma is_primitive_iff_content_eq_one {p : R[X]} : p.is_primitive ↔ p.content = 1 := begin rw [←normalize_content, normalize_eq_one, is_primitive], simp_rw [←dvd_content_iff_C_dvd], exact ⟨λ h, h p.content (dvd_refl p.content), λ h r hdvd, is_unit_of_dvd_unit hdvd h⟩, end lemma is_primitive.content_eq_one {p : R[X]} (hp : p.is_primitive) : p.content = 1 := is_primitive_iff_content_eq_one.mp hp open_locale classical noncomputable theory section prim_part /-- The primitive part of a polynomial `p` is the primitive polynomial gained by dividing `p` by `p.content`. If `p = 0`, then `p.prim_part = 1`. -/ def prim_part (p : R[X]) : R[X] := if p = 0 then 1 else classical.some (C_content_dvd p) lemma eq_C_content_mul_prim_part (p : R[X]) : p = C p.content * p.prim_part := begin by_cases h : p = 0, { simp [h] }, rw [prim_part, if_neg h, ← classical.some_spec (C_content_dvd p)], end @[simp] lemma prim_part_zero : prim_part (0 : R[X]) = 1 := if_pos rfl lemma is_primitive_prim_part (p : R[X]) : p.prim_part.is_primitive := begin by_cases h : p = 0, { simp [h] }, rw ← content_eq_zero_iff at h, rw is_primitive_iff_content_eq_one, apply mul_left_cancel₀ h, conv_rhs { rw [p.eq_C_content_mul_prim_part, mul_one, content_C_mul, normalize_content] } end lemma content_prim_part (p : R[X]) : p.prim_part.content = 1 := p.is_primitive_prim_part.content_eq_one lemma prim_part_ne_zero (p : R[X]) : p.prim_part ≠ 0 := p.is_primitive_prim_part.ne_zero lemma nat_degree_prim_part (p : R[X]) : p.prim_part.nat_degree = p.nat_degree := begin by_cases h : C p.content = 0, { rw [C_eq_zero, content_eq_zero_iff] at h, simp [h] }, conv_rhs { rw [p.eq_C_content_mul_prim_part, nat_degree_mul h p.prim_part_ne_zero, nat_degree_C, zero_add] }, end @[simp] lemma is_primitive.prim_part_eq {p : R[X]} (hp : p.is_primitive) : p.prim_part = p := by rw [← one_mul p.prim_part, ← C_1, ← hp.content_eq_one, ← p.eq_C_content_mul_prim_part] lemma is_unit_prim_part_C (r : R) : is_unit (C r).prim_part := begin by_cases h0 : r = 0, { simp [h0] }, unfold is_unit, refine ⟨⟨C ↑(norm_unit r)⁻¹, C ↑(norm_unit r), by rw [← ring_hom.map_mul, units.inv_mul, C_1], by rw [← ring_hom.map_mul, units.mul_inv, C_1]⟩, _⟩, rw [← normalize_eq_zero, ← C_eq_zero] at h0, apply mul_left_cancel₀ h0, conv_rhs { rw [← content_C, ← (C r).eq_C_content_mul_prim_part], }, simp only [units.coe_mk, normalize_apply, ring_hom.map_mul], rw [mul_assoc, ← ring_hom.map_mul, units.mul_inv, C_1, mul_one], end lemma prim_part_dvd (p : R[X]) : p.prim_part ∣ p := dvd.intro_left (C p.content) p.eq_C_content_mul_prim_part.symm lemma aeval_prim_part_eq_zero {S : Type*} [ring S] [is_domain S] [algebra R S] [no_zero_smul_divisors R S] {p : R[X]} {s : S} (hpzero : p ≠ 0) (hp : aeval s p = 0) : aeval s p.prim_part = 0 := begin rw [eq_C_content_mul_prim_part p, map_mul, aeval_C] at hp, have hcont : p.content ≠ 0 := λ h, hpzero (content_eq_zero_iff.1 h), replace hcont := function.injective.ne (no_zero_smul_divisors.algebra_map_injective R S) hcont, rw [map_zero] at hcont, exact eq_zero_of_ne_zero_of_mul_left_eq_zero hcont hp end lemma eval₂_prim_part_eq_zero {S : Type*} [comm_ring S] [is_domain S] {f : R →+* S} (hinj : function.injective f) {p : R[X]} {s : S} (hpzero : p ≠ 0) (hp : eval₂ f s p = 0) : eval₂ f s p.prim_part = 0 := begin rw [eq_C_content_mul_prim_part p, eval₂_mul, eval₂_C] at hp, have hcont : p.content ≠ 0 := λ h, hpzero (content_eq_zero_iff.1 h), replace hcont := function.injective.ne hinj hcont, rw [map_zero] at hcont, exact eq_zero_of_ne_zero_of_mul_left_eq_zero hcont hp end end prim_part lemma gcd_content_eq_of_dvd_sub {a : R} {p q : R[X]} (h : C a ∣ p - q) : gcd_monoid.gcd a p.content = gcd_monoid.gcd a q.content := begin rw content_eq_gcd_range_of_lt p (max p.nat_degree q.nat_degree).succ (lt_of_le_of_lt (le_max_left _ _) (nat.lt_succ_self _)), rw content_eq_gcd_range_of_lt q (max p.nat_degree q.nat_degree).succ (lt_of_le_of_lt (le_max_right _ _) (nat.lt_succ_self _)), apply finset.gcd_eq_of_dvd_sub, intros x hx, cases h with w hw, use w.coeff x, rw [← coeff_sub, hw, coeff_C_mul] end lemma content_mul_aux {p q : R[X]} : gcd_monoid.gcd (p * q).erase_lead.content p.leading_coeff = gcd_monoid.gcd (p.erase_lead * q).content p.leading_coeff := begin rw [gcd_comm (content _) _, gcd_comm (content _) _], apply gcd_content_eq_of_dvd_sub, rw [← self_sub_C_mul_X_pow, ← self_sub_C_mul_X_pow, sub_mul, sub_sub, add_comm, sub_add, sub_sub_cancel, leading_coeff_mul, ring_hom.map_mul, mul_assoc, mul_assoc], apply dvd_sub (dvd.intro _ rfl) (dvd.intro _ rfl), end @[simp] theorem content_mul {p q : R[X]} : (p * q).content = p.content * q.content := begin classical, suffices h : ∀ (n : ℕ) (p q : R[X]), ((p * q).degree < n) → (p * q).content = p.content * q.content, { apply h, apply (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_succ_self _))) }, intro n, induction n with n ih, { intros p q hpq, rw [with_bot.coe_zero, nat.with_bot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq, rcases hpq with rfl | rfl; simp }, intros p q hpq, by_cases p0 : p = 0, { simp [p0] }, by_cases q0 : q = 0, { simp [q0] }, rw [degree_eq_nat_degree (mul_ne_zero p0 q0), with_bot.coe_lt_coe, nat.lt_succ_iff_lt_or_eq, ← with_bot.coe_lt_coe, ← degree_eq_nat_degree (mul_ne_zero p0 q0), nat_degree_mul p0 q0] at hpq, rcases hpq with hlt | heq, { apply ih _ _ hlt }, rw [← p.nat_degree_prim_part, ← q.nat_degree_prim_part, ← with_bot.coe_eq_coe, with_bot.coe_add, ← degree_eq_nat_degree p.prim_part_ne_zero, ← degree_eq_nat_degree q.prim_part_ne_zero] at heq, rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part], suffices h : (q.prim_part * p.prim_part).content = 1, { rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.prim_part, mul_assoc, content_C_mul, content_C_mul, h, mul_one, content_prim_part, content_prim_part, mul_one, mul_one] }, rw [← normalize_content, normalize_eq_one, is_unit_iff_dvd_one, content_eq_gcd_leading_coeff_content_erase_lead, leading_coeff_mul, gcd_comm], apply (gcd_mul_dvd_mul_gcd _ _ _).trans, rw [content_mul_aux, ih, content_prim_part, mul_one, gcd_comm, ← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part, one_mul, mul_comm q.prim_part, content_mul_aux, ih, content_prim_part, mul_one, gcd_comm, ← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part], { rw [← heq, degree_mul, with_bot.add_lt_add_iff_right], { apply degree_erase_lt p.prim_part_ne_zero }, { rw [ne.def, degree_eq_bot], apply q.prim_part_ne_zero } }, { rw [mul_comm, ← heq, degree_mul, with_bot.add_lt_add_iff_left], { apply degree_erase_lt q.prim_part_ne_zero }, { rw [ne.def, degree_eq_bot], apply p.prim_part_ne_zero } } end theorem is_primitive.mul {p q : R[X]} (hp : p.is_primitive) (hq : q.is_primitive) : (p * q).is_primitive := by rw [is_primitive_iff_content_eq_one, content_mul, hp.content_eq_one, hq.content_eq_one, mul_one] @[simp] theorem prim_part_mul {p q : R[X]} (h0 : p * q ≠ 0) : (p * q).prim_part = p.prim_part * q.prim_part := begin rw [ne.def, ← content_eq_zero_iff, ← C_eq_zero] at h0, apply mul_left_cancel₀ h0, conv_lhs { rw [← (p * q).eq_C_content_mul_prim_part, p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part] }, rw [content_mul, ring_hom.map_mul], ring, end lemma is_primitive.dvd_prim_part_iff_dvd {p q : R[X]} (hp : p.is_primitive) (hq : q ≠ 0) : p ∣ q.prim_part ↔ p ∣ q := begin refine ⟨λ h, h.trans (dvd.intro_left _ q.eq_C_content_mul_prim_part.symm), λ h, _⟩, rcases h with ⟨r, rfl⟩, apply dvd.intro _, rw [prim_part_mul hq, hp.prim_part_eq], end theorem exists_primitive_lcm_of_is_primitive {p q : R[X]} (hp : p.is_primitive) (hq : q.is_primitive) : ∃ r : R[X], r.is_primitive ∧ (∀ s : R[X], p ∣ s ∧ q ∣ s ↔ r ∣ s) := begin classical, have h : ∃ (n : ℕ) (r : R[X]), r.nat_degree = n ∧ r.is_primitive ∧ p ∣ r ∧ q ∣ r := ⟨(p * q).nat_degree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩, rcases nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩, refine ⟨r, rprim, λ s, ⟨_, λ rs, ⟨pr.trans rs, qr.trans rs⟩⟩⟩, suffices hs : ∀ (n : ℕ) (s : R[X]), s.nat_degree = n → (p ∣ s ∧ q ∣ s → r ∣ s), { apply hs s.nat_degree s rfl }, clear s, by_contra' con, rcases nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩, have s0 : s ≠ 0, { contrapose! rs, simp [rs] }, have hs := nat.find_min' h ⟨_, s.nat_degree_prim_part, s.is_primitive_prim_part, (hp.dvd_prim_part_iff_dvd s0).2 ps, (hq.dvd_prim_part_iff_dvd s0).2 qs⟩, rw ← rdeg at hs, by_cases sC : s.nat_degree ≤ 0, { rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), is_primitive_iff_content_eq_one, content_C, normalize_eq_one] at rprim, rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs, apply rs rprim.dvd }, have hcancel := nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree hs (lt_of_not_ge sC), rw sdeg at hcancel, apply nat.find_min con hcancel, refine ⟨_, rfl, ⟨dvd_cancel_leads_of_dvd_of_dvd pr ps, dvd_cancel_leads_of_dvd_of_dvd qr qs⟩, λ rcs, rs _⟩, rw ← rprim.dvd_prim_part_iff_dvd s0, rw [cancel_leads, tsub_eq_zero_iff_le.mpr hs, pow_zero, mul_one] at rcs, have h := dvd_add rcs (dvd.intro_left _ rfl), have hC0 := rprim.ne_zero, rw [ne.def, ← leading_coeff_eq_zero, ← C_eq_zero] at hC0, rw [sub_add_cancel, ← rprim.dvd_prim_part_iff_dvd (mul_ne_zero hC0 s0)] at h, rcases is_unit_prim_part_C r.leading_coeff with ⟨u, hu⟩, apply h.trans (associated.symm ⟨u, _⟩).dvd, rw [prim_part_mul (mul_ne_zero hC0 s0), hu, mul_comm], end lemma dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part {p q : R[X]} (hq : q ≠ 0) : p ∣ q ↔ p.content ∣ q.content ∧ p.prim_part ∣ q.prim_part := begin split; intro h, { rcases h with ⟨r, rfl⟩, rw [content_mul, p.is_primitive_prim_part.dvd_prim_part_iff_dvd hq], exact ⟨dvd.intro _ rfl, p.prim_part_dvd.trans (dvd.intro _ rfl)⟩ }, { rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part], exact mul_dvd_mul (ring_hom.map_dvd C h.1) h.2 } end @[priority 100] instance normalized_gcd_monoid : normalized_gcd_monoid R[X] := normalized_gcd_monoid_of_exists_lcm $ λ p q, begin rcases exists_primitive_lcm_of_is_primitive p.is_primitive_prim_part q.is_primitive_prim_part with ⟨r, rprim, hr⟩, refine ⟨C (lcm p.content q.content) * r, λ s, _⟩, by_cases hs : s = 0, { simp [hs] }, by_cases hpq : C (lcm p.content q.content) = 0, { rw [C_eq_zero, lcm_eq_zero_iff, content_eq_zero_iff, content_eq_zero_iff] at hpq, rcases hpq with hpq | hpq; simp [hpq, hs] }, iterate 3 { rw dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part hs }, rw [content_mul, rprim.content_eq_one, mul_one, content_C, normalize_lcm, lcm_dvd_iff, prim_part_mul (mul_ne_zero hpq rprim.ne_zero), rprim.prim_part_eq, is_unit.mul_left_dvd _ _ _ (is_unit_prim_part_C (lcm p.content q.content)), ← hr s.prim_part], tauto, end lemma degree_gcd_le_left {p : R[X]} (hp : p ≠ 0) (q) : (gcd p q).degree ≤ p.degree := begin have := nat_degree_le_iff_degree_le.mp (nat_degree_le_of_dvd (gcd_dvd_left p q) hp), rwa degree_eq_nat_degree hp end lemma degree_gcd_le_right (p) {q : R[X]} (hq : q ≠ 0) : (gcd p q).degree ≤ q.degree := by { rw [gcd_comm], exact degree_gcd_le_left hq p } end normalized_gcd_monoid end polynomial
0e61c0385176da1b791391bdbd364fbc14c50cbb
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/pprod.lean
94ee99b10f2fe13f8f6a1a97a85b4d68d79373f5
[ "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
924
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ /-! # Extra facts about `pprod` -/ variables {α : Sort*} {β : Sort*} namespace pprod @[simp] lemma mk.eta {p : pprod α β} : pprod.mk p.1 p.2 = p := pprod.cases_on p (λ a b, rfl) @[simp] theorem «forall» {p : pprod α β → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : pprod α β → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ theorem forall' {p : α → β → Prop} : (∀ x : pprod α β, p x.1 x.2) ↔ ∀ a b, p a b := pprod.forall theorem exists' {p : α → β → Prop} : (∃ x : pprod α β, p x.1 x.2) ↔ ∃ a b, p a b := pprod.exists end pprod
1ed7ee36b8930df5e46c56fb110a230e0e3ce1d4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/generalize_proofs.lean
792166ed71dc3150b03f6229eeb29c4308ef322e
[ "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,067
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 tactic.doc_commands /-! # `generalize_proofs` A simple tactic to find and replace all occurrences of proof terms in the context and goal with new variables. -/ namespace tactic private meta def collect_proofs_in : expr → list expr → list name × list expr → tactic (list name × list expr) | e ctx (ns, hs) := let go (tac : list name × list expr → tactic (list name × list expr)) : tactic (list name × list expr) := do t ← infer_type e, mcond (is_prop t) (do first (hs.map $ λ h, do t' ← infer_type h, is_def_eq t t', g ← target, change $ g.replace (λ a n, if a = e then some h else none), return (ns, hs)) <|> (let (n, ns) := (match ns with | [] := (`_x, []) | (n :: ns) := (n, ns) end : name × list name) in do generalize e n, h ← intro n, return (ns, h::hs)) <|> return (ns, hs)) (tac (ns, hs)) in match e with | (expr.const _ _) := go return | (expr.local_const _ _ _ _) := do t ← infer_type e, collect_proofs_in t ctx (ns, hs) | (expr.mvar _ _ _) := do t ← infer_type e, collect_proofs_in t ctx (ns, hs) | (expr.app f x) := go (λ nh, collect_proofs_in f ctx nh >>= collect_proofs_in x ctx) | (expr.lam n b d e) := go (λ nh, do nh ← collect_proofs_in d ctx nh, var ← mk_local' n b d, collect_proofs_in (expr.instantiate_var e var) (var::ctx) nh) | (expr.pi n b d e) := do nh ← collect_proofs_in d ctx (ns, hs), var ← mk_local' n b d, collect_proofs_in (expr.instantiate_var e var) (var::ctx) nh | (expr.elet n t d e) := go (λ nh, do nh ← collect_proofs_in t ctx nh, nh ← collect_proofs_in d ctx nh, collect_proofs_in (expr.instantiate_var e d) ctx nh) | (expr.macro m l) := go (λ nh, mfoldl (λ x e, collect_proofs_in e ctx x) nh l) | _ := return (ns, hs) end /-- Generalize proofs in the goal, naming them with the provided list. -/ meta def generalize_proofs (ns : list name) (loc : interactive.loc) : tactic unit := do intros_dep, hs ← local_context >>= mfilter is_proof, n ← loc.get_locals >>= revert_lst, t ← target, collect_proofs_in t [] (ns, hs), intron n <|> (intros $> ()) open interactive interactive.types lean.parser local postfix *:9001 := many namespace interactive /-- Generalize proofs in the goal, naming them with the provided list. For example: ```lean example : list.nth_le [1, 2] 1 dec_trivial = 2 := begin -- ⊢ [1, 2].nth_le 1 _ = 2 generalize_proofs h, -- h : 1 < [1, 2].length -- ⊢ [1, 2].nth_le 1 h = 2 end ``` -/ meta def generalize_proofs : parse ident_* → parse location → tactic unit := tactic.generalize_proofs end interactive add_tactic_doc { name := "generalize_proofs", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize_proofs], tags := ["context management"] } end tactic
0ee35d1939d3b3ad4f0f9406c34aa6d8e32e8483
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/topology/continuous_on.lean
2ec704122ef145f9606125bd69f4ffdbcda79226
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
24,220
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions `nhds_within` of `nhds` `continuous_on` of `continuous` `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] /-- The "neighborhood within" filter. Elements of `nhds_within a s` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ principal s theorem nhds_within_eq (a : α) (s : set α) : nhds_within a s = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (t ∩ s) := have set.univ ∈ {s : set α | a ∈ s ∧ is_open s}, from ⟨set.mem_univ _, is_open_univ⟩, begin rw [nhds_within, nhds, lattice.binfi_inf]; try { exact this }, simp only [inf_principal] end theorem nhds_within_univ (a : α) : nhds_within a set.univ = 𝓝 a := by rw [nhds_within, principal_univ, lattice.inf_top_eq] theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := begin rw [nhds_within, mem_inf_principal, mem_nhds_sets_iff], split, { rintros ⟨u, hu, openu, au⟩, exact ⟨u, openu, au, λ x ⟨xu, xs⟩, hu xu xs⟩ }, rintros ⟨u, openu, au, hu⟩, exact ⟨u, λ x xu xs, hu ⟨xu, xs⟩, openu, au⟩ end lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := begin rw [nhds_within, mem_inf_principal], split, { exact λH, ⟨_, H, λx hx, hx.1 hx.2⟩ }, { exact λ⟨u, Hu, h⟩, mem_sets_of_superset Hu (λx xu xs, h ⟨xu, xs⟩ ) } end lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ nhds_within a t := mem_inf_sets_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ nhds_within a s := begin rw [nhds_within, mem_inf_principal], simp only [imp_self], exact univ_mem_sets end theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ nhds_within a s := inter_mem_sets (mem_inf_sets_of_right (mem_principal_self s)) (mem_inf_sets_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : nhds_within a s ≤ nhds_within a t := lattice.inf_le_inf (le_refl _) (principal_mono.mpr h) theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ nhds_within a s) : nhds_within a s = nhds_within a (s ∩ t) := le_antisymm (lattice.le_inf lattice.inf_le_left (le_principal_iff.mpr (inter_mem_sets self_mem_nhds_within h))) (lattice.inf_le_inf (le_refl _) (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict'' s $ mem_inf_sets_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict' s (mem_nhds_sets h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ nhds_within a t) : nhds_within a t ≤ nhds_within a s := begin rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩, have : nhds_within a t = nhds_within a (t ∩ u) := nhds_within_restrict _ au u_open, rw [this, inter_comm], exact nhds_within_mono _ uts end theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : nhds_within a t = nhds_within a u := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) : nhds_within a s = 𝓝 a := by rw [←nhds_within_univ]; apply nhds_within_eq_nhds_within h₀ h₁; rw [set.univ_inter, set.inter_self] @[simp] theorem nhds_within_empty (a : α) : nhds_within a {} = ⊥ := by rw [nhds_within, principal_empty, lattice.inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : nhds_within a (s ∪ t) = nhds_within a s ⊔ nhds_within a t := by unfold nhds_within; rw [←lattice.inf_sup_left, sup_principal] theorem nhds_within_inter (a : α) (s t : set α) : nhds_within a (s ∩ t) = nhds_within a s ⊓ nhds_within a t := by unfold nhds_within; rw [lattice.inf_left_comm, lattice.inf_assoc, inf_principal, ←lattice.inf_assoc, lattice.inf_idem] theorem nhds_within_inter' (a : α) (s t : set α) : nhds_within a (s ∩ t) = (nhds_within a s) ⊓ principal t := by { unfold nhds_within, rw [←inf_principal, lattice.inf_assoc] } lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : nhds_within (a, b) (s.prod t) = (nhds_within a s).prod (nhds_within b t) := by { unfold nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } theorem tendsto_if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (nhds_within a (s ∩ p)) l) (h₁ : tendsto g (nhds_within a (s ∩ {x | ¬ p x})) l) : tendsto (λ x, if p x then f x else g x) (nhds_within a s) l := by apply tendsto_if; rw [←nhds_within_inter']; assumption lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (nhds_within a s) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (set.image f (t ∩ s)) := have h₀ : directed_on ((λ (i : set α), principal (i ∩ s)) ⁻¹'o ge) {x : set α | x ∈ {t : set α | a ∈ t ∧ is_open t}}, from assume x ⟨ax, openx⟩ y ⟨ay, openy⟩, ⟨x ∩ y, ⟨⟨ax, ay⟩, is_open_inter openx openy⟩, le_principal_iff.mpr (set.inter_subset_inter_left _ (set.inter_subset_left _ _)), le_principal_iff.mpr (set.inter_subset_inter_left _ (set.inter_subset_right _ _))⟩, have h₁ : ∃ (i : set α), i ∈ {t : set α | a ∈ t ∧ is_open t}, from ⟨set.univ, set.mem_univ _, is_open_univ⟩, by { rw [nhds_within_eq, map_binfi_eq h₀ h₁], simp only [map_principal] } theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (nhds_within a t) l) : tendsto f (nhds_within a s) l := tendsto_le_left (nhds_within_mono a hst) h theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (nhds_within a s)) : tendsto f l (nhds_within a t) := tendsto_le_right (nhds_within_mono a hst) h theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (nhds_within a s) l := by rw [←nhds_within_univ] at h; exact tendsto_nhds_within_mono_left (set.subset_univ _) h theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : principal t = comap subtype.val (principal (subtype.val '' t)) := by rw comap_principal; rw set.preimage_image_eq; apply subtype.val_injective lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ nhds_within x s ≠ ⊥ := begin split, { assume hx, rw ← forall_sets_neq_empty_iff_neq_bot, assume o ho, rw mem_nhds_within at ho, rcases ho with ⟨u, u_open, xu, hu⟩, rw mem_closure_iff at hx, exact subset_ne_empty hu (hx u u_open xu) }, { assume h, rw mem_closure_iff, rintros u u_open xu, have : u ∩ s ∈ nhds_within x s, { rw mem_nhds_within, exact ⟨u, u_open, xu, subset.refl _⟩ }, exact forall_sets_neq_empty_iff_neq_bot.2 h (u ∩ s) this } end lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : nhds_within x s ≠ ⊥ := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : nhds_within x s ≠ ⊥) : x ∈ s := by simpa only [closure_eq_of_is_closed hs] using mem_closure_iff_nhds_within_ne_bot.2 hx /- nhds_within and subtypes -/ theorem mem_nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t u : set {x // x ∈ s}) : t ∈ nhds_within a u ↔ t ∈ comap (@subtype.val _ s) (nhds_within a.val (subtype.val '' u)) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : nhds_within a t = comap (@subtype.val _ s) (nhds_within a.val (subtype.val '' t)) := filter_eq $ by ext u; rw mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_val {s : set α} {a : α} (h : a ∈ s) : nhds_within a s = map subtype.val (𝓝 ⟨a, h⟩) := have h₀ : s ∈ nhds_within a s, by { rw [mem_nhds_within], existsi set.univ, simp [set.diff_eq] }, have h₁ : ∀ y ∈ s, ∃ x, @subtype.val _ s x = y, from λ y h, ⟨⟨y, h⟩, rfl⟩, begin rw [←nhds_within_univ, nhds_within_subtype, subtype.val_image_univ], exact (map_comap_of_surjective' h₀ h₁).symm, end theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (nhds_within a s) l ↔ tendsto (function.restrict f s) (𝓝 ⟨a, h⟩) l := by rw [tendsto, tendsto, function.restrict, nhds_within_eq_map_subtype_val h, ←(@filter.map_map _ _ _ _ subtype.val)] variables [topological_space β] [topological_space γ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (nhds_within x s) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (function.restrict f s) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (nhds_within (f x) (f '' s)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_sets_of_right $ mem_principal_sets.2 $ λ x, mem_image_of_mem _⟩ theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (function.restrict f s) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (function.restrict f s ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, function.restrict_eq, set.preimage_comp], simp only [subtype.preimage_val_eq_preimage_val_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous]; simp only [this] theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (function.restrict f s ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, function.restrict_eq, set.preimage_comp], simp only [subtype.preimage_val_eq_preimage_val_iff] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : nhds_within x s ≤ comap f (nhds_within (f x) (f '' s)) := map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := tendsto_le_left (nhds_within_mono x hs) h lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ nhds_within x s) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_tendsto (mem_closure_iff_nhds_within_ne_bot.1 hx) h $ mem_sets_of_superset self_mem_nhds_within (subset_preimage_image f s) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := begin rintros _ ⟨x, hx, rfl⟩, exact (hf x hx).mem_closure_image hx end theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (function.restrict f s)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin rintros _ ⟨x, xs, rfl⟩ t ht, rw [hleft x xs] at ht, replace h := h.nhds_le ⟨x, xs⟩, apply mem_nhds_within_of_mem_nhds, apply h, erw [map_compose.symm, function.comp, mem_map, ← nhds_within_eq_map_subtype_val], apply mem_sets_of_superset (inter_mem_nhds_within _ ht), assume y hy, rw [mem_set_of_eq, mem_preimage, hleft _ hy.1], exact hy.2 end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : ∀x ∈ s₁, g x = f x) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' x hx at A, have : {x : α | g x = f x} ∈ nhds_within x s₁ := mem_inf_sets_of_right h', apply tendsto.congr' _ A, convert this, ext, finish end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : ∀x ∈ s, g x = f x) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h end lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) : continuous_within_at (g ∘ f) s x := begin have : tendsto f (principal s) (principal t), by { rw tendsto_principal_principal, exact λx hx, h hx }, have : tendsto f (nhds_within x s) (principal t) := tendsto_le_left lattice.inf_le_right this, have : tendsto f (nhds_within x s) (nhds_within (f x) t) := tendsto_inf.2 ⟨hf, this⟩, exact tendsto.comp hg this end lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, tendsto_le_left (nhds_within_mono _ h) (hf x (h hx)) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := tendsto_le_left lattice.inf_le_left (h.tendsto x) lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf subset_preimage_univ lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ nhds_within x s := h ht lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ nhds_within (f x) (f '' s)) : f ⁻¹' t ∈ nhds_within x s := begin rw mem_nhds_within at ht, rcases ht with ⟨u, u_open, fxu, hu⟩, have : f ⁻¹' u ∩ s ∈ nhds_within x s := filter.inter_mem_sets (h (mem_nhds_sets u_open fxu)) self_mem_nhds_within, apply mem_sets_of_superset this, calc f ⁻¹' u ∩ s ⊆ f ⁻¹' u ∩ f ⁻¹' (f '' s) : inter_subset_inter_right _ (subset_preimage_image f s) ... = f ⁻¹' (u ∩ f '' s) : rfl ... ⊆ f ⁻¹' t : preimage_mono hu end lemma continuous_within_at.congr_of_mem_nhds_within {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : continuous_within_at f₁ s x := by rwa [continuous_within_at, filter.tendsto, hx, filter.map_cong h₁] lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_mem_nhds_within (mem_sets_of_superset self_mem_nhds_within h₁) hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open_inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed_inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) = interior (s ∩ f ⁻¹' (interior t)) : (interior_eq_of_open (hf.preimage_open_of_open hs is_open_interior)).symm ... ⊆ interior (s ∩ f ⁻¹' t) : interior_mono (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, interior_eq_of_open hs] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by { ext x, simp, split, finish, finish }, rw this, exact is_open_inter hu hv }, { rw [preimage_sUnion, inter_bUnion], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := tendsto_prod_mk_nhds hf hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
17aee28bfdb2830f963ce6ad4543cf1a60beb803
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/stone_cech.lean
fb50397d8a501f2fc13bda0237d5f0a372b05549
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,698
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.bases import topology.dense_embedding /-! # Stone-Čech compactification Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ noncomputable theory open filter set open_locale topological_space universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := range $ λ s : set α, {u | s ∈ u} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, inter_mem ua ub, assume v hv, ⟨_, _⟩⟩; apply mem_of_superset hv; simp [inter_subset_right a b] end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq_univ_of_forall (λ u, univ_mem)⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u} := ultrafilter_basis_is_basis.is_open ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u} := begin rw ← is_open_compl_iff, convert ultrafilter_is_open_basic sᶜ, ext u, exact ultrafilter.compl_mem_iff_not_mem.symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : ↑u ≤ 𝓝 x ↔ x = mjoin u := begin rw [eq_comm, ← ultrafilter.coe_le_coe], change ↑u ≤ 𝓝 x ↔ ∀ s ∈ x, {v : ultrafilter α | s ∈ v} ∈ u, simp only [topological_space.nhds_generate_from, le_infi_iff, ultrafilter_basis, le_principal_iff, mem_set_of_eq], split, { intros h a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros h a ⟨xi, a, rfl⟩, exact h _ xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨is_compact_iff_ultrafilter_le_nhds.mpr $ assume f _, ⟨mjoin f, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume x y f fx fy, have hx : x = mjoin f, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin f, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm instance : totally_disconnected_space (ultrafilter α) := begin rw totally_disconnected_space_iff_connected_component_singleton, intro A, simp only [set.eq_singleton_iff_unique_mem, mem_connected_component, true_and], intros B hB, rw ← ultrafilter.coe_le_coe, intros s hs, rw [connected_component_eq_Inter_clopen, set.mem_Inter] at hB, let Z := { F : ultrafilter α | s ∈ F }, have hZ : is_clopen Z := ⟨ultrafilter_is_open_basic s, ultrafilter_is_closed_basic s⟩, exact hB ⟨Z, hZ, hs⟩, end lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine infi_le_of_le {u | s ∈ u} _, refine infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, exact principal_mono.2 (λ a, id) end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α) := singleton_mem_pure, rw h at this, exact (mem_singleton_iff.mp (mem_pure.mp this)).symm end open topological_space /-- The range of `pure : α → ultrafilter α` is dense in `ultrafilter α`. -/ lemma dense_range_pure : dense_range (pure : α → ultrafilter α) := λ x, mem_closure_iff_ultrafilter.mpr ⟨x.map pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩ /-- The map `pure : α → ultra_filter α` induces on `α` the discrete topology. -/ lemma induced_topology_pure : topological_space.induced (pure : α → ultrafilter α) ultrafilter.topological_space = ⊥ := begin apply eq_bot_of_singletons_open, intros x, use [{u : ultrafilter α | {x} ∈ u}, ultrafilter_is_open_basic _], simp, end /-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/ lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥; exact ⟨⟨induced_topology_pure.symm⟩, dense_range_pure⟩ -- The following refined version will never be used /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥ ; exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure } end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f variables [t2_space γ] lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := begin letI : topological_space α := ⊥, haveI : discrete_topology α := ⟨rfl⟩, exact funext (dense_inducing_pure.extend_eq continuous_of_discrete_topology) end variables [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap pure (𝓝 b)) (𝓝 c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := compact_univ.ultrafilter_le_nhds (b.map f) (by rw [le_principal_iff]; exact univ_mem) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊥, haveI : normal_space γ := normal_of_compact_t2, exact dense_inducing_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ ↑(b.map f) ≤ 𝓝 c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : ↑b' ≤ 𝓝 b, from ultrafilter_converges_iff.mpr (bind_pure _).symm, rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) ↑b, rw ultrafilter_extend_extends, exact le_refl _ end, assume h, by letI : topological_space α := ⊥; exact dense_inducing_pure.extend_eq_of_tendsto (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance instance [inhabited α] : inhabited (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma dense_range_stone_cech_unit : dense_range (stone_cech_unit : α → stone_cech α) := dense_range_pure.quotient section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : ↑u ≤ 𝓝 x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g gx, have ↑(g.map pure) ≤ 𝓝 g, by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g.map stone_cech_unit : filter (stone_cech α)) ≤ 𝓝 ⟦g⟧, from continuous_at_iff_ultrafilter.mp (continuous_quotient_mk.tendsto g) _ this, by rwa (show ⟦g⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros ⟨x⟩ ⟨y⟩ g gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, let ff := stone_cech_extend hf, change ff ⟦x⟧ = ff ⟦y⟧, have lim := λ (z : ultrafilter α) (gz : (g : filter (stone_cech α)) ≤ 𝓝 ⟦z⟧), ((continuous_stone_cech_extend hf).tendsto _).mono_left gz, exact tendsto_nhds_unique (lim x gx) (lim y gy) end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
76e482fbff1dbbeb71eb12afc460a38bba45ca13
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/pseudo_normed_group/FP.lean
e7d97c354f76fa9595605dada0326ebffaf1f261
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,734
lean
import pseudo_normed_group.breen_deligne import for_mathlib.SemiNormedGroup /-! # Constructions on the filtration on a profinitely filtered pseudo-normed group ## Main definitions - `FiltrationPow r' c n`: the functor sending a profinitely filtered `M` to `M_c^n`. - `φ.eval_FP r' c₁ c₂`: The map M_c₁^m → M_c₂^n induced by a (c₁, c₂)-suitable φ. -/ open_locale classical nnreal big_operators noncomputable theory local attribute [instance] type_pow universe variables u @[simps] def pseudo_normed_group.filtration_obj (M) [profinitely_filtered_pseudo_normed_group M] (c) : Profinite := Profinite.of (pseudo_normed_group.filtration M c) open profinitely_filtered_pseudo_normed_group category_theory namespace Filtration variables (M : Type u) [profinitely_filtered_pseudo_normed_group M] @[simps] def cast_le (c₁ c₂ : ℝ≥0) [h : fact (c₁ ≤ c₂)] : pseudo_normed_group.filtration_obj.{u} M c₁ ⟶ pseudo_normed_group.filtration_obj.{u} M c₂ := { to_fun := pseudo_normed_group.cast_le, continuous_to_fun := continuous_cast_le c₁ c₂ } theorem cast_le_refl (c : ℝ≥0) : cast_le M c c = 𝟙 _ := by { ext, refl } theorem cast_le_comp (c₁ c₂ c₃ : ℝ≥0) [h₁ : fact (c₁ ≤ c₂)] [h₂ : fact (c₂ ≤ c₃)] : cast_le M c₁ c₂ ≫ cast_le M c₂ c₃ = @cast_le M _ c₁ c₃ ⟨le_trans h₁.1 h₂.1⟩ := by { ext, refl } end Filtration @[simps obj_obj obj_map_to_fun map_app {fully_applied := ff}] def Filtration (r' : ℝ≥0) : ℝ≥0 ⥤ ProFiltPseuNormGrpWithTinv.{u} r' ⥤ Profinite.{u} := { obj := λ c, { obj := λ M, pseudo_normed_group.filtration_obj M c, map := λ M N f, ⟨f.level c, f.level_continuous c⟩, map_id' := by { intros, ext, refl }, map_comp' := by { intros, ext, refl } }, map := λ c₁ c₂ h, { app := λ M, @Filtration.cast_le _ _ c₁ c₂ ⟨le_of_hom h⟩ }, map_id' := by { intros, ext, refl }, map_comp' := by { intros, ext, refl } } open SemiNormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne open profinitely_filtered_pseudo_normed_group open profinitely_filtered_pseudo_normed_group_with_Tinv /-- The functor that sends `A` to `A^n` -/ @[simps obj map] def Pow (n : ℕ) : Profinite ⥤ Profinite := { obj := λ A, of (A^n), map := λ A B f, { to_fun := λ x j, f (x j), continuous_to_fun := continuous_pi $ λ j, f.2.comp (continuous_apply j) } } @[simps] def Pow_Pow_X (N n : ℕ) (X) : (Pow N ⋙ Pow n).obj X ≅ (Pow (N * n)).obj X := Profinite.iso_of_homeo { to_equiv := (equiv.curry _ _ _).symm.trans (((equiv.prod_comm _ _).trans fin_prod_fin_equiv).arrow_congr (equiv.refl X)), continuous_to_fun := begin apply continuous_pi, intro ij, let k := ((equiv.prod_comm _ _).trans fin_prod_fin_equiv).symm ij, convert (@continuous_apply _ (λ i, X) _ k.2).comp (@continuous_apply _ (λ i, (X^N)) _ k.1), end, continuous_inv_fun := begin apply continuous_pi, intro i, refine continuous_pi _, intro j, exact continuous_apply _, end } . @[simps hom inv] def Pow_mul (N n : ℕ) : Pow (N * n) ≅ Pow N ⋙ Pow n := nat_iso.of_components (λ X, (Pow_Pow_X N n X).symm) begin intros X Y f, ext x i j, refl, end @[simps] def profinitely_filtered_pseudo_normed_group_with_Tinv.Tinv₀_hom {r' : ℝ≥0} (M : Type*) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] (c c₂ : ℝ≥0) [fact (c ≤ r' * c₂)] : filtration_obj M c ⟶ filtration_obj M c₂ := by exact ⟨Tinv₀ c c₂, Tinv₀_continuous _ _⟩ open profinitely_filtered_pseudo_normed_group_with_Tinv namespace Filtration @[simps] def res (r' c₁ c₂ : ℝ≥0) [h : fact (c₁ ≤ c₂)] : (Filtration r').obj c₁ ⟶ (Filtration r').obj c₂ := (Filtration r').map (hom_of_le h.1) theorem res_refl (r' c : ℝ≥0) : res r' c c = 𝟙 _ := by { ext, refl } theorem res_comp (r' c₁ c₂ c₃ : ℝ≥0) [h₁ : fact (c₁ ≤ c₂)] [h₂ : fact (c₂ ≤ c₃)] : res r' c₁ c₂ ≫ res r' c₂ c₃ = @res r' c₁ c₃ ⟨le_trans h₁.1 h₂.1⟩ := by { ext, refl } @[simps] def Tinv₀ {r' : ℝ≥0} (c c₂ : ℝ≥0) [fact (c ≤ r' * c₂)] : (Filtration.{u} r').obj c ⟶ (Filtration r').obj c₂ := { app := λ M, Tinv₀_hom M c c₂, naturality' := λ M₁ M₂ f, by { ext x, exact (f.map_Tinv _).symm } } theorem Tinv₀_comp_res {r' : ℝ≥0} (c₁ c₂ c₃ c₄ : ℝ≥0) [fact (c₁ ≤ r' * c₂)] [fact (c₃ ≤ r' * c₄)] [fact (c₂ ≤ c₄)] [fact (c₁ ≤ c₃)] : Tinv₀ c₁ c₂ ≫ res r' c₂ c₄ = res r' c₁ c₃ ≫ Tinv₀ c₃ c₄ := rfl def pi_iso (r' c : ℝ≥0) (M : ProFiltPseuNormGrpWithTinv r') (N : ℕ) : Profinite.of (filtration (M^N) c) ≅ Profinite.of ((filtration M c)^N) := Profinite.iso_of_homeo $ filtration_pi_homeo _ _ end Filtration /-- `FiltrationPow r' c n` is the functor sending a profinitely filtered `M` to `M_c^n`. -/ @[simps obj map {fully_applied := ff}] def FiltrationPow (r' : ℝ≥0) (c : ℝ≥0) (n : ℕ) : ProFiltPseuNormGrpWithTinv r' ⥤ Profinite := ProFiltPseuNormGrpWithTinv.Pow r' n ⋙ (Filtration r').obj c namespace FiltrationPow @[simps] def cast_le (r' c₁ c₂ : ℝ≥0) [fact (c₁ ≤ c₂)] (n : ℕ) : FiltrationPow.{u} r' c₁ n ⟶ FiltrationPow r' c₂ n := { app := λ M, (Filtration.cast_le _ c₁ c₂), naturality' := λ M N f, by { ext, refl } } theorem cast_le_refl (r' c : ℝ≥0) (n : ℕ) : cast_le r' c c n = 𝟙 _ := by { ext, refl } theorem cast_le_comp (r' c₁ c₂ c₃ : ℝ≥0) [h₁ : fact (c₁ ≤ c₂)] [h₂ : fact (c₂ ≤ c₃)] (n : ℕ) : cast_le r' c₁ c₂ n ≫ cast_le r' c₂ c₃ n = @cast_le r' c₁ c₃ ⟨le_trans h₁.1 h₂.1⟩ n := by { ext, refl } @[simps] def Tinv (r' : ℝ≥0) (c c₂) [fact (c ≤ r' * c₂)] (n) : FiltrationPow r' c n ⟶ FiltrationPow r' c₂ n := whisker_left _ (Filtration.Tinv₀ c c₂) lemma Tinv_app (r' : ℝ≥0) (c c₂) [fact (c ≤ r' * c₂)] (n M) : (Tinv r' c c₂ n).app M = (Tinv₀_hom _ c c₂) := rfl lemma cast_le_vcomp_Tinv (r' c₁ c₂ c₃ : ℝ≥0) [fact (c₁ ≤ c₂)] [fact (c₂ ≤ c₃)] [fact (c₁ ≤ r' * c₂)] [fact (c₂ ≤ r' * c₃)] (n : ℕ) : cast_le r' c₁ c₂ n ≫ Tinv r' c₂ c₃ n = Tinv r' c₁ c₂ n ≫ cast_le r' c₂ c₃ n := by { ext, refl } @[simps hom inv] def mul_iso (r' c : ℝ≥0) (M : ProFiltPseuNormGrpWithTinv r') (N n : ℕ) : (FiltrationPow r' c n).obj (ProFiltPseuNormGrpWithTinv.of r' (↥M ^ N)) ≅ (FiltrationPow r' c (N * n)).obj M := ((Filtration r').obj c).map_iso $ (ProFiltPseuNormGrpWithTinv.Pow_mul r' N n).symm.app _ end FiltrationPow namespace breen_deligne namespace basic_universal_map variables (r' c c₁ c₂ c₃ c₄ : ℝ≥0) {l m n : ℕ} (ϕ : basic_universal_map m n) open FiltrationPow profinitely_filtered_pseudo_normed_group_with_Tinv_hom @[simps] def eval_FP [ϕ.suitable c₁ c₂] : FiltrationPow.{u} r' c₁ m ⟶ FiltrationPow r' c₂ n := { app := λ M, { to_fun := ϕ.eval_png₀ M c₁ c₂, continuous_to_fun := ϕ.eval_png₀_continuous M c₁ c₂ }, naturality' := λ M₁ M₂ f, begin ext1 x, change ϕ.eval_png₀ M₂ c₁ c₂ ((FiltrationPow r' c₁ m).map f x) = (FiltrationPow r' c₂ n).map f (ϕ.eval_png₀ M₁ c₁ c₂ x), ext j, dsimp only [FiltrationPow_map, Filtration_obj_map_to_fun,basic_universal_map.eval_png₀_coe, profinitely_filtered_pseudo_normed_group_with_Tinv_hom.level_coe, comp_to_fun, coe_to_add_monoid_hom], simp only [basic_universal_map.eval_png_apply, pi_map_to_fun, f.map_sum, f.map_gsmul], end } lemma eval_FP_comp (g : basic_universal_map m n) (f : basic_universal_map l m) [hg : g.suitable c₂ c₃] [hf : f.suitable c₁ c₂] [(basic_universal_map.comp g f).suitable c₁ c₃] : (basic_universal_map.comp g f).eval_FP r' c₁ c₃ = f.eval_FP r' c₁ c₂ ≫ g.eval_FP r' c₂ c₃ := by { ext, dsimp, rw eval_png_comp, refl } lemma cast_le_comp_eval_FP [fact (c₁ ≤ c₂)] [ϕ.suitable c₂ c₄] [ϕ.suitable c₁ c₃] [fact (c₃ ≤ c₄)] : cast_le r' c₁ c₂ m ≫ ϕ.eval_FP r' c₂ c₄ = ϕ.eval_FP r' c₁ c₃ ≫ cast_le r' c₃ c₄ n := by { ext, refl } open FiltrationPow lemma Tinv_comp_eval_FP (r' c₁ c₂ c₃ c₄ : ℝ≥0) [fact (c₁ ≤ r' * c₂)] [fact (c₃ ≤ r' * c₄)] [ϕ.suitable c₁ c₃] [ϕ.suitable c₂ c₄] : Tinv r' c₁ c₂ m ≫ ϕ.eval_FP r' c₂ c₄ = ϕ.eval_FP r' c₁ c₃ ≫ Tinv r' c₃ c₄ n := begin ext M x : 3, change ϕ.eval_png₀ M c₂ c₄ ((Tinv r' c₁ c₂ m).app M x) = (Tinv r' c₃ c₄ n).app M (ϕ.eval_png₀ M c₁ c₃ x), ext j, dsimp, simp only [eval_png_apply, profinitely_filtered_pseudo_normed_group_hom.map_sum, profinitely_filtered_pseudo_normed_group_hom.map_gsmul, pi_Tinv_apply], end . lemma mul_iso_eval_FP (N : ℕ) [ϕ.suitable c₂ c₁] (M) : (FiltrationPow.mul_iso.{u u} r' c₂ M N m).inv ≫ (basic_universal_map.eval_FP r' c₂ c₁ ϕ).app (ProFiltPseuNormGrpWithTinv.of r' (M ^ N)) = (basic_universal_map.eval_FP r' c₂ c₁ ((basic_universal_map.mul N) ϕ)).app M ≫ (FiltrationPow.mul_iso.{u u} r' c₁ M N n).inv := begin ext x i j, dsimp [mul], simp only [eval_png_apply, equiv.symm_apply_apply, matrix.minor_apply, matrix.kronecker], rw [← fin_prod_fin_equiv.sum_comp, ← finset.univ_product_univ, finset.sum_product, finset.sum_comm], simp only [equiv.symm_apply_apply, matrix.one_apply, boole_mul, ite_smul, zero_smul, finset.sum_ite_eq, finset.mem_univ, if_true], convert finset.sum_apply j (finset.univ : finset (fin m)) _ using 1, end end basic_universal_map end breen_deligne
e563c6a185eda141caf906588e1371ef08359e22
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Server/Utils.lean
6146ff530610b58fbe1fb6d5907737a36680e42a
[ "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
5,697
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Data.Position import Lean.Data.Lsp import Lean.Server.InfoUtils import Init.System.FilePath namespace IO def throwServerError (err : String) : IO α := throw (userError err) namespace FS.Stream /-- Chains two streams by creating a new stream s.t. writing to it just writes to `a` but reading from it also duplicates the read output into `b`, c.f. `a | tee b` on Unix. NB: if `a` is written to but this stream is never read from, the output will *not* be duplicated. Use this if you only care about the data that was actually read. -/ def chainRight (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { a with flush := a.flush *> b.flush read := fun sz => do let bs ← a.read sz b.write bs if flushEagerly then b.flush pure bs getLine := do let ln ← a.getLine b.putStr ln if flushEagerly then b.flush pure ln } /-- Like `tee a | b` on Unix. See `chainOut`. -/ def chainLeft (a : Stream) (b : Stream) (flushEagerly : Bool := false) : Stream := { b with flush := a.flush *> b.flush write := fun bs => do a.write bs if flushEagerly then a.flush b.write bs putStr := fun s => do a.putStr s if flushEagerly then a.flush b.putStr s } /-- Prefixes all written outputs with `pre`. -/ def withPrefix (a : Stream) (pre : String) : Stream := { a with write := fun bs => do a.putStr pre a.write bs putStr := fun s => a.putStr (pre ++ s) } end FS.Stream end IO namespace Lean.Server structure DocumentMeta where uri : Lsp.DocumentUri version : Nat text : FileMap deriving Inhabited def replaceLspRange (text : FileMap) (r : Lsp.Range) (newText : String) : FileMap := let start := text.lspPosToUtf8Pos r.start let «end» := text.lspPosToUtf8Pos r.«end» let pre := text.source.extract 0 start let post := text.source.extract «end» text.source.bsize (pre ++ newText ++ post).toFileMap open IO /-- Duplicates an I/O stream to a log file `fName` in LEAN_SERVER_LOG_DIR if that envvar is set. -/ def maybeTee (fName : String) (isOut : Bool) (h : FS.Stream) : IO FS.Stream := do match (← IO.getEnv "LEAN_SERVER_LOG_DIR") with | none => pure h | some logDir => let hTee ← FS.Handle.mk (System.mkFilePath [logDir, fName]) FS.Mode.write true let hTee := FS.Stream.ofHandle hTee pure $ if isOut then hTee.chainLeft h true else h.chainRight hTee true /-- Transform the given path to a file:// URI. -/ def toFileUri (fname : System.FilePath) : Lsp.DocumentUri := let fname := fname.normalize.toString let fname := if System.Platform.isWindows then fname.map fun c => if c == '\\' then '/' else c else fname -- TODO(WN): URL-encode special characters -- Three slashes denote localhost. "file:///" ++ fname.dropWhile (· == '/') open Lsp /-- Returns the document contents with all changes applied, together with the position of the change which lands earliest in the file. Panics if there are no changes. -/ def foldDocumentChanges (changes : @& Array Lsp.TextDocumentContentChangeEvent) (oldText : FileMap) : FileMap × String.Pos := if changes.isEmpty then panic! "Lean.Server.foldDocumentChanges: empty change array" else let accumulateChanges : FileMap × String.Pos → TextDocumentContentChangeEvent → FileMap × String.Pos := fun ⟨newDocText, minStartOff⟩ change => match change with | TextDocumentContentChangeEvent.rangeChange (range : Range) (newText : String) => let startOff := oldText.lspPosToUtf8Pos range.start let newDocText := replaceLspRange newDocText range newText let minStartOff := minStartOff.min startOff ⟨newDocText, minStartOff⟩ | TextDocumentContentChangeEvent.fullChange (newText : String) => ⟨newText.toFileMap, 0⟩ -- NOTE: We assume Lean files are below 16 EiB. changes.foldl accumulateChanges (oldText, 0xffffffff) def publishDiagnostics (m : DocumentMeta) (diagnostics : Array Lsp.Diagnostic) (hOut : FS.Stream) : IO Unit := hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics : PublishDiagnosticsParams } } def publishMessages (m : DocumentMeta) (msgLog : MessageLog) (hOut : FS.Stream) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) publishDiagnostics m diagnostics.toArray hOut def publishProgress (m : DocumentMeta) (processing : Array LeanFileProgressProcessingInfo) (hOut : FS.Stream) : IO Unit := hOut.writeLspNotification { method := "$/lean/fileProgress" param := { textDocument := { uri := m.uri, version? := m.version } processing : LeanFileProgressParams } } def publishProgressAtPos (m : DocumentMeta) (pos : String.Pos) (hOut : FS.Stream) : IO Unit := publishProgress m #[{ range := ⟨m.text.utf8PosToLspPos pos, m.text.utf8PosToLspPos m.text.source.bsize⟩ }] hOut def publishProgressDone (m : DocumentMeta) (hOut : FS.Stream) : IO Unit := publishProgress m #[] hOut end Lean.Server namespace List universe u def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => if p hd then hd :: takeWhile p tl else [] end List def String.Range.toLspRange (text : Lean.FileMap) (r : String.Range) : Lean.Lsp.Range := ⟨text.utf8PosToLspPos r.start, text.utf8PosToLspPos r.stop⟩
24b6d401a5b419aa3ac5706e01b51936d12980fc
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Elab/InfoTree/Main.lean
57dc8691cad2b7daebaf41c22b88828a6a478e39
[ "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
15,848
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Leonardo de Moura, Sebastian Ullrich -/ import Lean.Meta.PPGoal namespace Lean.Elab.ContextInfo variable [Monad m] [MonadEnv m] [MonadMCtx m] [MonadOptions m] [MonadResolveName m] [MonadNameGenerator m] def saveNoFileMap : m ContextInfo := return { env := (← getEnv) fileMap := default mctx := (← getMCtx) options := (← getOptions) currNamespace := (← getCurrNamespace) openDecls := (← getOpenDecls) ngen := (← getNGen) } def save [MonadFileMap m] : m ContextInfo := do let ctx ← saveNoFileMap return { ctx with fileMap := (← getFileMap) } end ContextInfo def CompletionInfo.stx : CompletionInfo → Syntax | dot i .. => i.stx | id stx .. => stx | dotId stx .. => stx | fieldId stx .. => stx | namespaceId stx => stx | option stx => stx | endSection stx .. => stx | tactic stx .. => stx def CustomInfo.format : CustomInfo → Format | i => f!"CustomInfo({i.value.typeName})" instance : ToFormat CustomInfo := ⟨CustomInfo.format⟩ partial def InfoTree.findInfo? (p : Info → Bool) (t : InfoTree) : Option Info := match t with | context _ t => findInfo? p t | node i ts => if p i then some i else ts.findSome? (findInfo? p) | _ => none /-- Instantiate the holes on the given `tree` with the assignment table. (analoguous to instantiating the metavariables in an expression) -/ partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree := match tree with | node i c => node i <| c.map (substitute · assignment) | context i t => context i (substitute t assignment) | hole id => match assignment.find? id with | none => hole id | some tree => substitute tree assignment def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do let x := x.run { lctx := lctx } { mctx := info.mctx } /- We must execute `x` using the `ngen` stored in `info`. Otherwise, we may create `MVarId`s and `FVarId`s that have been used in `lctx` and `info.mctx`. -/ let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls, fileName := "<InfoTree>", fileMap := default } { env := info.env, ngen := info.ngen } return a def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext := { env := info.env, mctx := info.mctx, lctx := lctx, opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do ppTerm (info.toPPContext lctx) ⟨stx⟩ -- HACK: might not be a term private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format := let pos := stx.getPos?.getD 0 let endPos := stx.getTailPos?.getD pos f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}" where fmtPos pos info := let pos := format <| ctx.fileMap.toPosition pos match info with | .original .. => pos | .synthetic (canonical := true) .. => f!"{pos}†!" | _ => f!"{pos}†" private def formatElabInfo (ctx : ContextInfo) (info : ElabInfo) : Format := if info.elaborator.isAnonymous then formatStxRange ctx info.stx else f!"{formatStxRange ctx info.stx} @ {info.elaborator}" def TermInfo.runMetaM (info : TermInfo) (ctx : ContextInfo) (x : MetaM α) : IO α := ctx.runMetaM info.lctx x def TermInfo.format (ctx : ContextInfo) (info : TermInfo) : IO Format := do info.runMetaM ctx do let ty : Format ← try Meta.ppExpr (← Meta.inferType info.expr) catch _ => pure "<failed-to-infer-type>" return f!"{← Meta.ppExpr info.expr} {if info.isBinder then "(isBinder := true) " else ""}: {ty} @ {formatElabInfo ctx info.toElabInfo}" def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format := match info with | .dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}" | .id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {stx} : {expectedType?} @ {formatStxRange ctx info.stx}" | _ => return f!"[.] {info.stx} @ {formatStxRange ctx info.stx}" def CommandInfo.format (ctx : ContextInfo) (info : CommandInfo) : IO Format := do return f!"command @ {formatElabInfo ctx info.toElabInfo}" def OptionInfo.format (ctx : ContextInfo) (info : OptionInfo) : IO Format := do return f!"option {info.optionName} @ {formatStxRange ctx info.stx}" def FieldInfo.format (ctx : ContextInfo) (info : FieldInfo) : IO Format := do ctx.runMetaM info.lctx do return f!"{info.fieldName} : {← Meta.ppExpr (← Meta.inferType info.val)} := {← Meta.ppExpr info.val} @ {formatStxRange ctx info.stx}" def ContextInfo.ppGoals (ctx : ContextInfo) (goals : List MVarId) : IO Format := if goals.isEmpty then return "no goals" else ctx.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM (Meta.ppGoal ·))) def TacticInfo.format (ctx : ContextInfo) (info : TacticInfo) : IO Format := do let ctxB := { ctx with mctx := info.mctxBefore } let ctxA := { ctx with mctx := info.mctxAfter } let goalsBefore ← ctxB.ppGoals info.goalsBefore let goalsAfter ← ctxA.ppGoals info.goalsAfter return f!"Tactic @ {formatElabInfo ctx info.toElabInfo}\n{info.stx}\nbefore {goalsBefore}\nafter {goalsAfter}" def MacroExpansionInfo.format (ctx : ContextInfo) (info : MacroExpansionInfo) : IO Format := do let stx ← ctx.ppSyntax info.lctx info.stx let output ← ctx.ppSyntax info.lctx info.output return f!"Macro expansion\n{stx}\n===>\n{output}" def UserWidgetInfo.format (info : UserWidgetInfo) : Format := f!"UserWidget {info.widgetId}\n{Std.ToFormat.format info.props}" def FVarAliasInfo.format (info : FVarAliasInfo) : Format := f!"FVarAlias {info.id.name} -> {info.baseId.name}" def FieldRedeclInfo.format (ctx : ContextInfo) (info : FieldRedeclInfo) : Format := f!"FieldRedecl @ {formatStxRange ctx info.stx}" def Info.format (ctx : ContextInfo) : Info → IO Format | ofTacticInfo i => i.format ctx | ofTermInfo i => i.format ctx | ofCommandInfo i => i.format ctx | ofMacroExpansionInfo i => i.format ctx | ofOptionInfo i => i.format ctx | ofFieldInfo i => i.format ctx | ofCompletionInfo i => i.format ctx | ofUserWidgetInfo i => pure <| i.format | ofCustomInfo i => pure <| Std.ToFormat.format i | ofFVarAliasInfo i => pure <| i.format | ofFieldRedeclInfo i => pure <| i.format ctx def Info.toElabInfo? : Info → Option ElabInfo | ofTacticInfo i => some i.toElabInfo | ofTermInfo i => some i.toElabInfo | ofCommandInfo i => some i.toElabInfo | ofMacroExpansionInfo _ => none | ofOptionInfo _ => none | ofFieldInfo _ => none | ofCompletionInfo _ => none | ofUserWidgetInfo _ => none | ofCustomInfo _ => none | ofFVarAliasInfo _ => none | ofFieldRedeclInfo _ => none /-- Helper function for propagating the tactic metavariable context to its children nodes. We need this function because we preserve `TacticInfo` nodes during backtracking *and* their children. Moreover, we backtrack the metavariable context to undo metavariable assignments. `TacticInfo` nodes save the metavariable context before/after the tactic application, and can be pretty printed without any extra information. This is not the case for `TermInfo` nodes. Without this function, the formatting method would often fail when processing `TermInfo` nodes that are children of `TacticInfo` nodes that have been preserved during backtracking. Saving the metavariable context at `TermInfo` nodes is also not a good option because at `TermInfo` creation time, the metavariable context often miss information, e.g., a TC problem has not been resolved, a postponed subterm has not been elaborated, etc. See `Term.SavedState.restore`. -/ def Info.updateContext? : Option ContextInfo → Info → Option ContextInfo | some ctx, ofTacticInfo i => some { ctx with mctx := i.mctxAfter } | ctx?, _ => ctx? partial def InfoTree.format (tree : InfoTree) (ctx? : Option ContextInfo := none) : IO Format := do match tree with | hole id => return .nestD f!"• ?{toString id.name}" | context i t => format t i | node i cs => match ctx? with | none => return "• <context-not-available>" | some ctx => let fmt ← i.format ctx if cs.size == 0 then return .nestD f!"• {fmt}" else let ctx? := i.updateContext? ctx? return .nestD f!"• {fmt}{Std.Format.prefixJoin .line (← cs.toList.mapM fun c => format c ctx?)}" section variable [Monad m] [MonadInfoTree m] @[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit := modifyInfoState fun s => { s with trees := f s.trees } /-- Returns the current array of InfoTrees and resets it to an empty array. -/ def getResetInfoTrees : m (PersistentArray InfoTree) := do let trees := (← getInfoState).trees modifyInfoTrees fun _ => {} return trees def pushInfoTree (t : InfoTree) : m Unit := do if (← getInfoState).enabled then modifyInfoTrees fun ts => ts.push t def pushInfoLeaf (t : Info) : m Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) t def addCompletionInfo (info : CompletionInfo) : m Unit := do pushInfoLeaf <| Info.ofCompletionInfo info def addConstInfo [MonadEnv m] [MonadError m] (stx : Syntax) (n : Name) (expectedType? : Option Expr := none) : m Unit := do pushInfoLeaf <| .ofTermInfo { elaborator := .anonymous lctx := .empty expr := (← mkConstWithLevelParams n) stx expectedType? } /-- This does the same job as `resolveGlobalConstNoOverload`; resolving an identifier syntax to a unique fully resolved name or throwing if there are ambiguities. But also adds this resolved name to the infotree. This means that when you hover over a name in the sourcefile you will see the fully resolved name in the hover info.-/ def resolveGlobalConstNoOverloadWithInfo [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m Name := do let n ← resolveGlobalConstNoOverload id if (← getInfoState).enabled then -- we do not store a specific elaborator since identifiers are special-cased by the server anyway addConstInfo id n expectedType? return n /-- Similar to `resolveGlobalConstNoOverloadWithInfo`, except if there are multiple name resolutions then it returns them as a list. -/ def resolveGlobalConstWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m (List Name) := do let ns ← resolveGlobalConst id if (← getInfoState).enabled then for n in ns do addConstInfo id n expectedType? return ns /-- Similar to `resolveGlobalName`, but it also adds the resolved name to the info tree. -/ def resolveGlobalNameWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (ref : Syntax) (id : Name) : m (List (Name × List String)) := do let ns ← resolveGlobalName id if (← getInfoState).enabled then for (n, _) in ns do addConstInfo ref n return ns /-- Use this to descend a node on the infotree that is being built. It saves the current list of trees `t₀` and resets it and then runs `x >>= mkInfo`, producing either an `i : Info` or a hole id. Running `x >>= mkInfo` will modify the trees state and produce a new list of trees `t₁`. In the `i : Info` case, `t₁` become the children of a node `node i t₁` that is appended to `t₀`. -/ def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => do match a? with | none => modifyInfoTrees fun _ => treesSaved | some a => let info ← mkInfo a modifyInfoTrees fun trees => match info with | Sum.inl info => treesSaved.push <| InfoTree.node info trees | Sum.inr mvarId => treesSaved.push <| InfoTree.hole mvarId else x /-- Saves the current list of trees `t₀`, runs `x` to produce a new tree list `t₁` and runs `mkInfoTree t₁` to get `n : InfoTree` and then restores the trees to be `t₀ ++ [n]`.-/ def withInfoTreeContext [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let tree ← mkInfoTree st.trees modifyInfoTrees fun _ => treesSaved.push tree else x /-- Run `x` as a new child infotree node with header given by `mkInfo`. -/ @[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees) /-- Resets the trees state `t₀`, runs `x` to produce a new trees state `t₁` and sets the state to be `t₀ ++ (InfoTree.context Γ <$> t₁)` where `Γ` is the context derived from the monad state. -/ def withSaveInfoContext [MonadNameGenerator m] [MonadFinally m] [MonadEnv m] [MonadOptions m] [MonadMCtx m] [MonadResolveName m] [MonadFileMap m] (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let trees ← st.trees.mapM fun tree => do let tree := tree.substitute st.assignment pure <| InfoTree.context (← ContextInfo.save) tree modifyInfoTrees fun _ => treesSaved ++ trees else x def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) := return (← getInfoState).assignment[mvarId] def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do assert! (← getInfoHoleIdAssignment? mvarId).isNone modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree } end def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (stx output : Syntax) (x : m α) : m α := let mkInfo : m Info := do return Info.ofMacroExpansionInfo { lctx := (← getLCtx) stx, output } withInfoContext x mkInfo @[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => modifyInfoState fun s => if h : s.trees.size > 0 then have : s.trees.size - 1 < s.trees.size := Nat.sub_lt h (by decide) { s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[s.trees.size - 1] } else { s with trees := treesSaved } else x def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit := modifyInfoState fun s => { s with enabled := flag } def withEnableInfoTree [Monad m] [MonadInfoTree m] [MonadFinally m] (flag : Bool) (x : m α) : m α := do let saved := (← getInfoState).enabled try enableInfoTree flag x finally enableInfoTree saved def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) := return (← getInfoState).trees end Lean.Elab
7885e4ccbbc5e47235490a8e2d33b9e9d0b6fb8d
f3849be5d845a1cb97680f0bbbe03b85518312f0
/old_library/init/instances.lean
f1903ad60fc32fc6334a014202ffc523b8d05b5a
[ "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
972
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.meta.mk_dec_eq_instance init.subtype init.meta.occurrences init.sum open tactic subtype universe variables u v attribute [instance] definition subtype_decidable_eq {A : Type u} {P : A → Prop} [decidable_eq A] : decidable_eq {x \ P x} := by mk_dec_eq_instance set_option trace.app_builder true attribute [instance] definition list_decidable_eq {A : Type u} [decidable_eq A] : decidable_eq (list A) := by mk_dec_eq_instance attribute [instance] definition occurrences_decidable_eq : decidable_eq occurrences := by mk_dec_eq_instance attribute [instance] definition unit_decidable_eq : decidable_eq unit := by mk_dec_eq_instance attribute [instance] definition sum_decidable {A : Type u} {B : Type v} [decidable_eq A] [decidable_eq B] : decidable_eq (A ⊕ B) := by mk_dec_eq_instance
1afe2c86808f896daf2d1347a39357d9f742d48c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/continuous_function/polynomial.lean
04ae3993512dace38b934e67bf78ae7ad4ba6d83
[ "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
6,237
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.algebra.polynomial import topology.continuous_function.algebra import topology.continuous_function.compact import topology.unit_interval /-! # Constructions relating polynomial functions and continuous functions. ## Main definitions * `polynomial.to_continuous_map_on p X`: for `X : set R`, interprets a polynomial `p` as a bundled continuous function in `C(X, R)`. * `polynomial.to_continuous_map_on_alg_hom`: the same, as an `R`-algebra homomorphism. * `polynomial_functions (X : set R) : subalgebra R C(X, R)`: polynomial functions as a subalgebra. * `polynomial_functions_separates_points (X : set R) : (polynomial_functions X).separates_points`: the polynomial functions separate points. -/ variables {R : Type*} open_locale polynomial namespace polynomial section variables [semiring R] [topological_space R] [topological_semiring R] /-- Every polynomial with coefficients in a topological semiring gives a (bundled) continuous function. -/ @[simps] def to_continuous_map (p : R[X]) : C(R, R) := ⟨λ x : R, p.eval x, by continuity⟩ /-- A polynomial as a continuous function, with domain restricted to some subset of the semiring of coefficients. (This is particularly useful when restricting to compact sets, e.g. `[0,1]`.) -/ @[simps] def to_continuous_map_on (p : R[X]) (X : set R) : C(X, R) := ⟨λ x : X, p.to_continuous_map x, by continuity⟩ -- TODO some lemmas about when `to_continuous_map_on` is injective? end section variables {α : Type*} [topological_space α] [comm_semiring R] [topological_space R] [topological_semiring R] @[simp] lemma aeval_continuous_map_apply (g : R[X]) (f : C(α, R)) (x : α) : ((polynomial.aeval f) g) x = g.eval (f x) := begin apply polynomial.induction_on' g, { intros p q hp hq, simp [hp, hq], }, { intros n a, simp [pi.pow_apply], }, end end section noncomputable theory variables [comm_semiring R] [topological_space R] [topological_semiring R] /-- The algebra map from `polynomial R` to continuous functions `C(R, R)`. -/ @[simps] def to_continuous_map_alg_hom : R[X] →ₐ[R] C(R, R) := { to_fun := λ p, p.to_continuous_map, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, map_one' := by { ext, simp, }, map_mul' := by { intros, ext, simp, }, commutes' := by { intros, ext, simp [algebra.algebra_map_eq_smul_one], }, } /-- The algebra map from `polynomial R` to continuous functions `C(X, R)`, for any subset `X` of `R`. -/ @[simps] def to_continuous_map_on_alg_hom (X : set R) : R[X] →ₐ[R] C(X, R) := { to_fun := λ p, p.to_continuous_map_on X, map_zero' := by { ext, simp, }, map_add' := by { intros, ext, simp, }, map_one' := by { ext, simp, }, map_mul' := by { intros, ext, simp, }, commutes' := by { intros, ext, simp [algebra.algebra_map_eq_smul_one], }, } end end polynomial section variables [comm_semiring R] [topological_space R] [topological_semiring R] /-- The subalgebra of polynomial functions in `C(X, R)`, for `X` a subset of some topological semiring `R`. -/ def polynomial_functions (X : set R) : subalgebra R C(X, R) := (⊤ : subalgebra R R[X]).map (polynomial.to_continuous_map_on_alg_hom X) @[simp] lemma polynomial_functions_coe (X : set R) : (polynomial_functions X : set C(X, R)) = set.range (polynomial.to_continuous_map_on_alg_hom X) := by { ext, simp [polynomial_functions], } -- TODO: -- if `f : R → R` is an affine equivalence, then pulling back along `f` -- induces a normed algebra isomorphism between `polynomial_functions X` and -- `polynomial_functions (f ⁻¹' X)`, intertwining the pullback along `f` of `C(R, R)` to itself. lemma polynomial_functions_separates_points (X : set R) : (polynomial_functions X).separates_points := λ x y h, begin -- We use `polynomial.X`, then clean up. refine ⟨_, ⟨⟨_, ⟨⟨polynomial.X, ⟨algebra.mem_top, rfl⟩⟩, rfl⟩⟩, _⟩⟩, dsimp, simp only [polynomial.eval_X], exact (λ h', h (subtype.ext h')), end open_locale unit_interval open continuous_map /-- The preimage of polynomials on `[0,1]` under the pullback map by `x ↦ (b-a) * x + a` is the polynomials on `[a,b]`. -/ lemma polynomial_functions.comap_comp_right_alg_hom_Icc_homeo_I (a b : ℝ) (h : a < b) : (polynomial_functions I).comap (comp_right_alg_hom ℝ (Icc_homeo_I a b h).symm.to_continuous_map) = polynomial_functions (set.Icc a b) := begin ext f, fsplit, { rintro ⟨p, ⟨-,w⟩⟩, rw fun_like.ext_iff at w, dsimp at w, let q := p.comp ((b - a)⁻¹ • polynomial.X + polynomial.C (-a * (b-a)⁻¹)), refine ⟨q, ⟨_, _⟩⟩, { simp, }, { ext x, simp only [neg_mul, ring_hom.map_neg, ring_hom.map_mul, alg_hom.coe_to_ring_hom, polynomial.eval_X, polynomial.eval_neg, polynomial.eval_C, polynomial.eval_smul, smul_eq_mul, polynomial.eval_mul, polynomial.eval_add, polynomial.coe_aeval_eq_eval, polynomial.eval_comp, polynomial.to_continuous_map_on_alg_hom_apply, polynomial.to_continuous_map_on_apply, polynomial.to_continuous_map_apply], convert w ⟨_, _⟩; clear w, { -- why does `comm_ring.add` appear here!? change x = (Icc_homeo_I a b h).symm ⟨_ + _, _⟩, ext, simp only [Icc_homeo_I_symm_apply_coe, subtype.coe_mk], replace h : b - a ≠ 0 := sub_ne_zero_of_ne h.ne.symm, simp only [mul_add], field_simp, ring, }, { change _ + _ ∈ I, rw [mul_comm (b-a)⁻¹, ←neg_mul, ←add_mul, ←sub_eq_add_neg], have w₁ : 0 < (b-a)⁻¹ := inv_pos.mpr (sub_pos.mpr h), have w₂ : 0 ≤ (x : ℝ) - a := sub_nonneg.mpr x.2.1, have w₃ : (x : ℝ) - a ≤ b - a := sub_le_sub_right x.2.2 a, fsplit, { exact mul_nonneg w₂ (le_of_lt w₁), }, { rw [←div_eq_mul_inv, div_le_one (sub_pos.mpr h)], exact w₃, }, }, }, }, { rintro ⟨p, ⟨-,rfl⟩⟩, let q := p.comp ((b - a) • polynomial.X + polynomial.C a), refine ⟨q, ⟨_, _⟩⟩, { simp, }, { ext x, simp [mul_comm], }, }, end end
6a200443a181bc4ca789ac1bf20d8a40aec580eb
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/group_theory/order_of_element.lean
486baf5c1c149029b3a2139af38b631fdf9e85d7
[ "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
39,433
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Julian Kuelshammer -/ import algebra.pointwise import group_theory.coset import dynamics.periodic_pts import algebra.iterate_hom /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n ≥ 1` such that `x ^ n = 1`. ## Main definitions * `is_of_fin_order` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `is_of_fin_add_order` is the additive analogue of `is_of_find_order`. * `order_of x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `add_order_of` is the additive analogue of `order_of`. ## Tags order of an element -/ open function nat open_locale pointwise universes u v variables {G : Type u} {A : Type v} variables {x y : G} {a b : A} {n m : ℕ} section monoid_add_monoid variables [monoid G] [add_monoid A] section is_of_fin_order lemma is_periodic_pt_add_iff_nsmul_eq_zero (a : A) : is_periodic_pt ((+) a) n 0 ↔ n • a = 0 := by rw [is_periodic_pt, is_fixed_pt, add_left_iterate, add_zero] @[to_additive is_periodic_pt_add_iff_nsmul_eq_zero] lemma is_periodic_pt_mul_iff_pow_eq_one (x : G) : is_periodic_pt ((*) x) n 1 ↔ x ^ n = 1 := by rw [is_periodic_pt, is_fixed_pt, mul_left_iterate, mul_one] /-- `is_of_fin_add_order` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n ≥ 1` such that `n • a = 0`.-/ def is_of_fin_add_order (a : A) : Prop := (0 : A) ∈ periodic_pts ((+) a) /-- `is_of_fin_order` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n ≥ 1` such that `x ^ n = 1`.-/ @[to_additive is_of_fin_add_order] def is_of_fin_order (x : G) : Prop := (1 : G) ∈ periodic_pts ((*) x) lemma is_of_fin_add_order_of_mul_iff : is_of_fin_add_order (additive.of_mul x) ↔ is_of_fin_order x := iff.rfl lemma is_of_fin_order_of_add_iff : is_of_fin_order (multiplicative.of_add a) ↔ is_of_fin_add_order a := iff.rfl lemma is_of_fin_add_order_iff_nsmul_eq_zero (a : A) : is_of_fin_add_order a ↔ ∃ n, 0 < n ∧ n • a = 0 := by { convert iff.rfl, simp only [exists_prop, is_periodic_pt_add_iff_nsmul_eq_zero] } @[to_additive is_of_fin_add_order_iff_nsmul_eq_zero] lemma is_of_fin_order_iff_pow_eq_one (x : G) : is_of_fin_order x ↔ ∃ n, 0 < n ∧ x ^ n = 1 := by { convert iff.rfl, simp [is_periodic_pt_mul_iff_pow_eq_one] } end is_of_fin_order /-- `add_order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `n • a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `add_order_of a` is `0` by convention.-/ noncomputable def add_order_of (a : A) : ℕ := minimal_period ((+) a) 0 /-- `order_of x` is the order of the element `x`, i.e. the `n ≥ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `order_of x` is `0` by convention.-/ @[to_additive add_order_of] noncomputable def order_of (x : G) : ℕ := minimal_period ((*) x) 1 attribute [to_additive add_order_of] order_of @[to_additive] lemma commute.order_of_mul_dvd_lcm (h : commute x y) : order_of (x * y) ∣ nat.lcm (order_of x) (order_of y) := begin convert function.commute.minimal_period_of_comp_dvd_lcm h.function_commute_mul_left, rw [order_of, comp_mul_left], end @[simp] lemma add_order_of_of_mul_eq_order_of (x : G) : add_order_of (additive.of_mul x) = order_of x := rfl @[simp] lemma order_of_of_add_eq_add_order_of (a : A) : order_of (multiplicative.of_add a) = add_order_of a := rfl @[to_additive add_order_of_pos'] lemma order_of_pos' (h : is_of_fin_order x) : 0 < order_of x := minimal_period_pos_of_mem_periodic_pts h lemma pow_order_of_eq_one (x : G) : x ^ order_of x = 1 := begin convert is_periodic_pt_minimal_period ((*) x) _, rw [order_of, mul_left_iterate, mul_one], end lemma add_order_of_nsmul_eq_zero (a : A) : add_order_of a • a = 0 := begin convert is_periodic_pt_minimal_period ((+) a) _, rw [add_order_of, add_left_iterate, add_zero], end attribute [to_additive add_order_of_nsmul_eq_zero] pow_order_of_eq_one @[to_additive add_order_of_eq_zero] lemma order_of_eq_zero (h : ¬ is_of_fin_order x) : order_of x = 0 := by rwa [order_of, minimal_period, dif_neg] @[to_additive add_order_of_eq_zero_iff] lemma order_of_eq_zero_iff : order_of x = 0 ↔ ¬ is_of_fin_order x := ⟨λ h H, (order_of_pos' H).ne' h, order_of_eq_zero⟩ lemma nsmul_ne_zero_of_lt_add_order_of' (n0 : n ≠ 0) (h : n < add_order_of a) : n • a ≠ 0 := λ j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_add_iff_nsmul_eq_zero a).mpr j) @[to_additive nsmul_ne_zero_of_lt_add_order_of'] lemma pow_eq_one_of_lt_order_of' (n0 : n ≠ 0) (h : n < order_of x) : x ^ n ≠ 1 := λ j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_mul_iff_pow_eq_one x).mpr j) lemma add_order_of_le_of_nsmul_eq_zero (hn : 0 < n) (h : n • a = 0) : add_order_of a ≤ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_add_iff_nsmul_eq_zero) @[to_additive add_order_of_le_of_nsmul_eq_zero] lemma order_of_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : order_of x ≤ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_mul_iff_pow_eq_one) @[simp] lemma order_of_one : order_of (1 : G) = 1 := by rw [order_of, one_mul_eq_id, minimal_period_id] @[simp] lemma add_order_of_zero : add_order_of (0 : A) = 1 := by simp only [←order_of_of_add_eq_add_order_of, order_of_one, of_add_zero] attribute [to_additive add_order_of_zero] order_of_one @[simp] lemma order_of_eq_one_iff : order_of x = 1 ↔ x = 1 := by rw [order_of, is_fixed_point_iff_minimal_period_eq_one, is_fixed_pt, mul_one] @[simp] lemma add_order_of_eq_one_iff : add_order_of a = 1 ↔ a = 0 := by simp [← order_of_of_add_eq_add_order_of] attribute [to_additive add_order_of_eq_one_iff] order_of_eq_one_iff lemma pow_eq_mod_order_of {n : ℕ} : x ^ n = x ^ (n % order_of x) := calc x ^ n = x ^ (n % order_of x + order_of x * (n / order_of x)) : by rw [nat.mod_add_div] ... = x ^ (n % order_of x) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma nsmul_eq_mod_add_order_of {n : ℕ} : n • a = (n % add_order_of a) • a := begin apply multiplicative.of_add.injective, rw [← order_of_of_add_eq_add_order_of, of_add_nsmul, of_add_nsmul, pow_eq_mod_order_of], end attribute [to_additive nsmul_eq_mod_add_order_of] pow_eq_mod_order_of lemma order_of_dvd_of_pow_eq_one (h : x ^ n = 1) : order_of x ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_mul_iff_pow_eq_one _).mpr h) lemma add_order_of_dvd_of_nsmul_eq_zero (h : n • a = 0) : add_order_of a ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr h) attribute [to_additive add_order_of_dvd_of_nsmul_eq_zero] order_of_dvd_of_pow_eq_one lemma add_order_of_dvd_iff_nsmul_eq_zero {n : ℕ} : add_order_of a ∣ n ↔ n • a = 0 := ⟨λ h, by rw [nsmul_eq_mod_add_order_of, nat.mod_eq_zero_of_dvd h, zero_nsmul], add_order_of_dvd_of_nsmul_eq_zero⟩ @[to_additive add_order_of_dvd_iff_nsmul_eq_zero] lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of x ∣ n ↔ x ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ lemma exists_pow_eq_self_of_coprime (h : n.coprime (order_of x)) : ∃ m : ℕ, (x ^ n) ^ m = x := begin by_cases h0 : order_of x = 0, { rw [h0, coprime_zero_right] at h, exact ⟨1, by rw [h, pow_one, pow_one]⟩ }, by_cases h1 : order_of x = 1, { exact ⟨0, by rw [order_of_eq_one_iff.mp h1, one_pow, one_pow]⟩ }, obtain ⟨m, hm⟩ := exists_mul_mod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩), exact ⟨m, by rw [←pow_mul, pow_eq_mod_order_of, hm, pow_one]⟩, end lemma exists_nsmul_eq_self_of_coprime (a : A) (h : coprime n (add_order_of a)) : ∃ m : ℕ, m • (n • a) = a := begin change n.coprime (order_of (multiplicative.of_add a)) at h, exact exists_pow_eq_self_of_coprime h, end attribute [to_additive exists_nsmul_eq_self_of_coprime] exists_pow_eq_self_of_coprime lemma add_order_of_eq_add_order_of_iff {B : Type*} [add_monoid B] {b : B} : add_order_of a = add_order_of b ↔ ∀ n : ℕ, n • a = 0 ↔ n • b = 0 := begin simp_rw ← add_order_of_dvd_iff_nsmul_eq_zero, exact ⟨λ h n, by rw h, λ h, nat.dvd_antisymm ((h _).mpr dvd_rfl) ((h _).mp dvd_rfl)⟩, end @[to_additive add_order_of_eq_add_order_of_iff] lemma order_of_eq_order_of_iff {H : Type*} [monoid H] {y : H} : order_of x = order_of y ↔ ∀ n : ℕ, x ^ n = 1 ↔ y ^ n = 1 := by simp_rw [← is_periodic_pt_mul_iff_pow_eq_one, ← minimal_period_eq_minimal_period_iff, order_of] lemma add_order_of_injective {B : Type*} [add_monoid B] (f : A →+ B) (hf : function.injective f) (a : A) : add_order_of (f a) = add_order_of a := by simp_rw [add_order_of_eq_add_order_of_iff, ←f.map_nsmul, ←f.map_zero, hf.eq_iff, iff_self, forall_const] @[to_additive add_order_of_injective] lemma order_of_injective {H : Type*} [monoid H] (f : G →* H) (hf : function.injective f) (x : G) : order_of (f x) = order_of x := by simp_rw [order_of_eq_order_of_iff, ←f.map_pow, ←f.map_one, hf.eq_iff, iff_self, forall_const] @[simp, norm_cast, to_additive] lemma order_of_submonoid {H : submonoid G} (y : H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive order_of_add_units] lemma order_of_units {y : units G} : order_of (y : G) = order_of y := order_of_injective (units.coe_hom G) units.ext y variables (x) lemma order_of_pow' (h : n ≠ 0) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd h, simp only [order_of, mul_left_iterate], end variables (a) lemma add_order_of_nsmul' (h : n ≠ 0) : add_order_of (n • a) = add_order_of a / gcd (add_order_of a) n := by simpa [← order_of_of_add_eq_add_order_of, of_add_nsmul] using order_of_pow' _ h attribute [to_additive add_order_of_nsmul'] order_of_pow' variable (n) lemma order_of_pow'' (h : is_of_fin_order x) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd' h, simp only [order_of, mul_left_iterate], end lemma add_order_of_nsmul'' (h : is_of_fin_add_order a) : add_order_of (n • a) = add_order_of a / gcd (add_order_of a) n := by simp [← order_of_of_add_eq_add_order_of, of_add_nsmul, order_of_pow'' _ n (is_of_fin_order_of_add_iff.mpr h)] attribute [to_additive add_order_of_nsmul''] order_of_pow'' section p_prime variables {a x n} {p : ℕ} [hp : fact p.prime] include hp lemma add_order_of_eq_prime (hg : p • a = 0) (hg1 : a ≠ 0) : add_order_of a = p := minimal_period_eq_prime ((is_periodic_pt_add_iff_nsmul_eq_zero _).mpr hg) (by rwa [is_fixed_pt, add_zero]) @[to_additive add_order_of_eq_prime] lemma order_of_eq_prime (hg : x ^ p = 1) (hg1 : x ≠ 1) : order_of x = p := minimal_period_eq_prime ((is_periodic_pt_mul_iff_pow_eq_one _).mpr hg) (by rwa [is_fixed_pt, mul_one]) lemma add_order_of_eq_prime_pow (hnot : ¬ (p ^ n) • a = 0) (hfin : (p ^ (n + 1)) • a = 0) : add_order_of a = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_add_iff_nsmul_eq_zero, end @[to_additive add_order_of_eq_prime_pow] lemma order_of_eq_prime_pow (hnot : ¬ x ^ p ^ n = 1) (hfin : x ^ p ^ (n + 1) = 1) : order_of x = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_mul_iff_pow_eq_one, end omit hp -- An example on how to determine the order of an element of a finite group. example : order_of (-1 : units ℤ) = 2 := begin haveI : fact (prime 2) := ⟨prime_two⟩, exact order_of_eq_prime (int.units_mul_self _) dec_trivial, end end p_prime end monoid_add_monoid section cancel_monoid variables [left_cancel_monoid G] (x) variables [add_left_cancel_monoid A] (a) lemma pow_injective_aux (h : n ≤ m) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : m = n + (m - n) := (nat.add_sub_of_le h).symm, have h₃ : x ^ (m - n) = 1, by { rw [h₂, pow_add] at eq, apply mul_left_cancel, convert eq.symm, exact mul_one (x ^ n) }, have le : order_of x ≤ m - n, from order_of_le_of_pow_eq_one h₁ h₃, have lt : m - n < order_of x, from (sub_lt_iff_left h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (le.trans_lt lt) -- TODO: This lemma was originally private, but this doesn't seem to work with `to_additive`, -- therefore the private got removed. lemma nsmul_injective_aux {n m : ℕ} (h : n ≤ m) (hm : m < add_order_of a) (eq : n • a = m • a) : n = m := begin apply_fun multiplicative.of_add at eq, rw [of_add_nsmul, of_add_nsmul] at eq, rw ← order_of_of_add_eq_add_order_of at hm, exact pow_injective_aux (multiplicative.of_add a) h hm eq, end attribute [to_additive nsmul_injective_aux] pow_injective_aux lemma nsmul_injective_of_lt_add_order_of {n m : ℕ} (hn : n < add_order_of a) (hm : m < add_order_of a) (eq : n • a = m • a) : n = m := (le_total n m).elim (assume h, nsmul_injective_aux a h hm eq) (assume h, (nsmul_injective_aux a h hn eq.symm).symm) @[to_additive nsmul_injective_of_lt_add_order_of] lemma pow_injective_of_lt_order_of (hn : n < order_of x) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux x h hm eq) (assume h, (pow_injective_aux x h hn eq.symm).symm) end cancel_monoid section group variables [group G] [add_group A] {x a} {i : ℤ} @[to_additive add_order_of_dvd_iff_gsmul_eq_zero] lemma order_of_dvd_iff_gpow_eq_one : (order_of x : ℤ) ∣ i ↔ x ^ i = 1 := begin rcases int.eq_coe_or_neg i with ⟨i, rfl|rfl⟩, { rw [int.coe_nat_dvd, order_of_dvd_iff_pow_eq_one, gpow_coe_nat] }, { rw [dvd_neg, int.coe_nat_dvd, gpow_neg, inv_eq_one, gpow_coe_nat, order_of_dvd_iff_pow_eq_one] } end @[simp, norm_cast, to_additive] lemma order_of_subgroup {H : subgroup G} (y: H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y lemma gpow_eq_mod_order_of : x ^ i = x ^ (i % order_of x) := calc x ^ i = x ^ (i % order_of x + order_of x * (i / order_of x)) : by rw [int.mod_add_div] ... = x ^ (i % order_of x) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma gsmul_eq_mod_add_order_of : i • a = (i % add_order_of a) • a := begin apply multiplicative.of_add.injective, simp [of_add_gsmul, gpow_eq_mod_order_of], end attribute [to_additive gsmul_eq_mod_add_order_of] gpow_eq_mod_order_of @[to_additive nsmul_inj_iff_of_add_order_of_eq_zero] lemma pow_inj_iff_of_order_of_eq_zero (h : order_of x = 0) {n m : ℕ} : x ^ n = x ^ m ↔ n = m := begin by_cases hx : x = 1, { rw [←order_of_eq_one_iff, h] at hx, contradiction }, rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one] at h, push_neg at h, induction n with n IH generalizing m, { cases m, { simp }, { simpa [eq_comm] using h m.succ m.zero_lt_succ } }, { cases m, { simpa using h n.succ n.zero_lt_succ }, { simp [pow_succ, IH] } } end lemma pow_inj_mod {n m : ℕ} : x ^ n = x ^ m ↔ n % order_of x = m % order_of x := begin cases (order_of x).zero_le.eq_or_lt with hx hx, { simp [pow_inj_iff_of_order_of_eq_zero, hx.symm] }, rw [pow_eq_mod_order_of, @pow_eq_mod_order_of _ _ _ m], exact ⟨pow_injective_of_lt_order_of _ (nat.mod_lt _ hx) (nat.mod_lt _ hx), λ h, congr_arg _ h⟩ end lemma nsmul_inj_mod {n m : ℕ} : n • a = m • a ↔ n % add_order_of a = m % add_order_of a := begin cases (add_order_of a).zero_le.eq_or_lt with hx hx, { simp [nsmul_inj_iff_of_add_order_of_eq_zero, hx.symm] }, rw [nsmul_eq_mod_add_order_of, @nsmul_eq_mod_add_order_of _ _ _ m], refine ⟨nsmul_injective_of_lt_add_order_of a (nat.mod_lt n hx) (nat.mod_lt m hx), λ h, _⟩, rw h end attribute [to_additive nsmul_inj_mod] pow_inj_mod end group section fintype variables [fintype G] [fintype A] section finite_monoid variables [monoid G] [add_monoid A] open_locale big_operators lemma sum_card_add_order_of_eq_card_nsmul_eq_zero [decidable_eq A] (hn : 0 < n) : ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ a : A, add_order_of a = m)).card = (finset.univ.filter (λ a : A, n • a = 0)).card := calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ a : A, add_order_of a = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume a, suffices : add_order_of a ≤ n ∧ add_order_of a ∣ n ↔ n • a = 0, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, mul_comm, mul_nsmul, add_order_of_nsmul_eq_zero, nsmul_zero], λ h, ⟨add_order_of_le_of_nsmul_eq_zero hn h, add_order_of_dvd_of_nsmul_eq_zero h⟩⟩ end)) @[to_additive sum_card_add_order_of_eq_card_nsmul_eq_zero] lemma sum_card_order_of_eq_card_pow_eq_one [decidable_eq G] (hn : 0 < n) : ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = (finset.univ.filter (λ x : G, x ^ n = 1)).card := calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume x, suffices : order_of x ≤ n ∧ order_of x ∣ n ↔ x ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) end finite_monoid section finite_cancel_monoid -- TODO: Of course everything also works for right_cancel_monoids. variables [left_cancel_monoid G] [add_left_cancel_monoid A] -- TODO: Use this to show that a finite left cancellative monoid is a group. lemma exists_pow_eq_one (x : G) : is_of_fin_order x := begin refine (is_of_fin_order_iff_pow_eq_one _).mpr _, obtain ⟨i, j, a_eq, ne⟩ : ∃(i j : ℕ), x ^ i = x ^ j ∧ i ≠ j := by simpa only [not_forall, exists_prop, injective] using (not_injective_infinite_fintype (λi:ℕ, x^i)), wlog h'' : j ≤ i, refine ⟨i - j, nat.sub_pos_of_lt (lt_of_le_of_ne h'' ne.symm), mul_right_injective (x^j) _⟩, rw [mul_one, ← pow_add, ← a_eq, add_sub_cancel_of_le h''], end lemma exists_nsmul_eq_zero (a : A) : is_of_fin_add_order a := begin rcases exists_pow_eq_one (multiplicative.of_add a) with ⟨i, hi1, hi2⟩, refine ⟨i, hi1, multiplicative.of_add.injective _⟩, rw [add_left_iterate, of_add_zero, of_add_eq_one, add_zero], exact (is_periodic_pt_mul_iff_pow_eq_one (multiplicative.of_add a)).mp hi2, end attribute [to_additive exists_nsmul_eq_zero] exists_pow_eq_one lemma add_order_of_le_card_univ : add_order_of a ≤ fintype.card A := finset.le_card_of_inj_on_range (• a) (assume n _, finset.mem_univ _) (assume i hi j hj, nsmul_injective_of_lt_add_order_of a hi hj) @[to_additive add_order_of_le_card_univ] lemma order_of_le_card_univ : order_of x ≤ fintype.card G := finset.le_card_of_inj_on_range ((^) x) (assume n _, finset.mem_univ _) (assume i hi j hj, pow_injective_of_lt_order_of x hi hj) /-- This is the same as `add_order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative additive monoid.-/ lemma add_order_of_pos (a : A) : 0 < add_order_of a := add_order_of_pos' (exists_nsmul_eq_zero _) /-- This is the same as `order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative monoid.-/ @[to_additive add_order_of_pos] lemma order_of_pos (x : G) : 0 < order_of x := order_of_pos' (exists_pow_eq_one x) open nat /-- This is the same as `add_order_of_nsmul'` and `add_order_of_nsmul` but with one assumption less which is automatic in the case of a finite cancellative additive monoid. -/ lemma add_order_of_nsmul (a : A) : add_order_of (n • a) = add_order_of a / gcd (add_order_of a) n := add_order_of_nsmul'' _ _ (exists_nsmul_eq_zero _) /-- This is the same as `order_of_pow'` and `order_of_pow''` but with one assumption less which is automatic in the case of a finite cancellative monoid.-/ @[to_additive add_order_of_nsmul] lemma order_of_pow (x : G) : order_of (x ^ n) = order_of x / gcd (order_of x) n := order_of_pow'' _ _ (exists_pow_eq_one _) lemma mem_multiples_iff_mem_range_add_order_of [decidable_eq A] : b ∈ add_submonoid.multiples a ↔ b ∈ (finset.range (add_order_of a)).image ((• a) : ℕ → A) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (add_order_of_pos a) (assume i, nsmul_eq_mod_add_order_of.symm) @[to_additive mem_multiples_iff_mem_range_add_order_of] lemma mem_powers_iff_mem_range_order_of [decidable_eq G] : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (order_of_pos x) (assume i, pow_eq_mod_order_of.symm) noncomputable instance decidable_multiples [decidable_eq A] : decidable_pred (∈ add_submonoid.multiples a) := begin assume b, apply decidable_of_iff' (b ∈ (finset.range (add_order_of a)).image (• a)), exact mem_multiples_iff_mem_range_add_order_of, end @[to_additive decidable_multiples] noncomputable instance decidable_powers [decidable_eq G] : decidable_pred (∈ submonoid.powers x) := begin assume y, apply decidable_of_iff' (y ∈ (finset.range (order_of x)).image ((^) x)), exact mem_powers_iff_mem_range_order_of end /-- The equivalence between `fin (order_of x)` and `submonoid.powers x`, sending `i` to `x ^ i`. -/ noncomputable def fin_equiv_powers (x : G) : fin (order_of x) ≃ (submonoid.powers x : set G) := equiv.of_bijective (λ n, ⟨x ^ ↑n, ⟨n, rfl⟩⟩) ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ij, subtype.mk_eq_mk.2 (pow_injective_of_lt_order_of x hi hj (subtype.mk_eq_mk.1 ij)), λ ⟨_, i, rfl⟩, ⟨⟨i % order_of x, mod_lt i (order_of_pos x)⟩, subtype.eq pow_eq_mod_order_of.symm⟩⟩ /-- The equivalence between `fin (add_order_of a)` and `add_submonoid.multiples a`, sending `i` to `i • a`."-/ noncomputable def fin_equiv_multiples (a : A) : fin (add_order_of a) ≃ (add_submonoid.multiples a : set A) := fin_equiv_powers (multiplicative.of_add a) attribute [to_additive fin_equiv_multiples] fin_equiv_powers @[simp] lemma fin_equiv_powers_apply {x : G} {n : fin (order_of x)} : fin_equiv_powers x n = ⟨x ^ ↑n, n, rfl⟩ := rfl @[simp] lemma fin_equiv_multiples_apply {a : A} {n : fin (add_order_of a)} : fin_equiv_multiples a n = ⟨nsmul ↑n a, n, rfl⟩ := rfl attribute [to_additive fin_equiv_multiples_apply] fin_equiv_powers_apply @[simp] lemma fin_equiv_powers_symm_apply (x : G) (n : ℕ) {hn : ∃ (m : ℕ), x ^ m = x ^ n} : ((fin_equiv_powers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by rw [equiv.symm_apply_eq, fin_equiv_powers_apply, subtype.mk_eq_mk, pow_eq_mod_order_of, fin.coe_mk] @[simp] lemma fin_equiv_multiples_symm_apply (a : A) (n : ℕ) {hn : ∃ (m : ℕ), m • a = n • a} : ((fin_equiv_multiples a).symm ⟨n • a, hn⟩) = ⟨n % add_order_of a, nat.mod_lt _ (add_order_of_pos a)⟩ := fin_equiv_powers_symm_apply (multiplicative.of_add a) n attribute [to_additive fin_equiv_multiples_symm_apply] fin_equiv_powers_symm_apply /-- The equivalence between `submonoid.powers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ noncomputable def powers_equiv_powers (h : order_of x = order_of y) : (submonoid.powers x : set G) ≃ (submonoid.powers y : set G) := (fin_equiv_powers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_powers y)) /-- The equivalence between `submonoid.multiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`. -/ noncomputable def multiples_equiv_multiples (h : add_order_of a = add_order_of b) : (add_submonoid.multiples a : set A) ≃ (add_submonoid.multiples b : set A) := (fin_equiv_multiples a).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_multiples b)) attribute [to_additive multiples_equiv_multiples] powers_equiv_powers @[simp] lemma powers_equiv_powers_apply (h : order_of x = order_of y) (n : ℕ) : powers_equiv_powers h ⟨x ^ n, n, rfl⟩ = ⟨y ^ n, n, rfl⟩ := begin rw [powers_equiv_powers, equiv.trans_apply, equiv.trans_apply, fin_equiv_powers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_powers_symm_apply], simp [h] end @[simp] lemma multiples_equiv_multiples_apply (h : add_order_of a = add_order_of b) (n : ℕ) : multiples_equiv_multiples h ⟨n • a, n, rfl⟩ = ⟨n • b, n, rfl⟩ := powers_equiv_powers_apply h n attribute [to_additive multiples_equiv_multiples_apply] powers_equiv_powers_apply lemma order_eq_card_powers [decidable_eq G] : order_of x = fintype.card (submonoid.powers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_powers x⟩) lemma add_order_of_eq_card_multiples [decidable_eq A] : add_order_of a = fintype.card (add_submonoid.multiples a : set A) := (fintype.card_fin (add_order_of a)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_multiples a⟩) attribute [to_additive add_order_of_eq_card_multiples] order_eq_card_powers end finite_cancel_monoid section finite_group variables [group G] [add_group A] lemma exists_gpow_eq_one (x : G) : ∃ (i : ℤ) (H : i ≠ 0), x ^ (i : ℤ) = 1 := --lemma exists_gpow_eq_one (a : α) : ∃ (i : ℤ) (H : i ≠ 0), a ^ (i : ℤ) = 1 := begin rcases exists_pow_eq_one x with ⟨w, hw1, hw2⟩, refine ⟨w, int.coe_nat_ne_zero.mpr (ne_of_gt hw1), _⟩, rw gpow_coe_nat, exact (is_periodic_pt_mul_iff_pow_eq_one _).mp hw2, end lemma exists_gsmul_eq_zero (a : A) : ∃ (i : ℤ) (H : i ≠ 0), i • a = 0 := @exists_gpow_eq_one (multiplicative A) _ _ a attribute [to_additive] exists_gpow_eq_one lemma mem_multiples_iff_mem_gmultiples : b ∈ add_submonoid.multiples a ↔ b ∈ add_subgroup.gmultiples a := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % add_order_of a).nat_abs, by { simp only [nsmul_eq_smul] at hi ⊢, rwa [← gsmul_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (add_order_of_pos a))), ← gsmul_eq_mod_add_order_of] } ⟩⟩ open subgroup @[to_additive mem_multiples_iff_mem_gmultiples] lemma mem_powers_iff_mem_gpowers : y ∈ submonoid.powers x ↔ y ∈ gpowers x := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of x).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos x))), ← gpow_eq_mod_order_of]⟩⟩ lemma multiples_eq_gmultiples (a : A) : (add_submonoid.multiples a : set A) = add_subgroup.gmultiples a := set.ext $ λ y, mem_multiples_iff_mem_gmultiples @[to_additive multiples_eq_gmultiples] lemma powers_eq_gpowers (x : G) : (submonoid.powers x : set G) = gpowers x := set.ext $ λ x, mem_powers_iff_mem_gpowers lemma mem_gmultiples_iff_mem_range_add_order_of [decidable_eq A] : b ∈ add_subgroup.gmultiples a ↔ b ∈ (finset.range (add_order_of a)).image (• a) := by rw [← mem_multiples_iff_mem_gmultiples, mem_multiples_iff_mem_range_add_order_of] @[to_additive mem_gmultiples_iff_mem_range_add_order_of] lemma mem_gpowers_iff_mem_range_order_of [decidable_eq G] : y ∈ subgroup.gpowers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := by rw [← mem_powers_iff_mem_gpowers, mem_powers_iff_mem_range_order_of] noncomputable instance decidable_gmultiples [decidable_eq A] : decidable_pred (∈ add_subgroup.gmultiples a) := begin simp_rw ←set_like.mem_coe, rw ← multiples_eq_gmultiples, exact decidable_multiples, end @[to_additive decidable_gmultiples] noncomputable instance decidable_gpowers [decidable_eq G] : decidable_pred (∈ subgroup.gpowers x) := begin simp_rw ←set_like.mem_coe, rw ← powers_eq_gpowers, exact decidable_powers, end /-- The equivalence between `fin (order_of x)` and `subgroup.gpowers x`, sending `i` to `x ^ i`. -/ noncomputable def fin_equiv_gpowers (x : G) : fin (order_of x) ≃ (subgroup.gpowers x : set G) := (fin_equiv_powers x).trans (equiv.set.of_eq (powers_eq_gpowers x)) /-- The equivalence between `fin (add_order_of a)` and `subgroup.gmultiples a`, sending `i` to `i • a`. -/ noncomputable def fin_equiv_gmultiples (a : A) : fin (add_order_of a) ≃ (add_subgroup.gmultiples a : set A) := fin_equiv_gpowers (multiplicative.of_add a) attribute [to_additive fin_equiv_gmultiples] fin_equiv_gpowers @[simp] lemma fin_equiv_gpowers_apply {n : fin (order_of x)} : fin_equiv_gpowers x n = ⟨x ^ (n : ℕ), n, gpow_coe_nat x n⟩ := rfl @[simp] lemma fin_equiv_gmultiples_apply {n : fin (add_order_of a)} : fin_equiv_gmultiples a n = ⟨(n : ℕ) • a, n, gsmul_coe_nat a n⟩ := fin_equiv_gpowers_apply attribute [to_additive fin_equiv_gmultiples_apply] fin_equiv_gpowers_apply @[simp] lemma fin_equiv_gpowers_symm_apply (x : G) (n : ℕ) {hn : ∃ (m : ℤ), x ^ m = x ^ n} : ((fin_equiv_gpowers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by { rw [fin_equiv_gpowers, equiv.symm_trans_apply, equiv.set.of_eq_symm_apply], exact fin_equiv_powers_symm_apply x n } @[simp] lemma fin_equiv_gmultiples_symm_apply (a : A) (n : ℕ) {hn : ∃ (m : ℤ), m • a = n • a} : ((fin_equiv_gmultiples a).symm ⟨n • a, hn⟩) = ⟨n % add_order_of a, nat.mod_lt _ (add_order_of_pos a)⟩ := fin_equiv_gpowers_symm_apply (multiplicative.of_add a) n attribute [to_additive fin_equiv_gmultiples_symm_apply] fin_equiv_gpowers_symm_apply /-- The equivalence between `subgroup.gpowers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ noncomputable def gpowers_equiv_gpowers (h : order_of x = order_of y) : (subgroup.gpowers x : set G) ≃ (subgroup.gpowers y : set G) := (fin_equiv_gpowers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_gpowers y)) /-- The equivalence between `subgroup.gmultiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`. -/ noncomputable def gmultiples_equiv_gmultiples (h : add_order_of a = add_order_of b) : (add_subgroup.gmultiples a : set A) ≃ (add_subgroup.gmultiples b : set A) := (fin_equiv_gmultiples a).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_gmultiples b)) attribute [to_additive gmultiples_equiv_gmultiples] gpowers_equiv_gpowers @[simp] lemma gpowers_equiv_gpowers_apply (h : order_of x = order_of y) (n : ℕ) : gpowers_equiv_gpowers h ⟨x ^ n, n, gpow_coe_nat x n⟩ = ⟨y ^ n, n, gpow_coe_nat y n⟩ := begin rw [gpowers_equiv_gpowers, equiv.trans_apply, equiv.trans_apply, fin_equiv_gpowers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_gpowers_symm_apply], simp [h] end @[simp] lemma gmultiples_equiv_gmultiples_apply (h : add_order_of a = add_order_of b) (n : ℕ) : gmultiples_equiv_gmultiples h ⟨n • a, n, gsmul_coe_nat a n⟩ = ⟨n • b, n, gsmul_coe_nat b n⟩ := gpowers_equiv_gpowers_apply h n attribute [to_additive gmultiples_equiv_gmultiples_apply] gpowers_equiv_gpowers_apply lemma order_eq_card_gpowers [decidable_eq G] : order_of x = fintype.card (subgroup.gpowers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_gpowers x⟩) lemma add_order_eq_card_gmultiples [decidable_eq A] : add_order_of a = fintype.card (add_subgroup.gmultiples a : set A) := (fintype.card_fin (add_order_of a)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_gmultiples a⟩) attribute [to_additive add_order_eq_card_gmultiples] order_eq_card_gpowers open quotient_group /- TODO: use cardinal theory, introduce `card : set G → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of x ∣ fintype.card G := begin classical, have ft_prod : fintype (quotient (gpowers x) × (gpowers x)), from fintype.of_equiv G group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers x), from @fintype.prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers x)), from @fintype.prod_left _ _ _ ft_prod ⟨⟨1, (gpowers x).one_mem⟩⟩, have eq₁ : fintype.card G = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card G = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of x = @fintype.card _ ft_s, from calc order_of x = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, exact dvd.intro (@fintype.card (quotient (subgroup.gpowers x)) ft_cosets) (by rw [eq₁, eq₂, mul_comm]) end lemma add_order_of_dvd_card_univ : add_order_of a ∣ fintype.card A := begin rw ← order_of_of_add_eq_add_order_of, exact order_of_dvd_card_univ, end attribute [to_additive add_order_of_dvd_card_univ] order_of_dvd_card_univ @[simp] lemma pow_card_eq_one : x ^ fintype.card G = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ x _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] @[simp] lemma card_nsmul_eq_zero {a : A} : fintype.card A • a = 0 := begin apply multiplicative.of_add.injective, rw [of_add_nsmul, of_add_zero], exact pow_card_eq_one, end @[to_additive nsmul_eq_mod_card] lemma pow_eq_mod_card (n : ℕ) : x ^ n = x ^ (n % fintype.card G) := by rw [pow_eq_mod_order_of, ←nat.mod_mod_of_dvd n order_of_dvd_card_univ, ← pow_eq_mod_order_of] @[to_additive] lemma gpow_eq_mod_card (n : ℤ) : x ^ n = x ^ (n % fintype.card G) := by rw [gpow_eq_mod_order_of, ← int.mod_mod_of_dvd n (int.coe_nat_dvd.2 order_of_dvd_card_univ), ← gpow_eq_mod_order_of] attribute [to_additive card_nsmul_eq_zero] pow_card_eq_one /-- If `gcd(|G|,n)=1` then the `n`th power map is a bijection -/ @[simps] def pow_coprime (h : nat.coprime (fintype.card G) n) : G ≃ G := { to_fun := λ g, g ^ n, inv_fun := λ g, g ^ (nat.gcd_b (fintype.card G) n), left_inv := λ g, by { have key : g ^ _ = g ^ _ := congr_arg (λ n : ℤ, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [gpow_add, gpow_mul, gpow_mul, gpow_coe_nat, gpow_coe_nat, gpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_gpow, one_mul, eq_comm] at key }, right_inv := λ g, by { have key : g ^ _ = g ^ _ := congr_arg (λ n : ℤ, g ^ n) (nat.gcd_eq_gcd_ab (fintype.card G) n), rwa [gpow_add, gpow_mul, gpow_mul', gpow_coe_nat, gpow_coe_nat, gpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one, one_gpow, one_mul, eq_comm] at key } } @[simp] lemma pow_coprime_one (h : nat.coprime (fintype.card G) n) : pow_coprime h 1 = 1 := one_pow n @[simp] lemma pow_coprime_inv (h : nat.coprime (fintype.card G) n) {g : G} : pow_coprime h g⁻¹ = (pow_coprime h g)⁻¹ := inv_pow g n lemma inf_eq_bot_of_coprime {G : Type*} [group G] {H K : subgroup G} [fintype H] [fintype K] (h : nat.coprime (fintype.card H) (fintype.card K)) : H ⊓ K = ⊥ := begin refine (H ⊓ K).eq_bot_iff_forall.mpr (λ x hx, _), rw [←order_of_eq_one_iff, ←nat.dvd_one, ←h.gcd_eq_one, nat.dvd_gcd_iff], exact ⟨(congr_arg (∣ fintype.card H) (order_of_subgroup ⟨x, hx.1⟩)).mpr order_of_dvd_card_univ, (congr_arg (∣ fintype.card K) (order_of_subgroup ⟨x, hx.2⟩)).mpr order_of_dvd_card_univ⟩, end variable (a) lemma image_range_add_order_of [decidable_eq A] : finset.image (λ i, i • a) (finset.range (add_order_of a)) = (add_subgroup.gmultiples a : set A).to_finset := by {ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_gmultiples_iff_mem_range_add_order_of] } /-- TODO: Generalise to `submonoid.powers`.-/ @[to_additive image_range_add_order_of] lemma image_range_order_of [decidable_eq G] : finset.image (λ i, x ^ i) (finset.range (order_of x)) = (gpowers x : set G).to_finset := by { ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_gpowers_iff_mem_range_order_of] } lemma gcd_nsmul_card_eq_zero_iff : n • a = 0 ↔ (gcd n (fintype.card A)) • a = 0 := ⟨λ h, gcd_nsmul_eq_zero _ h $ card_nsmul_eq_zero, λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card A) in by rw [hm, mul_comm, mul_nsmul, h, nsmul_zero]⟩ /-- TODO: Generalise to `finite_cancel_monoid`. -/ @[to_additive gcd_nsmul_card_eq_zero_iff] lemma pow_gcd_card_eq_one_iff : x ^ n = 1 ↔ x ^ (gcd n (fintype.card G)) = 1 := ⟨λ h, pow_gcd_eq_one _ h $ pow_card_eq_one, λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card G) in by rw [hm, pow_mul, h, one_pow]⟩ end finite_group end fintype section pow_is_subgroup /-- A nonempty idempotent subset of a finite cancellative monoid is a submonoid -/ def submonoid_of_idempotent {M : Type*} [left_cancel_monoid M] [fintype M] (S : set M) (hS1 : S.nonempty) (hS2 : S * S = S) : submonoid M := have pow_mem : ∀ a : M, a ∈ S → ∀ n : ℕ, a ^ (n + 1) ∈ S := λ a ha, nat.rec (by rwa [zero_add, pow_one]) (λ n ih, (congr_arg2 (∈) (pow_succ a (n + 1)).symm hS2).mp (set.mul_mem_mul ha ih)), { carrier := S, one_mem' := by { obtain ⟨a, ha⟩ := hS1, rw [←pow_order_of_eq_one a, ←nat.sub_add_cancel (order_of_pos a)], exact pow_mem a ha (order_of a - 1) }, mul_mem' := λ a b ha hb, (congr_arg2 (∈) rfl hS2).mp (set.mul_mem_mul ha hb) } /-- A nonempty idempotent subset of a finite group is a subgroup -/ def subgroup_of_idempotent {G : Type*} [group G] [fintype G] (S : set G) (hS1 : S.nonempty) (hS2 : S * S = S) : subgroup G := { carrier := S, inv_mem' := λ a ha, by { rw [←one_mul a⁻¹, ←pow_one a, ←pow_order_of_eq_one a, ←pow_sub a (order_of_pos a)], exact (submonoid_of_idempotent S hS1 hS2).pow_mem ha (order_of a - 1) }, .. submonoid_of_idempotent S hS1 hS2 } /-- If `S` is a nonempty subset of a finite group `G`, then `S ^ |G|` is a subgroup -/ def pow_card_subgroup {G : Type*} [group G] [fintype G] (S : set G) (hS : S.nonempty) : subgroup G := have one_mem : (1 : G) ∈ (S ^ fintype.card G) := by { obtain ⟨a, ha⟩ := hS, rw ← pow_card_eq_one, exact set.pow_mem_pow ha (fintype.card G) }, subgroup_of_idempotent (S ^ (fintype.card G)) ⟨1, one_mem⟩ begin classical, refine (set.eq_of_subset_of_card_le (λ b hb, (congr_arg (∈ _) (one_mul b)).mp (set.mul_mem_mul one_mem hb)) (ge_of_eq _)).symm, change _ = fintype.card (_ * _ : set G), rw [←pow_add, group.card_pow_eq_card_pow_card_univ S (fintype.card G) le_rfl, group.card_pow_eq_card_pow_card_univ S (fintype.card G + fintype.card G) le_add_self], end end pow_is_subgroup
3455d857d7613c7b82b0d85d543e269909d56e5c
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/multiset/nodup.lean
dc559e43e6c84d167d07b844894fb6211f9cf846
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,963
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.powerset import data.multiset.range /-! # The `nodup` predicate for multisets without duplicate elements. -/ namespace multiset open list variables {α β γ : Type*} /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext p.nodup_iff) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a ::ₘ s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup ({a} : multiset α) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a ::ₘ a ::ₘ 0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a ::ₘ a ::ₘ 0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm lemma nodup_iff_ne_cons_cons {s : multiset α} : s.nodup ↔ ∀ a t, s ≠ a ::ₘ a ::ₘ t := nodup_iff_le.trans ⟨λ h a t s_eq, h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))), λ h a le, let ⟨t, s_eq⟩ := le_iff_exists_add.mp le in h a t (by rwa [cons_add, cons_add, zero_add] at s_eq )⟩ theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma nodup_iff_pairwise {α} {s : multiset α} : nodup s ↔ pairwise (≠) s := quotient.induction_on s $ λ l, (pairwise_coe_iff_pairwise (by exact λ a b, ne.symm)).symm lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem inj_on_of_nodup_map {f : α → β} {s : multiset α} : nodup (map f s) → ∀ (x ∈ s) (y ∈ s), f x = f y → x = y := quot.induction_on s $ λ l, inj_on_of_nodup_map theorem nodup_map_iff_inj_on {f : α → β} {s : multiset α} (d : nodup s) : nodup (map f s) ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨inj_on_of_nodup_map, λ h, nodup_map_on h d⟩ theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le sub_le_self' h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le le_sub_add h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (nodup_ext ht (nodup_map (show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy)) (nodup_attach.2 hs))).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _) end multiset
8c61588f19de230154c1edfa4d111e28656c2b5e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/closed/cartesian.lean
3cbf0119436cf0ba9c4038807ec74c9b5cb6acfe
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,519
lean
/- Copyright (c) 2020 Bhavik Mehta, Edward Ayers, Thomas Read. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Edward Ayers, Thomas Read -/ import category_theory.limits.shapes.finite_products import category_theory.limits.preserves.shapes.binary_products import category_theory.closed.monoidal import category_theory.monoidal.of_has_finite_products import category_theory.adjunction import category_theory.adjunction.mates import category_theory.epi_mono /-! # Cartesian closed categories Given a category with finite products, the cartesian monoidal structure is provided by the local instance `monoidal_of_has_finite_products`. We define exponentiable objects to be closed objects with respect to this monoidal structure, i.e. `(X × -)` is a left adjoint. We say a category is cartesian closed if every object is exponentiable (equivalently, that the category equipped with the cartesian monoidal structure is closed monoidal). Show that exponential forms a difunctor and define the exponential comparison morphisms. ## TODO Some of the results here are true more generally for closed objects and for closed monoidal categories, and these could be generalised. -/ universes v u u₂ noncomputable theory namespace category_theory open category_theory category_theory.category category_theory.limits local attribute [instance] monoidal_of_has_finite_products /-- An object `X` is *exponentiable* if `(X × -)` is a left adjoint. We define this as being `closed` in the cartesian monoidal structure. -/ abbreviation exponentiable {C : Type u} [category.{v} C] [has_finite_products C] (X : C) := closed X /-- If `X` and `Y` are exponentiable then `X ⨯ Y` is. This isn't an instance because it's not usually how we want to construct exponentials, we'll usually prove all objects are exponential uniformly. -/ def binary_product_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] {X Y : C} (hX : exponentiable X) (hY : exponentiable Y) : exponentiable (X ⨯ Y) := { is_adj := begin haveI := hX.is_adj, haveI := hY.is_adj, exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm end } /-- The terminal object is always exponentiable. This isn't an instance because most of the time we'll prove cartesian closed for all objects at once, rather than just for this one. -/ def terminal_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] : exponentiable ⊤_C := unit_closed /-- A category `C` is cartesian closed if it has finite products and every object is exponentiable. We define this as `monoidal_closed` with respect to the cartesian monoidal structure. -/ abbreviation cartesian_closed (C : Type u) [category.{v} C] [has_finite_products C] := monoidal_closed C variables {C : Type u} [category.{v} C] (A B : C) {X X' Y Y' Z : C} section exp variables [has_finite_products C] [exponentiable A] /-- This is (-)^A. -/ def exp : C ⥤ C := (@closed.is_adj _ _ _ A _).right /-- The adjunction between A ⨯ - and (-)^A. -/ def exp.adjunction : prod.functor.obj A ⊣ exp A := closed.is_adj.adj /-- The evaluation natural transformation. -/ def ev : exp A ⋙ prod.functor.obj A ⟶ 𝟭 C := closed.is_adj.adj.counit /-- The coevaluation natural transformation. -/ def coev : 𝟭 C ⟶ prod.functor.obj A ⋙ exp A := closed.is_adj.adj.unit @[simp] lemma exp_adjunction_counit : (exp.adjunction A).counit = ev A := rfl @[simp] lemma exp_adjunction_unit : (exp.adjunction A).unit = coev A := rfl @[simp, reassoc] lemma ev_naturality {X Y : C} (f : X ⟶ Y) : limits.prod.map (𝟙 A) ((exp A).map f) ≫ (ev A).app Y = (ev A).app X ≫ f := (ev A).naturality f @[simp, reassoc] lemma coev_naturality {X Y : C} (f : X ⟶ Y) : f ≫ (coev A).app Y = (coev A).app X ≫ (exp A).map (limits.prod.map (𝟙 A) f) := (coev A).naturality f notation A ` ⟹ `:20 B:20 := (exp A).obj B notation B ` ^^ `:30 A:30 := (exp A).obj B @[simp, reassoc] lemma ev_coev : limits.prod.map (𝟙 A) ((coev A).app B) ≫ (ev A).app (A ⨯ B) = 𝟙 (A ⨯ B) := adjunction.left_triangle_components (exp.adjunction A) @[simp, reassoc] lemma coev_ev : (coev A).app (A⟹B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A⟹B) := adjunction.right_triangle_components (exp.adjunction A) instance : preserves_colimits (prod.functor.obj A) := (exp.adjunction A).left_adjoint_preserves_colimits end exp variables {A} -- Wrap these in a namespace so we don't clash with the core versions. namespace cartesian_closed variables [has_finite_products C] [exponentiable A] /-- Currying in a cartesian closed category. -/ def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) := (closed.is_adj.adj.hom_equiv _ _).to_fun /-- Uncurrying in a cartesian closed category. -/ def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) := (closed.is_adj.adj.hom_equiv _ _).inv_fun end cartesian_closed open cartesian_closed variables [has_finite_products C] [exponentiable A] @[reassoc] lemma curry_natural_left (f : X ⟶ X') (g : A ⨯ X' ⟶ Y) : curry (limits.prod.map (𝟙 _) f ≫ g) = f ≫ curry g := adjunction.hom_equiv_naturality_left _ _ _ @[reassoc] lemma curry_natural_right (f : A ⨯ X ⟶ Y) (g : Y ⟶ Y') : curry (f ≫ g) = curry f ≫ (exp _).map g := adjunction.hom_equiv_naturality_right _ _ _ @[reassoc] lemma uncurry_natural_right (f : X ⟶ A⟹Y) (g : Y ⟶ Y') : uncurry (f ≫ (exp _).map g) = uncurry f ≫ g := adjunction.hom_equiv_naturality_right_symm _ _ _ @[reassoc] lemma uncurry_natural_left (f : X ⟶ X') (g : X' ⟶ A⟹Y) : uncurry (f ≫ g) = limits.prod.map (𝟙 _) f ≫ uncurry g := adjunction.hom_equiv_naturality_left_symm _ _ _ @[simp] lemma uncurry_curry (f : A ⨯ X ⟶ Y) : uncurry (curry f) = f := (closed.is_adj.adj.hom_equiv _ _).left_inv f @[simp] lemma curry_uncurry (f : X ⟶ A⟹Y) : curry (uncurry f) = f := (closed.is_adj.adj.hom_equiv _ _).right_inv f lemma curry_eq_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) : curry f = g ↔ f = uncurry g := adjunction.hom_equiv_apply_eq _ f g lemma eq_curry_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) : g = curry f ↔ uncurry g = f := adjunction.eq_hom_equiv_apply _ f g -- I don't think these two should be simp. lemma uncurry_eq (g : Y ⟶ A ⟹ X) : uncurry g = limits.prod.map (𝟙 A) g ≫ (ev A).app X := adjunction.hom_equiv_counit _ lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (coev A).app Y ≫ (exp A).map g := adjunction.hom_equiv_unit _ lemma uncurry_id_eq_ev (A X : C) [exponentiable A] : uncurry (𝟙 (A ⟹ X)) = (ev A).app X := by rw [uncurry_eq, prod.map_id_id, id_comp] lemma curry_id_eq_coev (A X : C) [exponentiable A] : curry (𝟙 _) = (coev A).app X := by { rw [curry_eq, (exp A).map_id (A ⨯ _)], apply comp_id } lemma curry_injective : function.injective (curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X)) := (closed.is_adj.adj.hom_equiv _ _).injective lemma uncurry_injective : function.injective (uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X)) := (closed.is_adj.adj.hom_equiv _ _).symm.injective /-- Show that the exponential of the terminal object is isomorphic to itself, i.e. `X^1 ≅ X`. The typeclass argument is explicit: any instance can be used. -/ def exp_terminal_iso_self [exponentiable ⊤_C] : (⊤_C ⟹ X) ≅ X := yoneda.ext (⊤_ C ⟹ X) X (λ Y f, (prod.left_unitor Y).inv ≫ uncurry f) (λ Y f, curry ((prod.left_unitor Y).hom ≫ f)) (λ Z g, by rw [curry_eq_iff, iso.hom_inv_id_assoc] ) (λ Z g, by simp) (λ Z W f g, by rw [uncurry_natural_left, prod.left_unitor_inv_naturality_assoc f] ) /-- The internal element which points at the given morphism. -/ def internalize_hom (f : A ⟶ Y) : ⊤_C ⟶ (A ⟹ Y) := curry (limits.prod.fst ≫ f) section pre variables {B} /-- Pre-compose an internal hom with an external hom. -/ def pre (f : B ⟶ A) [exponentiable B] : exp A ⟶ exp B := transfer_nat_trans_self (exp.adjunction _) (exp.adjunction _) (prod.functor.map f) lemma prod_map_pre_app_comp_ev (f : B ⟶ A) [exponentiable B] (X : C) : limits.prod.map (𝟙 B) ((pre f).app X) ≫ (ev B).app X = limits.prod.map f (𝟙 (A ⟹ X)) ≫ (ev A).app X := transfer_nat_trans_self_counit _ _ (prod.functor.map f) X lemma uncurry_pre (f : B ⟶ A) [exponentiable B] (X : C) : uncurry ((pre f).app X) = limits.prod.map f (𝟙 _) ≫ (ev A).app X := begin rw [uncurry_eq, prod_map_pre_app_comp_ev] end lemma coev_app_comp_pre_app (f : B ⟶ A) [exponentiable B] : (coev A).app X ≫ (pre f).app (A ⨯ X) = (coev B).app X ≫ (exp B).map (limits.prod.map f (𝟙 _)) := unit_transfer_nat_trans_self _ _ (prod.functor.map f) X @[simp] lemma pre_id (A : C) [exponentiable A] : pre (𝟙 A) = 𝟙 _ := by simp [pre] @[simp] lemma pre_map {A₁ A₂ A₃ : C} [exponentiable A₁] [exponentiable A₂] [exponentiable A₃] (f : A₁ ⟶ A₂) (g : A₂ ⟶ A₃) : pre (f ≫ g) = pre g ≫ pre f := by rw [pre, pre, pre, transfer_nat_trans_self_comp, prod.functor.map_comp] end pre /-- The internal hom functor given by the cartesian closed structure. -/ def internal_hom [cartesian_closed C] : Cᵒᵖ ⥤ C ⥤ C := { obj := λ X, exp X.unop, map := λ X Y f, pre f.unop } /-- If an initial object `I` exists in a CCC, then `A ⨯ I ≅ I`. -/ @[simps] def zero_mul {I : C} (t : is_initial I) : A ⨯ I ≅ I := { hom := limits.prod.snd, inv := t.to _, hom_inv_id' := begin have: (limits.prod.snd : A ⨯ I ⟶ I) = uncurry (t.to _), rw ← curry_eq_iff, apply t.hom_ext, rw [this, ← uncurry_natural_right, ← eq_curry_iff], apply t.hom_ext, end, inv_hom_id' := t.hom_ext _ _ } /-- If an initial object `0` exists in a CCC, then `0 ⨯ A ≅ 0`. -/ def mul_zero {I : C} (t : is_initial I) : I ⨯ A ≅ I := limits.prod.braiding _ _ ≪≫ zero_mul t /-- If an initial object `0` exists in a CCC then `0^B ≅ 1` for any `B`. -/ def pow_zero {I : C} (t : is_initial I) [cartesian_closed C] : I ⟹ B ≅ ⊤_ C := { hom := default _, inv := curry ((mul_zero t).hom ≫ t.to _), hom_inv_id' := begin rw [← curry_natural_left, curry_eq_iff, ← cancel_epi (mul_zero t).inv], { apply t.hom_ext }, { apply_instance }, { apply_instance } end } -- TODO: Generalise the below to its commutated variants. -- TODO: Define a distributive category, so that zero_mul and friends can be derived from this. /-- In a CCC with binary coproducts, the distribution morphism is an isomorphism. -/ def prod_coprod_distrib [has_binary_coproducts C] [cartesian_closed C] (X Y Z : C) : (Z ⨯ X) ⨿ (Z ⨯ Y) ≅ Z ⨯ (X ⨿ Y) := { hom := coprod.desc (limits.prod.map (𝟙 _) coprod.inl) (limits.prod.map (𝟙 _) coprod.inr), inv := uncurry (coprod.desc (curry coprod.inl) (curry coprod.inr)), hom_inv_id' := begin apply coprod.hom_ext, rw [coprod.inl_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inl_desc, uncurry_curry], rw [coprod.inr_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inr_desc, uncurry_curry], end, inv_hom_id' := begin rw [← uncurry_natural_right, ←eq_curry_iff], apply coprod.hom_ext, rw [coprod.inl_desc_assoc, ←curry_natural_right, coprod.inl_desc, ←curry_natural_left, comp_id], rw [coprod.inr_desc_assoc, ←curry_natural_right, coprod.inr_desc, ←curry_natural_left, comp_id], end } /-- If an initial object `I` exists in a CCC then it is a strict initial object, i.e. any morphism to `I` is an iso. This actually shows a slightly stronger version: any morphism to an initial object from an exponentiable object is an isomorphism. -/ lemma strict_initial {I : C} (t : is_initial I) (f : A ⟶ I) : is_iso f := begin haveI : mono (limits.prod.lift (𝟙 A) f ≫ (zero_mul t).hom) := mono_comp _ _, rw [zero_mul_hom, prod.lift_snd] at _inst, haveI: split_epi f := ⟨t.to _, t.hom_ext _ _⟩, apply is_iso_of_mono_of_split_epi end instance to_initial_is_iso [has_initial C] (f : A ⟶ ⊥_ C) : is_iso f := strict_initial initial_is_initial _ /-- If an initial object `0` exists in a CCC then every morphism from it is monic. -/ lemma initial_mono {I : C} (B : C) (t : is_initial I) [cartesian_closed C] : mono (t.to B) := ⟨λ B g h _, begin haveI := strict_initial t g, haveI := strict_initial t h, exact eq_of_inv_eq_inv (t.hom_ext _ _) end⟩ instance initial.mono_to [has_initial C] (B : C) [cartesian_closed C] : mono (initial.to B) := initial_mono B initial_is_initial variables {D : Type u₂} [category.{v} D] section functor variables [has_finite_products D] /-- Transport the property of being cartesian closed across an equivalence of categories. Note we didn't require any coherence between the choice of finite products here, since we transport along the `prod_comparison` isomorphism. -/ def cartesian_closed_of_equiv (e : C ≌ D) [h : cartesian_closed C] : cartesian_closed D := { closed := λ X, { is_adj := begin haveI q : exponentiable (e.inverse.obj X) := infer_instance, have : is_left_adjoint (prod.functor.obj (e.inverse.obj X)) := q.is_adj, have : e.functor ⋙ prod.functor.obj X ⋙ e.inverse ≅ prod.functor.obj (e.inverse.obj X), apply nat_iso.of_components _ _, intro Y, { apply as_iso (prod_comparison e.inverse X (e.functor.obj Y)) ≪≫ _, apply prod.map_iso (iso.refl _) (e.unit_iso.app Y).symm }, { intros Y Z g, dsimp [prod_comparison], simp [prod.comp_lift, ← e.inverse.map_comp, ← e.inverse.map_comp_assoc], -- I wonder if it would be a good idea to make `map_comp` a simp lemma the other way round dsimp, simp -- See note [dsimp, simp] }, { have : is_left_adjoint (e.functor ⋙ prod.functor.obj X ⋙ e.inverse) := by exactI adjunction.left_adjoint_of_nat_iso this.symm, have : is_left_adjoint (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) := by exactI adjunction.left_adjoint_of_comp e.inverse _, have : (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) ⋙ e.functor ≅ prod.functor.obj X, { apply iso_whisker_right e.counit_iso (prod.functor.obj X ⋙ e.inverse ⋙ e.functor) ≪≫ _, change prod.functor.obj X ⋙ e.inverse ⋙ e.functor ≅ prod.functor.obj X, apply iso_whisker_left (prod.functor.obj X) e.counit_iso, }, resetI, apply adjunction.left_adjoint_of_nat_iso this }, end } } end functor end category_theory
ab82388b165db5101b3790a57733ffed704424ea
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/linear_algebra/basis.lean
d03edbbce8117b4549ea07c26faa5e6b6dd1e756
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,158
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, Alexander Bentkamp -/ import linear_algebra.linear_independent import linear_algebra.projection import linear_algebra.linear_pmap import data.fintype.card /-! # Bases This file defines bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. ## Tags basis, bases -/ noncomputable theory universe u open function set submodule open_locale classical big_operators variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module open linear_map variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective [nontrivial R] (hv : is_basis R v) : injective v := λ x y h, linear_independent.injective hv.1 h lemma is_basis.range (hv : is_basis R v) : is_basis R (λ x, x : range v → M) := ⟨hv.1.to_subtype_range, by { convert hv.2, ext i, exact ⟨λ ⟨p, hp⟩, hp ▸ p.2, λ hi, ⟨⟨i, hi⟩, rfl⟩⟩ }⟩ /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := linear_map.ext_on_range hv.2 h lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ left_inverse.injective hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range_eq_map, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp @[simp] lemma is_basis.repr_self_apply (i j : ι) [decidable (i = j)] : hv.repr (v i) j = if i = j then 1 else 0 := by rw [hv.repr_eq_single, finsupp.single_apply] lemma is_basis.repr_eq_iff {f : M →ₗ[R] (ι →₀ R)} : hv.repr = f ↔ ∀ i, f (v i) = finsupp.single i 1 := begin split, { rintros rfl i, exact hv.repr_eq_single }, intro h, refine hv.ext (λ _, _), rw [h, hv.repr_eq_single] end lemma is_basis.repr_apply_eq {f : M → ι → R} (hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x) (f_eq : ∀ i, f (v i) = finsupp.single i 1) (x : M) (i : ι) : hv.repr x i = f x i := begin let f_i : M →ₗ[R] R := { to_fun := λ x, f x i, map_add' := λ _ _, by rw [hadd, pi.add_apply], map_smul' := λ _ _, by rw [hsmul, pi.smul_apply] }, show (finsupp.lapply i).comp hv.repr x = f_i x, congr' 1, refine hv.ext (λ j, _), show hv.repr (v j) i = f (v j) i, rw [hv.repr_eq_single, f_eq] end lemma is_basis.range_repr_self (i : ι) : hv.range.repr (v i) = finsupp.single ⟨v i, mem_range_self i⟩ 1 := hv.1.to_subtype_range.repr_eq_single _ _ rfl @[simp] lemma is_basis.range_repr (i : ι) : hv.range.repr x ⟨v i, mem_range_self i⟩ = hv.repr x i := begin by_cases H : (0 : R) = 1, { exact eq_of_zero_eq_one H _ _ }, refine (hv.repr_apply_eq _ _ _ x i).symm, { intros x y, ext j, rw [linear_map.map_add, finsupp.add_apply], refl }, { intros c x, ext j, rw [linear_map.map_smul, finsupp.smul_apply], refl }, { intro i, ext j, haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩, simp [hv.range_repr_self, finsupp.single_apply, hv.injective.eq_iff] } end /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr] ; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] @[simp] lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ λ b, by simp lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ λ b, by simp lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm @[simp] theorem module_equiv_finsupp_apply_basis (hv : is_basis R v) (i : ι) : module_equiv_finsupp hv (v i) = finsupp.single i 1 := (linear_equiv.symm_apply_eq _).2 $ by simp [linear_independent.total_equiv] /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the indexing sets of the two bases. -/ def linear_equiv_of_is_basis {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') (e : ι ≃ ι') : M ≃ₗ[R] M' := { inv_fun := hv'.constr (v ∘ e.symm), left_inv := have (hv'.constr (v ∘ e.symm)).comp (hv.constr (v' ∘ e)) = linear_map.id, from hv.ext $ by simp, λ x, congr_arg (λ h : M →ₗ[R] M, h x) this, right_inv := have (hv.constr (v' ∘ e)).comp (hv'.constr (v ∘ e.symm)) = linear_map.id, from hv'.ext $ by simp, λ y, congr_arg (λ h : M' →ₗ[R] M', h y) this, ..hv.constr (v' ∘ e) } /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def linear_equiv_of_is_basis' {v : ι → M} {v' : ι' → M'} (f : M → M') (g : M' → M) (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } @[simp] lemma linear_equiv_of_is_basis_comp {ι'' : Type*} {v : ι → M} {v' : ι' → M'} {v'' : ι'' → M''} (hv : is_basis R v) (hv' : is_basis R v') (hv'' : is_basis R v'') (e : ι ≃ ι') (f : ι' ≃ ι'' ) : (linear_equiv_of_is_basis hv hv' e).trans (linear_equiv_of_is_basis hv' hv'' f) = linear_equiv_of_is_basis hv hv'' (e.trans f) := begin apply linear_equiv.to_linear_map_injective, apply hv.ext, intros i, simp [linear_equiv_of_is_basis] end @[simp] lemma linear_equiv_of_is_basis_refl : linear_equiv_of_is_basis hv hv (equiv.refl ι) = linear_equiv.refl R M := begin apply linear_equiv.to_linear_map_injective, apply hv.ext, intros i, simp [linear_equiv_of_is_basis] end lemma linear_equiv_of_is_basis_trans_symm (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') : (linear_equiv_of_is_basis hv hv' e).trans (linear_equiv_of_is_basis hv' hv e.symm) = linear_equiv.refl R M := by simp lemma linear_equiv_of_is_basis_symm_trans (e : ι ≃ ι') {v' : ι' → M'} (hv' : is_basis R v') : (linear_equiv_of_is_basis hv' hv e.symm).trans (linear_equiv_of_is_basis hv hv' e) = linear_equiv.refl R M' := by simp lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end @[simp] lemma is_basis.repr_eq_zero {x : M} : hv.repr x = 0 ↔ x = 0 := ⟨λ h, (hv.total_repr x).symm.trans (h.symm ▸ (finsupp.total _ _ _ _).map_zero), λ h, h.symm ▸ hv.repr.map_zero⟩ lemma is_basis.ext_elem {x y : M} (h : ∀ i, hv.repr x i = hv.repr y i) : x = y := by { rw [← hv.total_repr x, ← hv.total_repr y], congr' 1, ext i, exact h i } section include hv -- Can't be an instance because the basis can't be inferred. lemma is_basis.no_zero_smul_divisors [no_zero_divisors R] : no_zero_smul_divisors R M := ⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin rw [← hv.total_repr x, ← linear_map.map_smul] at hcx, have := linear_independent_iff.mp hv.1 (c • hv.repr x) hcx, rw smul_eq_zero at this, exact this.resolve_right (λ hr, hx (hv.repr_eq_zero.mp hr)) end)⟩ lemma is_basis.smul_eq_zero [no_zero_divisors R] {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := @smul_eq_zero _ _ _ _ _ hv.no_zero_smul_divisors _ _ end end is_basis lemma is_basis_singleton_iff {R : Type*} [ring R] [nontrivial R] [module R M] [no_zero_smul_divisors R M] (ι : Type*) [unique ι] (x : M) : is_basis R (λ (_ : ι), x) ↔ x ≠ 0 ∧ ∀ y : M, ∃ r : R, r • x = y := begin fsplit, rintro ⟨li, sp⟩, fsplit, apply linear_independent.ne_zero (default ι) li, simpa [span_singleton_eq_top_iff] using sp, rintro ⟨nz, w⟩, fsplit, simpa [linear_independent_unique_iff] using nz, simpa [span_singleton_eq_top_iff] using w, end lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l hl, _), rw [finsupp.total_unique, smul_eq_mul, mul_one] at hl, exact finsupp.unique_ext hl }, { refine top_unique (λ _ _, _), simp only [mem_span_singleton, range_const, mul_one, exists_eq, smul_eq_mul] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { simpa only using hs.1.map' (f : M →ₗ[R] M') f.ker }, { rw [set.range_comp, ← linear_equiv.coe_coe, span_image, hs.2, map_top, f.range] } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.ext_iff, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end variables (M) lemma is_basis_empty [subsingleton M] (h_empty : ¬ nonempty ι) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, subsingleton.elim _ _ ⟩ variables {M} open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def is_basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := coe_fn, map_add' := finsupp.coe_add, map_smul' := finsupp.coe_smul, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ h.equiv_fun.to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr h.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma is_basis.equiv_fun_symm_apply (x : ι → R) : h.equiv_fun.symm x = ∑ i, x i • v i := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = ∑ i, x i • v i, dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0; simp [H] end lemma is_basis.equiv_fun_apply (u : M) : h.equiv_fun u = h.repr u := rfl lemma is_basis.equiv_fun_total (u : M) : ∑ i, h.equiv_fun u i • v i = u:= begin conv_rhs { rw ← h.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, h.equiv_fun_apply] end @[simp] lemma is_basis.equiv_fun_self (i j : ι) : h.equiv_fun (v i) j = if i = j then 1 else 0 := by { rw [h.equiv_fun_apply, h.repr_self_apply] } @[simp] theorem is_basis.constr_apply_fintype (f : ι → M') (x : M) : (h.constr f : M → M') x = ∑ i, (h.equiv_fun x i) • f i := by simp [h.constr_apply, h.equiv_fun_apply, finsupp.sum_fintype] end module section vector_space variables [field K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (coe : b → V) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ lemma exists_sum_is_basis (hs : linear_independent K v) : ∃ (ι' : Type u) (v' : ι' → V), is_basis K (sum.elim v v') := begin -- This is a hack: we jump through hoops to reuse `exists_subset_is_basis`. let s := set.range v, let e : ι ≃ s := equiv.of_injective v hs.injective, have : (λ x, x : s → V) = v ∘ e.symm := by { ext, dsimp, rw [equiv.apply_of_injective_symm v] }, have : linear_independent K (λ x, x : s → V), { rw this, exact linear_independent.comp hs _ (e.symm.injective), }, obtain ⟨b, ss, is⟩ := exists_subset_is_basis this, let e' : ι ⊕ (b \ s : set V) ≃ b := calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset ss, refine ⟨(b \ s : set V), λ x, x.1, _⟩, convert is_basis.comp is e' _, { funext x, cases x; simp; refl, }, { exact e'.bijective, }, end variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i, i : b → V) := let ⟨b, _, hb⟩ := exists_subset_is_basis (linear_independent_empty K V : _) in ⟨b, hb⟩ variables {K V} lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), rwa subtype.range_coe at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hB.ext (λ b, _), rw image_subset_iff at BC, have : f b = (⟨f b, BC b.2⟩ : C) := rfl, dsimp, rw [this, constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ instance module.submodule.is_complemented : is_complemented (submodule K V) := ⟨submodule.exists_is_compl⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), refine hC.ext (λ c, _), simp [constr_basis hC, right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end /-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole space. -/ lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') : ∃ g : V →ₗ[K] V', g.comp p.subtype = f := let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩ open submodule linear_map /-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map `f : V →ₗ[K] K` such that `p ≤ ker f`. -/ lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) : ∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f := begin rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp, rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩, refine ⟨f, _, _⟩, { rintro rfl, rw [linear_map.zero_comp] at hf, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1, simpa using (linear_map.congr_fun hf _).trans this }, { refine λ x hx, mem_ker.2 _, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0, simpa using (linear_map.congr_fun hf _).trans this } end theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) open fintype variables (K) (V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := exists.elim (exists_is_basis K V) $ λ b hb, ⟨card b, module.card_fintype hb⟩ end vector_space
09a035e1358f43538ec36010203ed90fcd34de19
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/evalProp.lean
0a7c9ff17b42ba806bab6f70ff84fd4585cb0c0c
[ "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
24
lean
#eval 2 < 5 #eval 2 > 5
2f0aac218662e580c15dba323d352da171e6218c
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/types/prod.hlean
9ccf6b2fa80ac78fd738dc6826be26b8177f1a27
[ "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
1,348
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about products -/ import init.trunc init.datatypes open eq equiv is_equiv truncation prod variables {A A' B B' C D : Type} {a a' a'' : A} {b b₁ b₂ b' b'' : B} {u v w : A × B} namespace prod -- prod.eta is already used for the eta rule for strict equality protected definition peta (u : A × B) : (pr₁ u , pr₂ u) = u := destruct u (λu1 u2, idp) definition pair_path (pa : a = a') (pb : b = b') : (a , b) = (a' , b') := eq.rec_on pa (eq.rec_on pb idp) protected definition path : (pr₁ u = pr₁ v) → (pr₂ u = pr₂ v) → u = v := begin apply (prod.rec_on u), intros (a₁, b₁), apply (prod.rec_on v), intros (a₂, b₂, H₁, H₂), apply (transport _ (peta (a₁, b₁))), apply (transport _ (peta (a₂, b₂))), apply (pair_path H₁ H₂), end /- Symmetry -/ definition isequiv_flip [instance] (A B : Type) : is_equiv (@flip A B) := adjointify flip flip (λu, destruct u (λb a, idp)) (λu, destruct u (λa b, idp)) definition symm_equiv (A B : Type) : A × B ≃ B × A := equiv.mk flip _ -- trunc_prod is defined in sigma end prod
a3871713b561ac0994b3aa245bd557e35e324e36
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/goalEOF.lean
6e6b56655aeeb0c6f358bb15e08e6a8a608cf6c1
[ "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
128
lean
-- Local Variables: -- require-final-newline: nil -- End: --v $/lean/plainGoal example : False := by rfl
24f7692d2ea591e0d82487f5c803943a9b28b341
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/logic/quantifiers.lean
5fad4f62cfb1687c9488d512091f1257c4d36562
[ "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
3,016
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 Universal and existential quantifiers. See also init.logic. -/ import .connectives open inhabited nonempty theorem exists_imp_distrib {A : Type} {B : Prop} {P : A → Prop} : ((∃ a : A, P a) → B) ↔ (∀ a : A, P a → B) := iff.intro (λ e x H, e (exists.intro x H)) Exists.rec theorem forall_iff_not_exists {A : Type} {P : A → Prop} : (¬ ∃ a : A, P a) ↔ ∀ a : A, ¬ P a := exists_imp_distrib theorem not_forall_not_of_exists {A : Type} {p : A → Prop} (H : ∃ x, p x) : ¬ ∀ x, ¬ p x := assume H1 : ∀ x, ¬ p x, obtain (w : A) (Hw : p w), from H, absurd Hw (H1 w) theorem not_exists_not_of_forall {A : Type} {p : A → Prop} (H2 : ∀ x, p x) : ¬ ∃ x, ¬p x := assume H1 : ∃ x, ¬ p x, obtain (w : A) (Hw : ¬ p w), from H1, absurd (H2 w) Hw theorem not_forall_of_exists_not {A : Type} {P : A → Prop} (H : ∃ a : A, ¬ P a) : ¬ ∀ a : A, P a := assume H', not_exists_not_of_forall H' H theorem forall_true_iff_true (A : Type) : (∀ x : A, true) ↔ true := iff_true_intro (λH, trivial) theorem forall_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∀ x : A, p) ↔ p := iff.intro (inhabited.destruct H) (λ Hr x, Hr) theorem exists_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∃ x : A, p) ↔ p := iff.intro (Exists.rec (λ x Hp, Hp)) (inhabited.destruct H exists.intro) theorem forall_and_distribute {A : Type} (φ ψ : A → Prop) : (∀ x, φ x ∧ ψ x) ↔ (∀ x, φ x) ∧ (∀ x, ψ x) := iff.intro (assume H, and.intro (take x, and.left (H x)) (take x, and.right (H x))) (assume H x, and.intro (and.left H x) (and.right H x)) theorem exists_or_distribute {A : Type} (φ ψ : A → Prop) : (∃ x, φ x ∨ ψ x) ↔ (∃ x, φ x) ∨ (∃ x, ψ x) := iff.intro (Exists.rec (λ x, or.imp !exists.intro !exists.intro)) (or.rec (exists_imp_exists (λ x, or.inl)) (exists_imp_exists (λ x, or.inr))) section open decidable eq.ops variables {A : Type} (P : A → Prop) (a : A) [H : decidable (P a)] include H definition decidable_forall_eq [instance] : decidable (∀ x, x = a → P x) := if pa : P a then inl (λ x heq, eq.substr heq pa) else inr (not.mto (λH, H a rfl) pa) definition decidable_exists_eq [instance] : decidable (∃ x, x = a ∧ P x) := if pa : P a then inl (exists.intro a (and.intro rfl pa)) else inr (Exists.rec (λh, and.rec (λheq, eq.substr heq pa))) end /- definite description -/ section open classical noncomputable definition the {A : Type} {p : A → Prop} (H : ∃! x, p x) : A := some (exists_of_exists_unique H) theorem the_spec {A : Type} {p : A → Prop} (H : ∃! x, p x) : p (the H) := some_spec (exists_of_exists_unique H) theorem eq_the {A : Type} {p : A → Prop} (H : ∃! x, p x) {y : A} (Hy : p y) : y = the H := unique_of_exists_unique H Hy (the_spec H) end
40b08df45b58679fb7fad143a2428751fd5b76a0
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/order/zorn.lean
e2aef7bc5afa4bac2e93e7095da77190d4afa96e
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,462
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import data.set.lattice noncomputable theory universes u open set classical local attribute [instance] decidable_inhabited local attribute [instance] prop_decidable namespace zorn section chain parameters {α : Type u} {r : α → α → Prop} local infix ` ≺ `:50 := r def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) theorem chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) def super_chain (c₁ c₂ : set α) := chain c₂ ∧ c₁ ⊂ c₂ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') def succ_chain (c : set α) := if h : ∃c', chain c ∧ super_chain c c' then some h else c theorem succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] theorem chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc theorem super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂, cases hc₂.neg_resolve_left hc₁ with c' hc', exact succ_spec ⟨c', hc₁, hc'⟩ end theorem succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) theorem chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption theorem chain_closure_closure : chain_closure (⋃₀ chain_closure) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case _root_.zorn.chain_closure.succ c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case _root_.zorn.chain_closure.union s hs ih { refine (or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case _root_.zorn.chain_closure.succ c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case _root_.zorn.chain_closure.union s hs ih { apply or.imp_left (assume h', subset.antisymm h' h), apply classical.by_contradiction, simp [not_or_distrib, sUnion_subset_iff, classical.not_forall], intros h₁ c₃ h₂ hc₃, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₂ $ h' ▸ subset.refl _) }, { exact (h₁ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₂ $ subset.trans succ_increasing h) } } end theorem chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this theorem chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case _root_.zorn.chain_closure.succ c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case _root_.zorn.chain_closure.union s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end theorem chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ theorem chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case _root_.zorn.chain_closure.succ c hc h { exact chain_succ h }, case _root_.zorn.chain_closure.union s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ chain_closure), have super_chain (⋃₀ chain_closure) (succ_chain (⋃₀ chain_closure)), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, h₂, (h₃ : (⋃₀ chain_closure) ≠ succ_chain (⋃₀ chain_closure))⟩ := this in have succ_chain (⋃₀ chain_closure) = (⋃₀ chain_closure), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ theorem zorn (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @zorn α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ end zorn
fbc37ef53acb0c39d4c5792e7657f71cf09707fc
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/equiv/set.lean
a9b1673d3a509a646f3cb89b614b9b55d6abcabb
[ "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
23,228
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.equiv.basic import data.set.function /-! # Equivalences and sets In this file we provide lemmas linking equivalences to sets. Some notable definitions are: * `equiv.of_injective`: an injective function is (noncomputably) equivalent to its range. * `equiv.set_congr`: two equal sets are equivalent as types. * `equiv.set.union`: a disjoint union of sets is equivalent to their `sum`. This file is separate from `equiv/basic` such that we do not require the full lattice structure on sets before defining what an equivalence is. -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} namespace equiv @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv lemma _root_.set.mem_image_equiv {α β} {S : set α} {f : α ≃ β} {x : β} : x ∈ f '' S ↔ f.symm x ∈ S := set.ext_iff.mp (f.image_eq_preimage S) x /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.image_equiv_eq_preimage_symm {α β} (S : set α) (f : α ≃ β) : f '' S = f.symm ⁻¹' S := f.image_eq_preimage S /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.preimage_equiv_eq_image_symm {α β} (S : set α) (f : β ≃ α) : f ⁻¹' S = f.symm '' S := (f.symm.image_eq_preimage S).symm @[simp] protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : e.symm '' t ⊆ s ↔ t ⊆ e '' s := by rw [set.image_subset_iff, e.image_eq_preimage] @[simp] protected lemma subset_image' {α β} (e : α ≃ β) (s : set α) (t : set β) : s ⊆ e.symm '' t ↔ e '' s ⊆ t := calc s ⊆ e.symm '' t ↔ e.symm.symm '' s ⊆ t : by rw e.symm.subset_image ... ↔ e '' s ⊆ t : by rw e.symm_symm @[simp] lemma symm_image_image {α β} (e : α ≃ β) (s : set α) : e.symm '' (e '' s) = s := e.left_inverse_symm.image_image s lemma eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : set α) (t : set β) : t = e '' s ↔ e.symm '' t = s := (e.symm.injective.image_injective.eq_iff' (e.symm_image_image s)).symm @[simp] lemma image_symm_image {α β} (e : α ≃ β) (s : set β) : e '' (e.symm '' s) = s := e.symm.symm_image_image s @[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s := e.injective.preimage_image s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' sᶜ = (f '' s)ᶜ := set.image_compl_eq f.bijective @[simp] lemma symm_preimage_preimage {α β} (e : α ≃ β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.right_inverse_symm.preimage_preimage s @[simp] lemma preimage_symm_preimage {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.left_inverse_symm.preimage_preimage s @[simp] lemma preimage_subset {α β} (e : α ≃ β) (s t : set β) : e ⁻¹' s ⊆ e ⁻¹' t ↔ s ⊆ t := e.surjective.preimage_subset_preimage_iff @[simp] lemma image_subset {α β} (e : α ≃ β) (s t : set α) : e '' s ⊆ e '' t ↔ s ⊆ t := set.image_subset_image_iff e.injective @[simp] lemma image_eq_iff_eq {α β} (e : α ≃ β) (s t : set α) : e '' s = e '' t ↔ s = t := set.image_eq_image e.injective lemma preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t := set.preimage_eq_iff_eq_image e.bijective lemma eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t := set.eq_preimage_iff_image_eq e.bijective lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ ⁻¹' (s ×ˢ (t ×ˢ u)) = (s ×ˢ t) ×ˢ u := by { ext, simp [and_assoc] } /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) : s ≃ Σ x : α, {y | (x, y) ∈ s} := { to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩, inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩, left_inv := λ ⟨⟨x, y⟩, h⟩, rfl, right_inv := λ ⟨x, y, h⟩, rfl } /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps apply] def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_equiv_prop h /-- A set is equivalent to its image under an equivalence. -/ -- We could construct this using `equiv.set.image e s e.injective`, -- but this definition provides an explicit inverse. @[simps] def image {α β : Type*} (e : α ≃ β) (s : set α) : s ≃ e '' s := { to_fun := λ x, ⟨e x.1, by simp⟩, inv_fun := λ y, ⟨e.symm y.1, by { rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩, simpa using m, }⟩, left_inv := λ x, by simp, right_inv := λ y, by simp, }. open set namespace set /-- `univ α` is equivalent to `α`. -/ @[simps apply symm_apply] protected def univ (α) : @univ α ≃ α := ⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ /-- An empty set is equivalent to the `empty` type. -/ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty _ /-- An empty set is equivalent to a `pempty` type. -/ protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty _ /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x, or.inl x.2⟩ | (sum.inr x) := ⟨x, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg $ λ h, H ⟨h, ha⟩ @[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ := rfl @[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ := rfl /-- A singleton set is equivalent to a `punit` type. -/ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ /-- Equal sets are equivalent. -/ @[simps apply symm_apply] protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/ protected def insert {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (λ x ⟨hx, hx'⟩, by simp [*] at *) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) @[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ := rfl @[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ := rfl @[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sum_compl {α} (s : set α) [decidable_pred (∈ s)] : s ⊕ (sᶜ : set α) ≃ α := calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : sᶜ) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } @[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : s} : (equiv.set.sum_compl s).symm x = sum.inl x := by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx @[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x := by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx /-- `sum_diff_subset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] : s ⊕ (t \ s : set α) ≃ t := calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) : (equiv.set.union (by simp [inter_diff_self])).symm ... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] }) @[simp] lemma sum_diff_subset_apply_inl {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl @[simp] lemma sum_diff_subset_apply_inr {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : t \ s) : equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl lemma sum_diff_subset_symm_apply_of_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∈ s) : (equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inl], exact subtype.eq rfl, end lemma sum_diff_subset_symm_apply_of_not_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∉ s) : (equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inr], exact subtype.eq rfl, end /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred (∈ s)] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred (∈ s)] [decidable_pred (∈ t)] (e₀ : s ≃ t) : {e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) := { to_fun := λ e, subtype_equiv e (λ a, not_congr $ iff.symm $ maps_to.mem_iff (maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2 ⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)), inv_fun := λ e₁, subtype.mk (calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm ... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁ ... ≃ β : set.sum_compl t) (λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply, set.sum_compl_apply_inl, set.sum_compl_symm_apply]), left_inv := λ e, begin ext x, by_cases hx : x ∈ s, { simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩, sum.map_inl, sum_congr_apply, trans_apply, subtype.coe_mk, set.sum_compl_apply_inl] }, { simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, trans_apply, sum_congr_apply, subtype.coe_mk] }, end, right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans, subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] } /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : set α) (t : set β) : ↥(s ×ˢ t) ≃ s × t := @subtype_prod_equiv_prod α β s t /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps apply] protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (H.inj_on s) @[simp] protected lemma image_symm_apply {α β} (f : α → β) (s : set α) (H : injective f) (x : α) (h : x ∈ s) : (set.image f s H).symm ⟨f x, ⟨x, ⟨h, rfl⟩⟩⟩ = ⟨x, h⟩ := begin apply (set.image f s H).injective, simp [(set.image f s H).apply_symm_apply], end lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) : (λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) := begin ext ⟨b, a, has, rfl⟩, have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2, simp [equiv.set.image, equiv.set.image_of_inj_on, hf.eq_iff, this], end /-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/ @[simps] protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/ protected def powerset {α} (S : set α) : 𝒫 S ≃ set S := { to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α), inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩, left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩, right_inv := λ x, by ext; simp } /-- If `s` is a set in `range f`, then its image under `range_splitting f` is in bijection (via `f`) with `s`. -/ @[simps] noncomputable def range_splitting_image_equiv {α β : Type*} (f : α → β) (s : set (range f)) : range_splitting f '' s ≃ s := { to_fun := λ x, ⟨⟨f x, by simp⟩, (by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simpa [apply_range_splitting f] using m, })⟩, inv_fun := λ x, ⟨range_splitting f x, ⟨x, ⟨x.2, rfl⟩⟩⟩, left_inv := λ x, by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simp [apply_range_splitting f] }, right_inv := λ x, by simp [apply_range_splitting f], } end set /-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the range of `f`. While awkward, the `nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is empty too. This hypothesis is absent on analogous definitions on stronger `equiv`s like `linear_equiv.of_left_inverse` and `ring_equiv.of_left_inverse` as their typeclass assumptions are already sufficient to ensure non-emptiness. -/ @[simps] def of_left_inverse {α β : Sort*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : α ≃ set.range f := { to_fun := λ a, ⟨f a, a, rfl⟩, inv_fun := λ b, f_inv (nonempty_of_exists b.2) b, left_inv := λ a, hf ⟨a⟩ a, right_inv := λ ⟨b, a, ha⟩, subtype.eq $ show f (f_inv ⟨a⟩ b) = b, from eq.trans (congr_arg f $ by exact ha ▸ (hf _ a)) ha } /-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`. Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike the stronger but less convenient `of_left_inverse`. -/ abbreviation of_left_inverse' {α β : Sort*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : α ≃ set.range f := of_left_inverse f (λ _, f_inv) (λ _, hf) /-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/ @[simps apply] noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ set.range f := equiv.of_left_inverse f (λ h, by exactI function.inv_fun f) (λ h, by exactI function.left_inverse_inv_fun hf) theorem apply_of_injective_symm {α β} {f : α → β} (hf : injective f) (b : set.range f) : f ((of_injective f hf).symm b) = b := subtype.ext_iff.1 $ (of_injective f hf).apply_symm_apply b @[simp] theorem of_injective_symm_apply {α β} {f : α → β} (hf : injective f) (a : α) : (of_injective f hf).symm ⟨f a, ⟨a, rfl⟩⟩ = a := begin apply (of_injective f hf).injective, simp [apply_of_injective_symm hf], end lemma coe_of_injective_symm {α β} {f : α → β} (hf : injective f) : ((of_injective f hf).symm : range f → α) = range_splitting f := by { ext ⟨y, x, rfl⟩, apply hf, simp [apply_range_splitting f] } @[simp] lemma self_comp_of_injective_symm {α β} {f : α → β} (hf : injective f) : f ∘ ((of_injective f hf).symm) = coe := funext (λ x, apply_of_injective_symm hf x) lemma of_left_inverse_eq_of_injective {α β : Type*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : of_left_inverse f f_inv hf = of_injective f ((em (nonempty α)).elim (λ h, (hf h).injective) (λ h _ _ _, by { haveI : subsingleton α := subsingleton_of_not_nonempty h, simp })) := by { ext, simp } lemma of_left_inverse'_eq_of_injective {α β : Type*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : of_left_inverse' f f_inv hf = of_injective f hf.injective := by { ext, simp } protected lemma set_forall_iff {α β} (e : α ≃ β) {p : set α → Prop} : (∀ a, p a) ↔ (∀ a, p (e ⁻¹' a)) := by simpa [equiv.image_eq_preimage] using (equiv.set.congr e).forall_congr_left' protected lemma preimage_sUnion {α β} (f : α ≃ β) {s : set (set β)} : f ⁻¹' (⋃₀ s) = ⋃₀ (_root_.set.image f ⁻¹' s) := by { ext x, simp [(equiv.set.congr f).symm.exists_congr_left] } end equiv /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the types `↥s` and `↥t`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β) (h : set.bij_on f s t) : s ≃ t := equiv.of_bijective _ h.bijective /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { rw [dif_pos h, function.update_apply_equiv_apply, equiv.symm_symm, function.comp, function.update_apply, function.update_apply, dif_pos h], have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk), simp_rw h_coe }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
c96de0633cabf9b39866448e7c0298a3a7c4d5f4
0ed3609caf1962115b28aeb010d2bda5f67ddc4c
/src/data/fintype.lean
000e1345d6505705f38503752042f862c4e33fd1
[ "Apache-2.0" ]
permissive
jonaslippert/mathlib
82dba29632969e3ed1c153a6454306f6bc9d9037
1435a196db69a7886a11e310e8923f3dcf249b81
refs/heads/master
1,609,938,673,069
1,582,018,388,000
1,582,018,388,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,282
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = (finset.univ : finset α).sum (λ _, 1) := finset.card_eq_sum_ones _ end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end theorem fin.prod_univ_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.prod f = f 0 * univ.prod (λ i:fin n, f i.succ) := begin rw [fin.univ_succ, prod_insert, prod_image], { intros x _ y _ hxy, exact fin.succ.inj hxy }, { simpa using fin.succ_ne_zero } end @[simp, to_additive] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : univ.prod f = 1 := rfl theorem fin.sum_univ_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.sum f = f 0 + univ.sum (λ i:fin n, f i.succ) := by apply @fin.prod_univ_succ (multiplicative β) attribute [to_additive] fin.prod_univ_succ lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end theorem fin.prod_univ_cast_succ [comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.prod f = univ.prod (λ i:fin n, f i.cast_succ) * f (fin.last n) := begin rw [fin.univ_cast_succ, prod_insert, prod_image, mul_comm], { intros x _ y _ hxy, exact fin.cast_succ_inj.mp hxy }, { simpa using fin.cast_succ_ne_last } end theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n:ℕ} (f : fin n.succ → β) : univ.sum f = univ.sum (λ i:fin n, f i.cast_succ) + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [∀ a, fintype (β a)] [decidable α] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [fintype α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) @[to_additive] lemma finset.range_prod_eq_univ_prod [comm_monoid β] (n : ℕ) (f : ℕ → β) : (range n).prod f = univ.prod (λ (k : fin n), f k) := begin symmetry, refine prod_bij (λ k hk, k) _ _ _ _, { rintro ⟨k, hk⟩ _, simp * }, { rintro ⟨k, hk⟩ _, simp * }, { intros, rwa fin.eq_iff_veq }, { intros k hk, rw mem_range at hk, exact ⟨⟨k, hk⟩, mem_univ _, rfl⟩ } end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] 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.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) 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; cc) 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 nodup_of_nodup_cons hl, 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', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ 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])⟩ 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.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) 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.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l 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.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.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 α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = finset.singleton x := begin apply symm, apply eq_of_subset_of_card_le (subset_univ (finset.singleton x)), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
e674732142876b59908d3ce7b8895dc5c0c6fe33
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/sym/sym2.lean
bd9d2a62f46f52b67d6ca4c3ef76787dc15964a3
[ "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
19,259
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.sym.basic import tactic.linarith /-! # The symmetric square This file defines the symmetric square, which is `α × α` modulo swapping. This is also known as the type of unordered pairs. More generally, the symmetric square is the second symmetric power (see `data.sym.basic`). The equivalence is `sym2.equiv_sym`. From the point of view that an unordered pair is equivalent to a multiset of cardinality two (see `sym2.equiv_multiset`), there is a `has_mem` instance `sym2.mem`, which is a `Prop`-valued membership test. Given `h : a ∈ z` for `z : sym2 α`, then `h.other` is the other element of the pair, defined using `classical.choice`. If `α` has decidable equality, then `h.other'` computably gives the other element. The universal property of `sym2` is provided as `sym2.lift`, which states that functions from `sym2 α` are equivalent to symmetric two-argument functions from `α`. Recall that an undirected graph (allowing self loops, but no multiple edges) is equivalent to a symmetric relation on the vertex type `α`. Given a symmetric relation on `α`, the corresponding edge set is constructed by `sym2.from_rel` which is a special case of `sym2.lift`. ## Notation The symmetric square has a setoid instance, so `⟦(a, b)⟧` denotes a term of the symmetric square. ## Tags symmetric square, unordered pairs, symmetric powers -/ open finset fintype function sym universe u variables {α β γ : Type*} namespace sym2 /-- This is the relation capturing the notion of pairs equivalent up to permutations. -/ inductive rel (α : Type u) : (α × α) → (α × α) → Prop | refl (x y : α) : rel (x, y) (x, y) | swap (x y : α) : rel (x, y) (y, x) attribute [refl] rel.refl @[symm] lemma rel.symm {x y : α × α} : rel α x y → rel α y x := by rintro ⟨_, _⟩; constructor @[trans] lemma rel.trans {x y z : α × α} : rel α x y → rel α y z → rel α x z := by { intros a b, cases_matching* rel _ _ _; apply rel.refl <|> apply rel.swap } lemma rel.is_equivalence : equivalence (rel α) := by tidy; apply rel.trans; assumption instance rel.setoid (α : Type u) : setoid (α × α) := ⟨rel α, rel.is_equivalence⟩ end sym2 /-- `sym2 α` is the symmetric square of `α`, which, in other words, is the type of unordered pairs. It is equivalent in a natural way to multisets of cardinality 2 (see `sym2.equiv_multiset`). -/ @[reducible] def sym2 (α : Type u) := quotient (sym2.rel.setoid α) namespace sym2 @[elab_as_eliminator] protected lemma ind {f : sym2 α → Prop} (h : ∀ x y, f ⟦(x, y)⟧) : ∀ i, f i := quotient.ind $ prod.rec $ by exact h @[elab_as_eliminator] protected lemma induction_on {f : sym2 α → Prop} (i : sym2 α) (hf : ∀ x y, f ⟦(x,y)⟧) : f i := i.ind hf protected lemma «exists» {α : Sort*} {f : sym2 α → Prop} : (∃ (x : sym2 α), f x) ↔ ∃ x y, f ⟦(x, y)⟧ := (surjective_quotient_mk _).exists.trans prod.exists protected lemma «forall» {α : Sort*} {f : sym2 α → Prop} : (∀ (x : sym2 α), f x) ↔ ∀ x y, f ⟦(x, y)⟧ := (surjective_quotient_mk _).forall.trans prod.forall lemma eq_swap {a b : α} : ⟦(a, b)⟧ = ⟦(b, a)⟧ := by { rw quotient.eq, apply rel.swap } lemma congr_right {a b c : α} : ⟦(a, b)⟧ = ⟦(a, c)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } lemma congr_left {a b c : α} : ⟦(b, a)⟧ = ⟦(c, a)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } lemma eq_iff {x y z w : α} : ⟦(x, y)⟧ = ⟦(z, w)⟧ ↔ (x = z ∧ y = w) ∨ (x = w ∧ y = z) := begin split; intro h, { rw quotient.eq at h, cases h; tidy }, { cases h; rw [h.1, h.2], rw eq_swap } end /-- The universal property of `sym2`; symmetric functions of two arguments are equivalent to functions from `sym2`. Note that when `β` is `Prop`, it can sometimes be more convenient to use `sym2.from_rel` instead. -/ def lift : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁} ≃ (sym2 α → β) := { to_fun := λ f, quotient.lift (uncurry ↑f) $ by { rintro _ _ ⟨⟩, exacts [rfl, f.prop _ _] }, inv_fun := λ F, ⟨curry (F ∘ quotient.mk), λ a₁ a₂, congr_arg F eq_swap⟩, left_inv := λ f, subtype.ext rfl, right_inv := λ F, funext $ sym2.ind $ by exact λ x y, rfl } @[simp] lemma lift_mk (f : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁}) (a₁ a₂ : α) : lift f ⟦(a₁, a₂)⟧ = (f : α → α → β) a₁ a₂ := rfl @[simp] lemma coe_lift_symm_apply (F : sym2 α → β) (a₁ a₂ : α) : (lift.symm F : α → α → β) a₁ a₂ = F ⟦(a₁, a₂)⟧ := rfl /-- The functor `sym2` is functorial, and this function constructs the induced maps. -/ def map (f : α → β) : sym2 α → sym2 β := quotient.map (prod.map f f) (by { rintros _ _ h, cases h, { refl }, apply rel.swap }) @[simp] lemma map_id : sym2.map (@id α) = id := by tidy lemma map_comp {g : β → γ} {f : α → β} : sym2.map (g ∘ f) = sym2.map g ∘ sym2.map f := by tidy lemma map_map {g : β → γ} {f : α → β} (x : sym2 α) : map g (map f x) = map (g ∘ f) x := by tidy @[simp] lemma map_pair_eq (f : α → β) (x y : α) : map f ⟦(x, y)⟧ = ⟦(f x, f y)⟧ := rfl lemma map.injective {f : α → β} (hinj : injective f) : injective (map f) := begin intros z z', refine quotient.ind₂ (λ z z', _) z z', cases z with x y, cases z' with x' y', repeat { rw [map_pair_eq, eq_iff] }, rintro (h|h); simp [hinj h.1, hinj h.2], end section membership /-! ### Declarations about membership -/ /-- This is a predicate that determines whether a given term is a member of a term of the symmetric square. From this point of view, the symmetric square is the subtype of cardinality-two multisets on `α`. -/ def mem (x : α) (z : sym2 α) : Prop := ∃ (y : α), z = ⟦(x, y)⟧ instance : has_mem α (sym2 α) := ⟨mem⟩ lemma mem_mk_left (x y : α) : x ∈ ⟦(x, y)⟧ := ⟨y, rfl⟩ lemma mem_mk_right (x y : α) : y ∈ ⟦(x, y)⟧ := eq_swap.subst $ mem_mk_left y x @[simp] lemma mem_iff {a b c : α} : a ∈ ⟦(b, c)⟧ ↔ a = b ∨ a = c := { mp := by { rintro ⟨_, h⟩, rw eq_iff at h, tidy }, mpr := by { rintro ⟨_⟩; subst a, { apply mem_mk_left }, apply mem_mk_right } } lemma out_fst_mem (e : sym2 α) : e.out.1 ∈ e := ⟨e.out.2, by rw [prod.mk.eta, e.out_eq]⟩ lemma out_snd_mem (e : sym2 α) : e.out.2 ∈ e := ⟨e.out.1, by rw [eq_swap, prod.mk.eta, e.out_eq]⟩ lemma ball {p : α → Prop} {a b : α} : (∀ c ∈ ⟦(a, b)⟧, p c) ↔ p a ∧ p b := begin refine ⟨λ h, ⟨h _ $ mem_mk_left _ _, h _ $ mem_mk_right _ _⟩, λ h c hc, _⟩, obtain rfl | rfl := sym2.mem_iff.1 hc, { exact h.1 }, { exact h.2 } end /-- Given an element of the unordered pair, give the other element using `classical.some`. See also `mem.other'` for the computable version. -/ noncomputable def mem.other {a : α} {z : sym2 α} (h : a ∈ z) : α := classical.some h @[simp] lemma other_spec {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other)⟧ = z := by erw ← classical.some_spec h lemma other_mem {a : α} {z : sym2 α} (h : a ∈ z) : h.other ∈ z := by { convert mem_mk_right a h.other, rw other_spec h } lemma mem_and_mem_iff {x y : α} {z : sym2 α} (hne : x ≠ y) : x ∈ z ∧ y ∈ z ↔ z = ⟦(x, y)⟧ := begin refine ⟨quotient.rec_on_subsingleton z _, _⟩, { rintro ⟨z₁, z₂⟩ ⟨hx, hy⟩, rw eq_iff, cases mem_iff.mp hx with hx hx; cases mem_iff.mp hy with hy hy; subst x; subst y; try { exact (hne rfl).elim }; simp only [true_or, eq_self_iff_true, and_self, or_true] }, { rintro rfl, simp }, end lemma eq_of_ne_mem {x y : α} {z z' : sym2 α} (h : x ≠ y) (h1 : x ∈ z) (h2 : y ∈ z) (h3 : x ∈ z') (h4 : y ∈ z') : z = z' := ((mem_and_mem_iff h).mp ⟨h1, h2⟩).trans ((mem_and_mem_iff h).mp ⟨h3, h4⟩).symm @[ext] protected lemma ext (z z' : sym2 α) (h : ∀ x, x ∈ z ↔ x ∈ z') : z = z' := begin refine quotient.rec_on_subsingleton z (λ w, _) h, refine quotient.rec_on_subsingleton z' (λ w', _), intro h, cases w with x y, cases w' with x' y', simp only [mem_iff] at h, apply eq_iff.mpr, have hx := h x, have hy := h y, have hx' := h x', have hy' := h y', simp only [true_iff, true_or, eq_self_iff_true, iff_true, or_true] at hx hy hx' hy', cases hx; subst x; cases hy; subst y; cases hx'; try { subst x' }; cases hy'; try { subst y' }; simp only [eq_self_iff_true, and_self, or_self, true_or, or_true], end instance mem.decidable [decidable_eq α] (x : α) (z : sym2 α) : decidable (x ∈ z) := quotient.rec_on_subsingleton z (λ ⟨y₁, y₂⟩, decidable_of_iff' _ mem_iff) end membership /-- A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image of this diagonal in `sym2 α`. -/ def diag (x : α) : sym2 α := ⟦(x, x)⟧ lemma diag_injective : function.injective (sym2.diag : α → sym2 α) := λ x y h, by cases quotient.exact h; refl /-- A predicate for testing whether an element of `sym2 α` is on the diagonal. -/ def is_diag : sym2 α → Prop := lift ⟨eq, λ _ _, propext eq_comm⟩ lemma mk_is_diag_iff {x y : α} : is_diag ⟦(x, y)⟧ ↔ x = y := iff.rfl @[simp] lemma is_diag_iff_proj_eq (z : α × α) : is_diag ⟦z⟧ ↔ z.1 = z.2 := prod.rec_on z $ λ _ _, mk_is_diag_iff @[simp] lemma diag_is_diag (a : α) : is_diag (diag a) := eq.refl a lemma is_diag.mem_range_diag {z : sym2 α} : is_diag z → z ∈ set.range (@diag α) := begin induction z using quotient.induction_on, cases z, rintro (rfl : z_fst = z_snd), exact ⟨z_fst, rfl⟩, end lemma is_diag_iff_mem_range_diag (z : sym2 α) : is_diag z ↔ z ∈ set.range (@diag α) := ⟨is_diag.mem_range_diag, λ ⟨i, hi⟩, hi ▸ diag_is_diag i⟩ instance is_diag.decidable_pred (α : Type u) [decidable_eq α] : decidable_pred (@is_diag α) := by { refine λ z, quotient.rec_on_subsingleton z (λ a, _), erw is_diag_iff_proj_eq, apply_instance } lemma other_ne {a : α} {z : sym2 α} (hd : ¬is_diag z) (h : a ∈ z) : h.other ≠ a := begin intro hn, apply hd, have h' := sym2.other_spec h, rw hn at h', rw ←h', simp, end section relations /-! ### Declarations about symmetric relations -/ variables {r : α → α → Prop} /-- Symmetric relations define a set on `sym2 α` by taking all those pairs of elements that are related. -/ def from_rel (sym : symmetric r) : set (sym2 α) := set_of (lift ⟨r, λ x y, propext ⟨λ h, sym h, λ h, sym h⟩⟩) @[simp] lemma from_rel_proj_prop {sym : symmetric r} {z : α × α} : ⟦z⟧ ∈ from_rel sym ↔ r z.1 z.2 := iff.rfl @[simp] lemma from_rel_prop {sym : symmetric r} {a b : α} : ⟦(a, b)⟧ ∈ from_rel sym ↔ r a b := iff.rfl lemma from_rel_irreflexive {sym : symmetric r} : irreflexive r ↔ ∀ {z}, z ∈ from_rel sym → ¬is_diag z := { mp := λ h, sym2.ind $ by { rintros a b hr (rfl : a = b), exact h _ hr }, mpr := λ h x hr, h (from_rel_prop.mpr hr) rfl } lemma mem_from_rel_irrefl_other_ne {sym : symmetric r} (irrefl : irreflexive r) {a : α} {z : sym2 α} (hz : z ∈ from_rel sym) (h : a ∈ z) : h.other ≠ a := other_ne (from_rel_irreflexive.mp irrefl hz) h instance from_rel.decidable_pred (sym : symmetric r) [h : decidable_rel r] : decidable_pred (∈ sym2.from_rel sym) := λ z, quotient.rec_on_subsingleton z (λ x, h _ _) /-- The inverse to `sym2.from_rel`. Given a set on `sym2 α`, give a symmetric relation on `α` (see `sym2.to_rel_symmetric`). -/ def to_rel (s : set (sym2 α)) (x y : α) : Prop := ⟦(x, y)⟧ ∈ s @[simp] lemma to_rel_prop (s : set (sym2 α)) (x y : α) : to_rel s x y ↔ ⟦(x, y)⟧ ∈ s := iff.rfl lemma to_rel_symmetric (s : set (sym2 α)) : symmetric (to_rel s) := λ x y, by simp [eq_swap] lemma to_rel_from_rel (sym : symmetric r) : to_rel (from_rel sym) = r := rfl lemma from_rel_to_rel (s : set (sym2 α)) : from_rel (to_rel_symmetric s) = s := set.ext (λ z, sym2.ind (λ x y, iff.rfl) z) end relations section sym_equiv /-! ### Equivalence to the second symmetric power -/ local attribute [instance] vector.perm.is_setoid private def from_vector : vector α 2 → α × α | ⟨[a, b], h⟩ := (a, b) private lemma perm_card_two_iff {a₁ b₁ a₂ b₂ : α} : [a₁, b₁].perm [a₂, b₂] ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ a₁ = b₂ ∧ b₁ = a₂ := { mp := by { simp [← multiset.coe_eq_coe, ← multiset.cons_coe, multiset.cons_eq_cons]; tidy }, mpr := by { intro h, cases h; rw [h.1, h.2], apply list.perm.swap', refl } } /-- The symmetric square is equivalent to length-2 vectors up to permutations. -/ def sym2_equiv_sym' : equiv (sym2 α) (sym' α 2) := { to_fun := quotient.map (λ (x : α × α), ⟨[x.1, x.2], rfl⟩) (by { rintros _ _ ⟨_⟩, { refl }, apply list.perm.swap', refl }), inv_fun := quotient.map from_vector (begin rintros ⟨x, hx⟩ ⟨y, hy⟩ h, cases x with _ x, { simpa using hx, }, cases x with _ x, { simpa using hx, }, cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] }, cases y with _ y, { simpa using hy, }, cases y with _ y, { simpa using hy, }, cases y with _ y, swap, { exfalso, simp at hy, linarith [hy] }, rcases perm_card_two_iff.mp h with ⟨rfl,rfl⟩|⟨rfl,rfl⟩, { refl }, apply sym2.rel.swap, end), left_inv := by tidy, right_inv := λ x, begin refine quotient.rec_on_subsingleton x (λ x, _), { cases x with x hx, cases x with _ x, { simpa using hx, }, cases x with _ x, { simpa using hx, }, cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] }, refl }, end } /-- The symmetric square is equivalent to the second symmetric power. -/ def equiv_sym (α : Type*) : sym2 α ≃ sym α 2 := equiv.trans sym2_equiv_sym' sym_equiv_sym'.symm /-- The symmetric square is equivalent to multisets of cardinality two. (This is currently a synonym for `equiv_sym`, but it's provided in case the definition for `sym` changes.) -/ def equiv_multiset (α : Type*) : sym2 α ≃ {s : multiset α // s.card = 2} := equiv_sym α end sym_equiv section decidable /-- An algorithm for computing `sym2.rel`. -/ def rel_bool [decidable_eq α] (x y : α × α) : bool := if x.1 = y.1 then x.2 = y.2 else if x.1 = y.2 then x.2 = y.1 else ff lemma rel_bool_spec [decidable_eq α] (x y : α × α) : ↥(rel_bool x y) ↔ rel α x y := begin cases x with x₁ x₂, cases y with y₁ y₂, dsimp [rel_bool], split_ifs; simp only [false_iff, bool.coe_sort_ff, bool.of_to_bool_iff], rotate 2, { contrapose! h, cases h; cc }, all_goals { subst x₁, split; intro h1, { subst h1; apply sym2.rel.swap }, { cases h1; cc } } end /-- Given `[decidable_eq α]` and `[fintype α]`, the following instance gives `fintype (sym2 α)`. -/ instance (α : Type*) [decidable_eq α] : decidable_rel (sym2.rel α) := λ x y, decidable_of_bool (rel_bool x y) (rel_bool_spec x y) /-! ### The other element of an element of the symmetric square -/ /-- A function that gives the other element of a pair given one of the elements. Used in `mem.other'`. -/ private def pair_other [decidable_eq α] (a : α) (z : α × α) : α := if a = z.1 then z.2 else z.1 /-- Get the other element of the unordered pair using the decidable equality. This is the computable version of `mem.other`. -/ def mem.other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : α := quot.rec (λ x h', pair_other a x) (begin clear h z, intros x y h, ext hy, convert_to pair_other a x = _, { have h' : ∀ {c e h}, @eq.rec _ ⟦x⟧ (λ s, a ∈ s → α) (λ _, pair_other a x) c e h = pair_other a x, { intros _ e _, subst e }, apply h', }, have h' := (rel_bool_spec x y).mpr h, cases x with x₁ x₂, cases y with y₁ y₂, cases mem_iff.mp hy with hy'; subst a; dsimp [rel_bool] at h'; split_ifs at h'; try { rw bool.of_to_bool_iff at h', subst x₁, subst x₂ }; dsimp [pair_other], simp only [ne.symm h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', simp only [h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', end) z h @[simp] lemma other_spec' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other')⟧ = z := begin induction z, cases z with x y, have h' := mem_iff.mp h, dsimp [mem.other', quot.rec, pair_other], cases h'; subst a, { simp only [if_true, eq_self_iff_true], refl, }, { split_ifs, subst h_1, refl, rw eq_swap, refl, }, refl, end @[simp] lemma other_eq_other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other = h.other' := by rw [←congr_right, other_spec' h, other_spec] lemma other_mem' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other' ∈ z := by { rw ←other_eq_other', exact other_mem h } lemma other_invol' [decidable_eq α] {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other' ∈ z) : hb.other' = a := begin induction z, cases z with x y, dsimp [mem.other', quot.rec, pair_other] at hb, split_ifs at hb; dsimp [mem.other', quot.rec, pair_other], simp only [h, if_true, eq_self_iff_true], split_ifs, assumption, refl, simp only [h, if_false, if_true, eq_self_iff_true], exact ((mem_iff.mp ha).resolve_left h).symm, refl, end lemma other_invol {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other ∈ z) : hb.other = a := begin classical, rw other_eq_other' at hb ⊢, convert other_invol' ha hb, rw other_eq_other', end lemma filter_image_quotient_mk_is_diag [decidable_eq α] (s : finset α) : ((s.product s).image quotient.mk).filter is_diag = s.diag.image quotient.mk := begin ext z, induction z using quotient.induction_on, rcases z with ⟨x, y⟩, simp only [mem_image, mem_diag, exists_prop, mem_filter, prod.exists, mem_product], split, { rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩, rw [←h, sym2.mk_is_diag_iff] at hab, exact ⟨a, b, ⟨ha, hab⟩, h⟩ }, { rintro ⟨a, b, ⟨ha, rfl⟩, h⟩, rw ←h, exact ⟨⟨a, a, ⟨ha, ha⟩, rfl⟩, rfl⟩ } end lemma filter_image_quotient_mk_not_is_diag [decidable_eq α] (s : finset α) : ((s.product s).image quotient.mk).filter (λ a : sym2 α, ¬a.is_diag) = s.off_diag.image quotient.mk := begin ext z, induction z using quotient.induction_on, rcases z with ⟨x, y⟩, simp only [mem_image, mem_off_diag, exists_prop, mem_filter, prod.exists, mem_product], split, { rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩, rw [←h, sym2.mk_is_diag_iff] at hab, exact ⟨a, b, ⟨ha, hb, hab⟩, h⟩ }, { rintro ⟨a, b, ⟨ha, hb, hab⟩, h⟩, rw [ne.def, ←sym2.mk_is_diag_iff, h] at hab, exact ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩ } end end decidable instance [subsingleton α] : subsingleton (sym2 α) := (equiv_sym α).injective.subsingleton instance [unique α] : unique (sym2 α) := unique.mk' _ instance [is_empty α] : is_empty (sym2 α) := (equiv_sym α).is_empty instance [nontrivial α] : nontrivial (sym2 α) := diag_injective.nontrivial end sym2
3e10fb2b97b43a4c4cf914e25728e46e9ced03b2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/dold_kan/n_reflects_iso.lean
a7f00f781d4b513bedb8d87b9659214dbfb4dde3
[ "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
2,599
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.functor_n import algebraic_topology.dold_kan.decomposition import category_theory.idempotents.homological_complex /-! # N₁ and N₂ reflects isomorphisms In this file, it is shown that the functor `N₁ : simplicial_object C ⥤ karoubi (chain_complex C ℕ)` reflects isomorphisms for any preadditive category `C`. TODO @joelriou: deduce that `N₂ : karoubi (simplicial_object C) ⥤ karoubi (chain_complex C ℕ)` also reflects isomorphisms. -/ open category_theory open category_theory.category open category_theory.idempotents open opposite open_locale simplicial namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] open morph_components instance : reflects_isomorphisms (N₁ : simplicial_object C ⥤ karoubi (chain_complex C ℕ)) := ⟨λ X Y f, begin introI, /- restating the result in a way that allows induction on the degree n -/ suffices : ∀ (n : ℕ), is_iso (f.app (op [n])), { haveI : ∀ (Δ : simplex_categoryᵒᵖ), is_iso (f.app Δ) := λ Δ, this Δ.unop.len, apply nat_iso.is_iso_of_is_iso_app, }, /- restating the assumption in a more practical form -/ have h₁ := homological_complex.congr_hom (karoubi.hom_ext.mp (is_iso.hom_inv_id (N₁.map f))), have h₂ := homological_complex.congr_hom (karoubi.hom_ext.mp (is_iso.inv_hom_id (N₁.map f))), have h₃ := λ n, karoubi.homological_complex.p_comm_f_assoc (inv (N₁.map f)) (n) (f.app (op [n])), simp only [N₁_map_f, karoubi.comp_f, homological_complex.comp_f, alternating_face_map_complex.map_f, N₁_obj_p, karoubi.id_eq, assoc] at h₁ h₂ h₃, /- we have to construct an inverse to f in degree n, by induction on n -/ intro n, induction n with n hn, /- degree 0 -/ { use (inv (N₁.map f)).f.f 0, have h₁₀ := h₁ 0, have h₂₀ := h₂ 0, dsimp at h₁₀ h₂₀, simp only [id_comp, comp_id] at h₁₀ h₂₀, tauto, }, /- induction step -/ { haveI := hn, use φ { a := P_infty.f (n+1) ≫ (inv (N₁.map f)).f.f (n+1), b := λ i, inv (f.app (op [n])) ≫ X.σ i, }, simp only [morph_components.id, ← id_φ, ← pre_comp_φ, pre_comp, ← post_comp_φ, post_comp, P_infty_f_naturality_assoc, is_iso.hom_inv_id_assoc, assoc, is_iso.inv_hom_id_assoc, simplicial_object.σ_naturality, h₁, h₂, h₃], tauto, }, end⟩ end dold_kan end algebraic_topology
2523293e5e6fe9f0cd9d1ee2ef2d052b65813294
78269ad0b3c342b20786f60690708b6e328132b0
/src/library_dev/data/nat/bquant.lean
181ee1fadb76dd496fd1d7dd867679b4530e4efa
[]
no_license
dselsam/library_dev
e74f46010fee9c7b66eaa704654cad0fcd2eefca
1b4e34e7fb067ea5211714d6d3ecef5132fc8218
refs/heads/master
1,610,372,841,675
1,497,014,421,000
1,497,014,421,000
86,526,137
0
0
null
1,490,752,133,000
1,490,752,132,000
null
UTF-8
Lean
false
false
2,375
lean
import .sub open nat def ball (n : nat) (P : nat → Prop) := ∀ k : ℕ, k < n → P k def ball' (n : nat) (P : Π (k : ℕ) (p : k < n), Prop) := Π (k : ℕ) (p : k < n), P k p theorem ball_zero (P : nat → Prop) : ball 0 P := λ x Hlt, absurd Hlt (not_lt_zero _) theorem ball_zero' (P : Π (k : ℕ) (p : k < 0), Prop) : ball' 0 P := λ k p, absurd p (not_lt_zero _) theorem ball_of_ball_succ {n : nat} {P : nat → Prop} (H : ball (succ n) P) : ball n P := λ x Hlt, H x (lt.step Hlt) def step_p {n : ℕ} (P : Π (k : ℕ) (p : k < succ n), Prop) : Π (k : ℕ) (p : k < n), Prop := λ k p, P k (lt.step p) theorem ball_of_ball_succ' {n : nat} {P : Π (k : ℕ) (p : k < succ n), Prop} (H : ball' (succ n) P) : ball' n (step_p P) := λ x Hlt, H _ _ theorem ball_succ_of_ball {n : nat} {P : nat → Prop} (H₁ : ball n P) (H₂ : P n) : ball (succ n) P := λ (x : nat) (Hlt : x < succ n), or.elim (nat.eq_or_lt_of_le (le_of_succ_le_succ Hlt)) (λ heq : x = n, (eq.symm heq) ▸ H₂) (λ hlt : x < n, H₁ x hlt) theorem not_ball_of_not {n : nat} {P : nat → Prop} (H₁ : ¬ P n) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (H n (lt.base n)) H₁ theorem not_ball_succ_of_not_ball {n : nat} {P : nat → Prop} (H₁ : ¬ ball n P) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (ball_of_ball_succ H) H₁ instance decidable_ball (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (ball n P) := nat.rec_on n (decidable.is_true (ball_zero P)) (λ n₁ ih, decidable.rec_on ih (λ ih_neg, decidable.is_false (not_ball_succ_of_not_ball ih_neg)) (λ ih_pos, decidable.rec_on (H n₁) (λ p_neg, decidable.is_false (not_ball_of_not p_neg)) (λ p_pos, decidable.is_true (ball_succ_of_ball ih_pos p_pos)))) instance decidable_lo_hi (lo hi : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := suffices ball (hi - lo) (λx, P (lo + x)) ↔ (∀x, lo ≤ x → x < hi → P x), from decidable_of_decidable_of_iff (by apply_instance) this, ⟨λal x hl hh, by note := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (by rw add_comm; exact nat.add_lt_of_lt_sub h)⟩
820c828dacb4afd8139fe7141e10714428f74526
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/uniform_ring.lean
7d8bbd1c1196bf5255c9a8056ef1a1b66ec74b6a
[ "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
12,073
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 -/ import algebra.algebra.basic import topology.algebra.group_completion import topology.algebra.ring.ideal /-! # Completion of topological rings: > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This files endows the completion of a topological ring with a ring structure. More precisely the instance `uniform_space.completion.ring` builds a ring structure on the completion of a ring endowed with a compatible uniform structure in the sense of `uniform_add_group`. There is also a commutative version when the original ring is commutative. Moreover, if a topological ring is an algebra over a commutative semiring, then so is its `uniform_space.completion`. The last part of the file builds a ring structure on the biggest separated quotient of a ring. ## Main declarations: Beyond the instances explained above (that don't have to be explicitly invoked), the main constructions deal with continuous ring morphisms. * `uniform_space.completion.extension_hom`: extends a continuous ring morphism from `R` to a complete separated group `S` to `completion R`. * `uniform_space.completion.map_ring_hom` : promotes a continuous ring morphism from `R` to `S` into a continuous ring morphism from `completion R` to `completion S`. TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`. -/ open classical set filter topological_space add_comm_group open_locale classical noncomputable theory universes u 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]), .. add_monoid_with_one.unary, ..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 α 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_add_monoid_hom_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) section algebra variables (A : Type*) [ring A] [uniform_space A] [uniform_add_group A] [topological_ring A] (R : Type*) [comm_semiring R] [algebra R A] [has_uniform_continuous_const_smul R A] @[simp] lemma map_smul_eq_mul_coe (r : R) : completion.map ((•) r) = (*) (algebra_map R A r : completion A) := begin ext x, refine completion.induction_on x _ (λ a, _), { exact is_closed_eq (completion.continuous_map) (continuous_mul_left _) }, { rw [map_coe (uniform_continuous_const_smul r) a, algebra.smul_def, coe_mul] }, end instance : algebra R (completion A) := { commutes' := λ r x, completion.induction_on x (is_closed_eq (continuous_mul_left _) (continuous_mul_right _)) $ λ a, by simpa only [coe_mul] using congr_arg (coe : A → completion A) (algebra.commutes r a), smul_def' := λ r x, congr_fun (map_smul_eq_mul_coe A R r) x, ..((uniform_space.completion.coe_ring_hom : A →+* completion A).comp (algebra_map R A)) } lemma algebra_map_def (r : R) : algebra_map R (completion A) r = (algebra_map R A r : completion A) := rfl end algebra section comm_ring 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 } /-- A shortcut instance for the common case -/ instance algebra' : algebra R (completion R) := by apply_instance end comm_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 $ λ x y, (add_group_separation_rel x y).trans $ iff.trans (by refl) (submodule.quotient_rel_r_def _).symm lemma ring_sep_quot (α : Type u) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (α ⧸ (⊥ : ideal α).closure) := 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.congr_right $ λ x y, (add_group_separation_rel x y).trans $ iff.trans (by refl) (submodule.quotient_rel_r_def _).symm /- 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 section uniform_extension variables {α : Type*} [uniform_space α] [semiring α] variables {β : Type*} [uniform_space β] [semiring β] [topological_semiring β] variables {γ : Type*} [uniform_space γ] [semiring γ] [topological_semiring γ] variables [t2_space γ] [complete_space γ] /-- The dense inducing extension as a ring homomorphism. -/ noncomputable def dense_inducing.extend_ring_hom {i : α →+* β} {f : α →+* γ} (ue : uniform_inducing i) (dr : dense_range i) (hf : uniform_continuous f): β →+* γ := { to_fun := (ue.dense_inducing dr).extend f, map_one' := by { convert dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous 1, exacts [i.map_one.symm, f.map_one.symm], }, map_zero' := by { convert dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous 0, exacts [i.map_zero.symm, f.map_zero.symm], }, map_add' := begin have h := (uniform_continuous_uniformly_extend ue dr hf).continuous, refine λ x y, dense_range.induction_on₂ dr _ (λ a b, _) x y, { exact is_closed_eq (continuous.comp h continuous_add) ((h.comp continuous_fst).add (h.comp continuous_snd)), }, { simp_rw [← i.map_add, dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous _, ← f.map_add], }, end, map_mul' := begin have h := (uniform_continuous_uniformly_extend ue dr hf).continuous, refine λ x y, dense_range.induction_on₂ dr _ (λ a b, _) x y, { exact is_closed_eq (continuous.comp h continuous_mul) ((h.comp continuous_fst).mul (h.comp continuous_snd)), }, { simp_rw [← i.map_mul, dense_inducing.extend_eq (ue.dense_inducing dr) hf.continuous _, ← f.map_mul], }, end, } end uniform_extension
ff3379202a5ae66c7ef3ad4fe9a88d378bb76eb0
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/meta_level1.lean
bf8475dd0a11f922bfeca58469aceef5f4f79631
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
964
lean
import system.io vm_eval do pp (level.max (level.succ level.zero) (level.param `foo)), put_str "\n" vm_eval level.normalize (level.succ (level.max (level.max level.zero (level.succ level.zero)) (level.param `l₁))) vm_eval level.imax (level.mvar `m) (level.of_nat 10) vm_eval if level.zero = level.zero then "eq" else "neq" vm_eval level.occurs (level.param `l2) (level.max (level.param `l1) (level.param `l2)) vm_eval level.occurs (level.param `l3) (level.max (level.param `l1) (level.param `l2)) vm_eval level.eqv (level.max (level.param `l1) (level.param `l2)) (level.max (level.param `l2) (level.param `l1)) vm_eval level.eqv (level.max (level.param `l1) (level.param `l2)) (level.max (level.param `l2) (level.param `l2)) vm_eval level.has_param (level.max (level.param `l1) (level.param `l2)) `l1 vm_eval level.has_param (level.max (level.param `l1) (level.param `l2)) `l2 vm_eval level.has_param (level.max (level.param `l1) (level.param `l2)) `l3
f033afa0ca5644de05bdfefb2b7560d95faaaefd
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/logic/function.lean
66c41e8fae61fb9920902aa9dbc999908ec9d9d1
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
8,676
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Miscellaneous function constructions and lemmas. -/ import logic.basic data.option universes u v w namespace function section variables {α : Sort u} {β : Sort v} {f : α → β} lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl @[simp] theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α | a b := decidable_of_iff _ I.eq_iff instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem cantor_surjective {α} (f : α → α → Prop) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) theorem cantor_injective {α : Type*} (f : (α → Prop) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ surjective_of_has_right_inverse ⟨f, λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩⟩ /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem left_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf local attribute [instance] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [inhabited α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} local attribute [instance] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else default α theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀x∈s, ∀y∈s, f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = default α := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := surjective_of_has_right_inverse ⟨_, left_inverse_inv_fun hf⟩ lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, injective_of_has_left_inverse⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, surjective_of_has_right_inverse⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨injective_of_left_inverse gl, surjective_of_has_right_inverse ⟨_, gr⟩⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := injective_of_has_left_inverse ⟨f, right_inverse_surj_inv h⟩ end surj_inv section update variables {α : Sort u} {β : α → Sort v} [decidable_eq α] def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a @[simp] lemma update_same {a : α} {v : β a} {f : Πa, β a} : update f a v a = v := dif_pos rfl @[simp] lemma update_noteq {a a' : α} {v : β a'} {f : Πa, β a} (h : a ≠ a') : update f a' v a = f a := dif_neg h end update lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := funext $ assume ⟨a, b⟩, rfl end function
d449dec1a33c2be2d392a0cfb481301e8a8a28d7
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/macro.lean
fd4203683c59c673857d8b1c75bc082ebc3c78b6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,206
lean
abbrev Set (α : Type) := α → Prop axiom setOf {α : Type} : (α → Prop) → Set α axiom mem {α : Type} : α → Set α → Prop axiom univ {α : Type} : Set α axiom Union {α : Type} : Set (Set α) → Set α syntax:100 term " ∈ " term:99 : term macro_rules | `($x ∈ $s) => `(mem $x $s) declare_syntax_cat index syntax term : index -- `≤` has precedence 50 syntax term:51 "≤" ident "<" term:51 : index syntax ident ":" term : index syntax "{" index " | " term "}" : term macro_rules | `({$l:term ≤ $x < $u | $p}) => `(setOf (fun $x => $l ≤ $x ∧ $x < $u ∧ $p)) | `({$x:ident : $t | $p}) => `(setOf (fun ($x : $t) => $p)) | `({$x:term ∈ $s | $p}) => `(setOf (fun $x => $x ∈ $s ∧ $p)) | `({$x:term ≤ $e | $p}) => `(setOf (fun $x => $x ≤ $e ∧ $p)) | `({$b:term | $r}) => `(setOf (fun $b => $r)) #check { 1 ≤ x < 10 | x ≠ 5 } #check { f : Nat → Nat | f 1 > 0 } syntax "⋃ " term ", " term : term macro_rules | `(⋃ $b, $r) => `(Union {$b:term | $r}) #check ⋃ x, x = x #check ⋃ (x : Set Unit), x = x #check ⋃ x ∈ univ, x = x syntax "#check2" term : command macro_rules | `(#check2 $e) => `(#check $e #check $e) #check2 1
d39807e0d3cd27f84aa64ea87316826dde7d6879
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/control/bitraversable/instances.lean
96d89dd41f8760ee9b2e2fd3bef164da15f40c3d
[ "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
4,394
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.bitraversable.lemmas import control.traversable.lemmas /-! # bitraversable instances ## Instances * prod * sum * const * flip * bicompl * bicompr ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ universes u v w variables {t : Type u → Type u → Type u} [bitraversable t] section variables {F : Type u → Type u} [applicative F] def prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β') | (x,y) := prod.mk <$> f x <*> f' y instance : bitraversable prod := { bitraverse := @prod.bitraverse } instance : is_lawful_bitraversable prod := by constructor; introsI; cases x; simp [bitraverse,prod.bitraverse] with functor_norm; refl open functor def sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β') | (sum.inl x) := sum.inl <$> f x | (sum.inr x) := sum.inr <$> f' x instance : bitraversable sum := { bitraverse := @sum.bitraverse } instance : is_lawful_bitraversable sum := by constructor; introsI; cases x; simp [bitraverse,sum.bitraverse] with functor_norm; refl def const.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : const α β → F (const α' β') := f instance bitraversable.const : bitraversable const := { bitraverse := @const.bitraverse } instance is_lawful_bitraversable.const : is_lawful_bitraversable const := by constructor; introsI; simp [bitraverse,const.bitraverse] with functor_norm; refl def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : flip t α β → F (flip t α' β') := (bitraverse f' f : t β α → F (t β' α')) instance bitraversable.flip : bitraversable (flip t) := { bitraverse := @flip.bitraverse t _ } open is_lawful_bitraversable instance is_lawful_bitraversable.flip [is_lawful_bitraversable t] : is_lawful_bitraversable (flip t) := by constructor; intros; unfreezingI { casesm is_lawful_bitraversable t }; tactic.apply_assumption open bitraversable functor @[priority 10] instance bitraversable.traversable {α} : traversable (t α) := { traverse := @tsnd t _ _ } @[priority 10] instance bitraversable.is_lawful_traversable [is_lawful_bitraversable t] {α} : is_lawful_traversable (t α) := by { constructor; introsI; simp [traverse,comp_tsnd] with functor_norm, { refl }, { simp [tsnd_eq_snd_id], refl }, { simp [tsnd,binaturality,function.comp] with functor_norm } } end open bifunctor traversable is_lawful_traversable is_lawful_bitraversable open function (bicompl bicompr) section bicompl variables (F G : Type u → Type u) [traversable F] [traversable G] def bicompl.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompl t F G α α' → m (bicompl t F G β β') := (bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _) instance : bitraversable (bicompl t F G) := { bitraverse := @bicompl.bitraverse t _ F G _ _ } instance [is_lawful_traversable F] [is_lawful_traversable G] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompl t F G) := begin constructor; introsI; simp [bitraverse, bicompl.bitraverse, bimap, traverse_id, bitraverse_id_id, comp_bitraverse] with functor_norm, { simp [traverse_eq_map_id',bitraverse_eq_bimap_id], }, { revert x, dunfold bicompl, simp [binaturality,naturality_pf] } end end bicompl section bicompr variables (F : Type u → Type u) [traversable F] def bicompr.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompr F t α α' → m (bicompr F t β β') := (traverse (bitraverse f f') : F (t α α') → m _) instance : bitraversable (bicompr F t) := { bitraverse := @bicompr.bitraverse t _ F _ } instance [is_lawful_traversable F] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompr F t) := begin constructor; introsI; simp [bitraverse,bicompr.bitraverse,bitraverse_id_id] with functor_norm, { simp [bitraverse_eq_bimap_id',traverse_eq_map_id'], refl }, { revert x, dunfold bicompr, intro, simp [naturality,binaturality'] } end end bicompr
96c5338ba2db4216d8fcfff3be4abb5864bcbedf
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/proposition.lean
eccfdda0e78e9e3e45a0290f675ea62ee3cf4a6b
[ "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
99
lean
proposition tst {a b : Prop} : a → b → a ∧ b := begin intros, split, repeat assumption end
1fc9fb9ef458d1a8e9ea9d74c63080016897895e
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/sheaves/sheaf_on_basis.lean
0386c66eae9d9188c196a45b8c12f41b9ce61837
[]
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
6,946
lean
/- Sheaf (of types) on basis and extension. https://stacks.math.columbia.edu/tag/009J https://stacks.math.columbia.edu/tag/009N -/ import sheaves.covering.covering_on_basis import sheaves.presheaf import sheaves.presheaf_on_basis import sheaves.presheaf_extension import sheaves.sheaf import sheaves.sheaf_on_standard_basis import sheaves.stalk_on_basis universes u v w open topological_space open lattice open covering open classical section sheaf_on_basis parameters {α : Type u} [topological_space α] parameters {B : set (opens α)} {HB : opens.is_basis B} -- Sheaf condition. definition is_sheaf_on_basis (F : presheaf_on_basis α HB) := ∀ {U} (BU : U ∈ B) (OC : covering_basis U), ∀ (s : Π i, F (OC.BUis i)), (∀ i j k, F.res (OC.BUis i) (OC.BUijks i j k) (subset_covering_basis_inter_left i j k) (s i) = F.res (OC.BUis j) (OC.BUijks i j k) (subset_covering_basis_inter_right i j k) (s j)) → ∃! S, ∀ i, F.res BU (OC.BUis i) (subset_covering i) S = s i section presheaf_extension_preserves_sheaf_condition -- Presheaf extension preserves sheaf condition. noncomputable def global_section (F : presheaf_on_basis α HB) (U : opens α) (OC : covering U) (s : Π i, (F ₑₓₜ) (OC.Uis i)) (Hsec : ∀ (j k : OC.γ), 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)) : {r : Π (x ∈ U), stalk_on_basis F x // ∀ (x ∈ U), ∃ (V) (BV : V ∈ B) (Hx : x ∈ V) (σ : F BV), ∀ (y ∈ U ∩ V), r y = λ _, ⟦{U := V, BU := BV, Hx := H.2, s := σ}⟧} := begin refine ⟨_, _⟩, { -- Define s. intros x HxU, rw OC.Hcov.symm at HxU, rcases (classical.indefinite_description _ HxU) with ⟨Uk, HUk⟩, rcases (classical.indefinite_description _ HUk) with ⟨HUkUis, HxUk⟩, rcases (classical.indefinite_description _ HUkUis) with ⟨OUk, ⟨HOUkUis, HUkeq⟩⟩, rcases (classical.indefinite_description _ HOUkUis) with ⟨k, HUiskeq⟩, rw HUkeq.symm at HxUk, rw HUiskeq.symm at HxUk, exact (s k).val x HxUk }, { -- Prove the property of s. intros x HxU, erw OC.Hcov.symm at HxU, rcases HxU with ⟨Uk, ⟨⟨OUk, ⟨⟨k, HUiskeq⟩, HUkeq⟩⟩, HxUk⟩⟩, rw HUkeq.symm at HxUk, rw HUiskeq.symm at HxUk, rcases (s k).property x HxUk with ⟨V, ⟨BV, ⟨HxV, ⟨σ, Hσ⟩⟩⟩⟩, -- We find W ∈ B such that x ∈ W and W ⊆ V ∩ Ui k. have HxVUik : x ∈ (V ∩ OC.Uis k) := ⟨HxV, HxUk⟩, have OVUik := is_open_inter V.2 (OC.Uis k).2, have HVUik := mem_nhds_sets OVUik HxVUik, have HW := (mem_nhds_of_is_topological_basis HB).1 HVUik, rcases HW with ⟨W, BW, ⟨HxW, HWVUk⟩⟩, simp at BW, rcases BW with ⟨OW, BW⟩, -- We now find the right σ' ∈ F(W). have HWV := (set.subset.trans HWVUk $ set.inter_subset_left _ _), let σ' := F.res BV BW HWV σ, -- Exists (W, σ') and proceed. use [⟨W, OW⟩, BW, HxW, σ'], rintros y ⟨HyU, HyW⟩, have HyVUik : y ∈ (V ∩ OC.Uis k) := HWVUk HyW, apply funext, intros HyU; dsimp, -- Now we need to show that ⟦(s k, Ui k)⟧ corresponds to ⟦(σ', W)⟧. have Hsk := Hσ y HyVUik.symm, let HyUi := λ t, ∃ (H : t ∈ subtype.val '' set.range OC.Uis), y ∈ t, rcases (classical.indefinite_description HyUi _) with ⟨S, HS⟩; dsimp, let HyS := λ H : S ∈ subtype.val '' set.range OC.Uis, y ∈ S, rcases (classical.indefinite_description HyS _) with ⟨HSUiR, HySUiR⟩; dsimp, let HOUksub := λ t : subtype is_open, t ∈ set.range (OC.Uis) ∧ t.val = S, rcases (classical.indefinite_description HOUksub _) with ⟨OUl, ⟨HOUl, HOUleq⟩⟩; dsimp, let HSUi := λ i, OC.Uis i = OUl, cases (classical.indefinite_description HSUi _) with l HSUil; dsimp, -- We finally have (s l).val y _ = ⟦(W, σ')⟧. have HyOUk : y ∈ OUl.val := HOUleq.symm ▸ HySUiR, have HyUil : y ∈ OC.Uis l := HSUil.symm ▸ HyOUk, have HyUik : y ∈ OC.Uis k := HyVUik.2, suffices Hsuff : (s l).val y HyUil = (s k).val y HyUik, erw [Hsuff, Hsk], apply quotient.sound, use [⟨W, OW⟩, BW, HyW, HWV, (set.subset.refl _)]; simp, apply F.Hcomp', -- Proving Hsuff. let F' := presheaf_on_basis_to_presheaf F, let UkUl := OC.Uis k ∩ OC.Uis l, have Hslres : (s l).val y HyUil = (F'.res (OC.Uis l) UkUl (set.inter_subset_right _ _) (s l)).val y ⟨HyUik, HyUil⟩ := rfl, have Hskres : (s k).val y HyUik = (F'.res (OC.Uis k) UkUl (set.inter_subset_left _ _) (s k)).val y ⟨HyUik, HyUil⟩ := rfl, have Hs := Hsec k l, unfold res_to_inter_left at Hs, unfold res_to_inter_right at Hs, erw [Hslres, Hskres, Hs], apply congr_arg; simp } end theorem extension_is_sheaf (F : presheaf_on_basis α HB) (HF : is_sheaf_on_basis F) : is_sheaf (F ₑₓₜ) := begin split, -- Locality. { intros U OC s t Hst, apply subtype.eq, apply funext, intros x, apply funext, intros HxU, rw OC.Hcov.symm at HxU, rcases HxU with ⟨Uj1, ⟨⟨⟨Uj2, OUj⟩, ⟨⟨j, HUj⟩, Heq⟩⟩, HxUj⟩⟩, rcases Heq, rcases Heq, have Hstj := congr_fun (subtype.mk_eq_mk.1 (Hst j)), have HxUj1 : x ∈ OC.Uis j := HUj.symm ▸ HxUj, have Hstjx := congr_fun (Hstj x) HxUj1, exact Hstjx, }, -- Gluing. { intros U OC s Hsec, existsi (global_section F U OC s Hsec), -- To show: S|i = s_i for all i. intros i, apply subtype.eq, apply funext, intros x, apply funext, intros HxUi, have HxU : x ∈ U := OC.Hcov ▸ (opens_supr_subset OC.Uis i) HxUi, let HyUi := λ t, ∃ (H : t ∈ set.range OC.Uis), x ∈ t, dunfold presheaf_on_basis_to_presheaf; dsimp, dunfold global_section; dsimp, -- Same process of dealing with subtype.rec. let HyUi := λ t, ∃ (H : t ∈ subtype.val '' set.range OC.Uis), x ∈ t, rcases (classical.indefinite_description HyUi _) with ⟨S, HS⟩; dsimp, let HyS := λ H : S ∈ subtype.val '' set.range OC.Uis, x ∈ S, rcases (classical.indefinite_description HyS HS) with ⟨HSUiR, HySUiR⟩; dsimp, let HOUksub := λ t : subtype is_open, t ∈ set.range (OC.Uis) ∧ t.val = S, rcases (classical.indefinite_description HOUksub _) with ⟨OUl, ⟨HOUl, HOUleq⟩⟩; dsimp, let HSUi := λ i, OC.Uis i = OUl, cases (classical.indefinite_description HSUi _) with l HSUil; dsimp, -- Now we just need to apply Hsec in the right way. dunfold presheaf_on_basis_to_presheaf at Hsec, dunfold res_to_inter_left at Hsec, dunfold res_to_inter_right at Hsec, dsimp at Hsec, replace Hsec := Hsec i l, rw subtype.ext at Hsec, dsimp at Hsec, replace Hsec := congr_fun Hsec x, dsimp at Hsec, replace Hsec := congr_fun Hsec, have HxOUk : x ∈ OUl.val := HOUleq.symm ▸ HySUiR, have HxUl : x ∈ OC.Uis l := HSUil.symm ▸ HxOUk, exact (Hsec ⟨HxUi, HxUl⟩).symm }, end end presheaf_extension_preserves_sheaf_condition end sheaf_on_basis
c7ed11ca9ae81560fcfa91a2b9541bca66bf31b1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/opposites.lean
d66b4be1d6cbdc22ec2c43fe372f414634db9b88
[ "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
1,785
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.equiv import group_theory.group_action.opposite /-! # Module operations on `Mᵐᵒᵖ` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains definitions that build on top of the group action definitions in `group_theory.group_action.opposite`. -/ namespace mul_opposite universes u v variables (R : Type u) {M : Type v} [semiring R] [add_comm_monoid M] [module R M] /-- `mul_opposite.distrib_mul_action` extends to a `module` -/ instance : module R (mul_opposite M) := { add_smul := λ r₁ r₂ x, unop_injective $ add_smul r₁ r₂ (unop x), zero_smul := λ x, unop_injective $ zero_smul _ (unop x), ..mul_opposite.distrib_mul_action M R } /-- The function `op` is a linear equivalence. -/ def op_linear_equiv : M ≃ₗ[R] Mᵐᵒᵖ := { map_smul' := mul_opposite.op_smul, .. op_add_equiv } @[simp] lemma coe_op_linear_equiv : (op_linear_equiv R : M → Mᵐᵒᵖ) = op := rfl @[simp] lemma coe_op_linear_equiv_symm : ((op_linear_equiv R).symm : Mᵐᵒᵖ → M) = unop := rfl @[simp] lemma coe_op_linear_equiv_to_linear_map : ((op_linear_equiv R).to_linear_map : M → Mᵐᵒᵖ) = op := rfl @[simp] lemma coe_op_linear_equiv_symm_to_linear_map : ((op_linear_equiv R).symm.to_linear_map : Mᵐᵒᵖ → M) = unop := rfl @[simp] lemma op_linear_equiv_to_add_equiv : (op_linear_equiv R : M ≃ₗ[R] Mᵐᵒᵖ).to_add_equiv = op_add_equiv := rfl @[simp] lemma op_linear_equiv_symm_to_add_equiv : (op_linear_equiv R : M ≃ₗ[R] Mᵐᵒᵖ).symm.to_add_equiv = op_add_equiv.symm := rfl end mul_opposite
b06c4cbcdacb22a80fa8ac21de25a4a6252df324
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/rng.lean
c0a0f2da0a2a2751f44229a97b7dc3e9bbcda6c1
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
388
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Random number generators. -/ namespace certigrad open list constant RNG : Type namespace RNG constant mk : ℕ → RNG constant to_string : RNG → string instance : has_to_string RNG := has_to_string.mk to_string end RNG end certigrad
834f96321176fc0ef5182690a601b50529812156
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/coeIssues4.lean
55a036fd9eedf5980f8c3a7c6f5f611e2f87a175
[ "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
538
lean
-- def f : List Int → Bool := fun _ => true def ex3 : IO Bool := do let xs ← pure [1, 2, 3]; pure $ f xs -- Works inductive Expr | val : Nat → Expr | app : Expr → Expr → Expr instance : Coe Nat Expr := ⟨Expr.val⟩ def foo : Expr → Expr := fun e => e def ex1 : Bool := f [1, 2, 3] -- Works def ex2 : Bool := let xs := [1, 2, 3]; f xs -- Works def ex4 := [1, 2, 3].map $ fun x => x+1 def ex5 (xs : List String) := xs.foldl (fun r x => r.push x) Array.empty set_option pp.all true in #check foo 1 def ex6 := foo 1
a836b76389989588878e62ddc8ad3fb3b7a3d5ad
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep_2/basic_definitions/kernel_range.lean
7a687910353946473e58b58be8199425e767aec9
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
1,582
lean
import .sub_module universe variables u v w w' variables {G : Type u} [group G] {R : Type v}[ring R] variables {M1 : Type w} [add_comm_group M1] [module R M1] {M2 : Type w'} [add_comm_group M2] [module R M2] {ρ1 : group_representation G R M1} {ρ2 : group_representation G R M2} (f : ρ1 ⟶ᵣ ρ2 ) open stability morphism linear_map namespace Kernel instance ker_is_stable_submodule : stable_submodule ρ1 (ker f.ℓ) := { stability := begin intros g x hyp, erw mem_ker at *, change (f.ℓ ⊚ (ρ1 g)) x = _, erw f.commute, change(ρ2 g) (f.ℓ x) = 0, rw hyp, exact (ρ2 g).map_zero, end } /-! The Kernel of `f : ρ1 ⟶ᵣ ρ2` has representation. -/ def ker : group_representation G R (ker f.ℓ) := Res ρ1 end Kernel namespace range open linear_map /-- Range is stable. Let `y ∈ Im f`, let `g ∈ G`, we want : `ρ g y ∈ Im f`. Take `x ∈ M1` s.t `f x = y`. We have (from `f.commute`) : `(f ∘ ρ1 g) x = ρ2 g ∘ f x` i.e `ρ2 g y = f ( ρ1 g x)` and so `ρ2 g y ∈ Im f` -/ instance : stable_submodule ρ2 (range (f.ℓ)) := { stability := begin intros g y hyp, rw mem_range at *, rcases hyp with ⟨z , hyp ⟩, rw ← hyp, use (ρ1 g) z, change (f.ℓ ⊚ ρ1 g) z = _, rw f.commute, exact rfl, end } /-- For a morphism `f : ρ1 ⟶ᵣ ρ2` between `representation` we define a sub representation of `M2` -/ def Range : group_representation G R (range f.ℓ) := Res ρ2 end range
5de3b58c9e8d5be0167b054d6b35acd453750dc9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/module/submodule.lean
c3a100ff2db49328e5af57834c6bc5514c346c85
[ "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
15,118
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.linear_map import data.equiv.module import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u'' u' u v w variables {G : Type u''} {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [module R M] instance : set_like (submodule R M) M := ⟨submodule.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p := iff.rfl variables {p q : submodule R M} @[simp] lemma mem_mk {S : set M} {x : M} (h₁ h₂ h₃) : x ∈ (⟨S, h₁, h₂, h₃⟩ : submodule R M) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set M) (h₁ h₂ h₃) : ((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl @[simp] lemma mk_le_mk {S S' : set M} (h₁ h₂ h₃ h₁' h₂' h₃') : (⟨S, h₁, h₂, h₃⟩ : submodule R M) ≤ (⟨S', h₁', h₂', h₃'⟩ : submodule R M) ↔ S ⊆ S' := iff.rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M := { carrier := s, zero_mem' := hs.symm ▸ p.zero_mem', add_mem' := hs.symm ▸ p.add_mem', smul_mem' := hs.symm ▸ p.smul_mem' } @[simp] lemma coe_copy (S : submodule R M) (s : set M) (hs : s = ↑S) : (S.copy s hs : set M) = s := rfl lemma copy_eq (S : submodule R M) (s : set M) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) := to_add_submonoid_strict_mono.monotone @[simp] theorem coe_to_add_submonoid (p : submodule R M) : (p.to_add_submonoid : set M) = p := rfl theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff @[mono] lemma to_sub_mul_action_strict_mono : strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id @[mono] lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) := to_sub_mul_action_strict_mono.monotone @[simp] theorem coe_to_sub_mul_action (p : submodule R M) : (p.to_sub_mul_action : set M) = p := rfl end submodule namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {module_M : module R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem' lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma smul_of_tower_mem [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] (r : S) (h : x ∈ p) : r • x ∈ p := p.to_sub_mul_action.smul_of_tower_mem r h lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := p.to_add_submonoid.sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' [group G] [mul_action G M] [has_scalar G R] [is_scalar_tower G R M] (g : G) : g • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' g instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] : has_scalar S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ instance [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] : is_scalar_tower S R p := p.to_sub_mul_action.is_scalar_tower protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_smul_of_tower [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] (r : S) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance module' [semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] : module S p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } instance : module R p := p.module' instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p := ⟨λ c x h, have c = 0 ∨ (x : M) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl /-- Note the `add_submonoid` version of this lemma is called `add_submonoid.coe_finset_sum`. -/ @[simp] lemma coe_sum (x : ι → p) (s : finset ι) : ↑(∑ i in s, x i) = ∑ i in s, (x i : M) := p.subtype.map_sum section restrict_scalars variables (S) [semiring S] [module S M] [module R M] [has_scalar S R] [is_scalar_tower S R M] /-- `V.restrict_scalars S` is the `S`-submodule of the `S`-module given by restriction of scalars, corresponding to `V`, an `R`-submodule of the original `R`-module. -/ def restrict_scalars (V : submodule R M) : submodule S M := { carrier := V, zero_mem' := V.zero_mem, smul_mem' := λ c m h, V.smul_of_tower_mem c h, add_mem' := λ x y hx hy, V.add_mem hx hy } @[simp] lemma coe_restrict_scalars (V : submodule R M) : (V.restrict_scalars S : set M) = V := rfl @[simp] lemma restrict_scalars_mem (V : submodule R M) (m : M) : m ∈ V.restrict_scalars S ↔ m ∈ V := iff.refl _ @[simp] lemma restrict_scalars_self (V : submodule R M) : V.restrict_scalars R = V := set_like.coe_injective rfl variables (R S M) lemma restrict_scalars_injective : function.injective (restrict_scalars S : submodule R M → submodule S M) := λ V₁ V₂ h, ext $ set.ext_iff.1 (set_like.ext'_iff.1 h : _) @[simp] lemma restrict_scalars_inj {V₁ V₂ : submodule R M} : restrict_scalars S V₁ = restrict_scalars S V₂ ↔ V₁ = V₂ := (restrict_scalars_injective S _ _).eq_iff /-- Even though `p.restrict_scalars S` has type `submodule S M`, it is still an `R`-module. -/ instance restrict_scalars.orig_module (p : submodule R M) : module R (p.restrict_scalars S) := (by apply_instance : module R p) instance (p : submodule R M) : is_scalar_tower S R (p.restrict_scalars S) := { smul_assoc := λ r s x, subtype.ext $ smul_assoc r s (x : M) } /-- `restrict_scalars S` is an embedding of the lattice of `R`-submodules into the lattice of `S`-submodules. -/ @[simps] def restrict_scalars_embedding : submodule R M ↪o submodule S M := { to_fun := restrict_scalars S, inj' := restrict_scalars_injective S R M, map_rel_iff' := λ p q, by simp [set_like.le_def] } /-- Turning `p : submodule R M` into an `S`-submodule gives the same module structure as turning it into a type and adding a module structure. -/ @[simps {simp_rhs := tt}] def restrict_scalars_equiv (p : submodule R M) : p.restrict_scalars S ≃ₗ[R] p := { to_fun := id, inv_fun := id, map_smul' := λ c x, rfl, .. add_equiv.refl p } end restrict_scalars end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {module_M : module R M} variables (p p' : submodule R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := p.to_sub_mul_action.neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl @[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl include module_M theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M) | p q h := set_like.ext (set_like.ext_iff.1 h : _) @[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' := to_add_subgroup_injective.eq_iff @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) := to_add_subgroup_strict_mono.monotone omit module_M lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := p.to_add_subgroup.sub_mem @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := p.to_add_subgroup.add_mem_cancel_right lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := p.to_add_subgroup.add_mem_cancel_left instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl end add_comm_group section is_domain variables [ring R] [is_domain R] variables [add_comm_group M] [module R M] {b : ι → M} lemma not_mem_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ∉ N := by { intro hx, simpa using ortho (-1) x hx } lemma ne_zero_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ≠ 0 := mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho) end is_domain section ordered_monoid variables [semiring R] /-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/ instance to_ordered_add_comm_monoid {M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_add_comm_monoid S := subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/ instance to_linear_ordered_add_comm_monoid {M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_add_comm_monoid S := subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/ instance to_ordered_cancel_add_comm_monoid {M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_cancel_add_comm_monoid S := subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`. -/ instance to_linear_ordered_cancel_add_comm_monoid {M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_cancel_add_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) end ordered_monoid section ordered_group variables [ring R] /-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/ instance to_ordered_add_comm_group {M} [ordered_add_comm_group M] [module R M] (S : submodule R M) : ordered_add_comm_group S := subtype.coe_injective.ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`. -/ instance to_linear_ordered_add_comm_group {M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) : linear_ordered_add_comm_group S := subtype.coe_injective.linear_ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) end ordered_group end submodule namespace submodule variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M] variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p : submodule R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff s0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [module R M] := submodule R M
0421120be7cfc58f6bb5ea0f299e878688c50dc5
e0d5cc416b0cf9011f9706e3b89ad18e34595c44
/src/cayden/identities.lean
8f90be710d44767b1219aeb2648b831d0a9f0a43
[]
no_license
avigad/verified-encodings
c90701b68636c0bae2127b9eb7bcc53e71d06bc8
2b8c3b07a7cfcdad3b13cf01685eabe395f35c17
refs/heads/master
1,687,237,025,852
1,626,625,618,000
1,626,625,618,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,755
lean
/- Proving some useful identities in propositional logic -/ import data.list import data.finset open classical theorem resolution_single (p q r : Prop) : (p ∨ q) ∧ (¬p ∨ r) → q ∨ r := begin intro h, cases h with hpq hpr, cases classical.em p, cases hpr with hnp hr, exfalso, exact hnp h, exact or.inr hr, cases hpq with hp hq, exfalso, exact h hp, exact or.intro_left _ hq, end variable α : Prop #reduce (sizeof α) #reduce (finset.sizeof Prop {α}) #print finset.sizeof theorem erase_smaller (s : finset Prop) (a : Prop) (h : a ∈ s) : finset.sizeof Prop (s.erase a) < finset.sizeof Prop s := begin have k : (s.erase a) ⊂ s, from finset.erase_ssubset h, have j : finset.sizeof Prop (s.erase a) = finset.sizeof Prop (s.erase a), from rfl, have a_geq: sizeof a ≥ 0, simp, -- what could the reason be? tactic? have a_in : a ∈ {a}, from finset.mem_singleton_self a, have single_g : sizeof a < finset.sizeof Prop {a}, from finset.sizeof_lt_sizeof_of_mem a_in, have singleton_g : 0 < finset.sizeof Prop {a}, from pos_of_gt single_g, sorry end -- Now let's explore the definition of clauses as finite lists (of props) def clause := list Prop def clause_as_list_to_prop : list Prop → Prop | [] := ff | (x :: xs) := x ∨ (clause_as_list_to_prop xs) def clause_as_set_to_prop : finset Prop → Prop | s := if ∃a: Prop, a ∈ s then ∃a ∈ s, have finset.sizeof Prop (s.erase a) < finset.sizeof Prop s, from erase_smaller s a H, a ∨ (clause_as_set_to_prop (s.erase a)) else ff -- TODO: Why : clause not work, but list Prop does? theorem resolution_clause_as_list (c₁ c₂ : list Prop) (p : Prop) : (p ∈ c₁) ∧ ((¬p) ∈ c₂) → ((clause_as_list_to_prop c₁ ∧ clause_as_list_to_prop c₂) → clause_as_list_to_prop (c₁.append c₂)) := begin intro hpp, cases hpp with hp hnp, intro hcc, cases hcc with hc1 hc2, sorry end --theorem resolution_clause_as_set := sorry -- Now we prove that if we have a list of lists and partition them according to containing p, we can resolve -- Definition of XOR in logic.lean -- def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) -- Define shorthand for XOR notation a ⊕ b := xor a b -- Essentially a proof of de Morgan's laws lemma xor_as_cnf (a b : Prop) : a ⊕ b ↔ (a ∨ b) ∧ (¬a ∨ ¬b) := begin split, intro h, have j : (a ∧ ¬b) ∨ (b ∧ ¬ a), from h, cases j with anb bna, cases anb with ha hb, exact and.intro (or.intro_left _ ha) (or.intro_right _ hb), cases bna with hb ha, exact and.intro (or.intro_right _ hb) (or.intro_left _ ha), intro h, cases h with hab hnn, cases classical.em a, cases classical.em b, exfalso, cases hnn with han hbn, exact han h, exact hbn h_1, exact or.intro_left _ (and.intro h h_1), cases classical.em b, exact or.intro_right _ (and.intro h_1 h), cases hab with ha hb, exfalso, exact h ha, exfalso, exact h_1 hb, end -- Now let's try to define XOR for more variables -- Assumes the Props as arguments are atoms -- For the XOR gate, the pos versus neg for instantiating isn't really useful -- as the functions ignore pos/neg and treat all vars as being pos -- Theoretically, this isn't a problem, as we can just negate all vars until it works inductive literal : Type | Pos : nat → literal | Neg : nat → literal def nat_from_literal : literal → nat | (literal.Pos n) := n | (literal.Neg n) := n --def cnf_clause := list literal --def cnf := list cnf_clause --def xor_gate := list literal namespace xor_gate def evaluate_xor_helper (α : nat → bool) : list literal → nat → nat | [] n := n | (literal.Pos p :: r) n := bool.to_nat (α p) + evaluate_xor_helper r n | (literal.Neg p :: r) n := bool.to_nat (bnot (α p)) -- well-founded goes away if xor_gate becomes list literal def evaluate_xor (α : nat → bool) : list literal → bool | [] := false | (literal.Pos p :: r) := bxor (α p) (evaluate_xor r) | (literal.Neg p :: r) := bxor (bnot (α p)) (evaluate_xor r) -- The two branches are literally the same - way to reduce down to one? -- Way to get prod.mk out of the expression? def explode_with_negated_count : list literal → list (list literal × nat) | [] := [([], 0)] | (literal.Pos p :: r) := let e : list (list literal × nat) := explode_with_negated_count r, l1 := list.map (λx, let (l, c) := x in prod.mk (literal.Pos p :: l) (c : nat)) e, l2 := list.map (λx, let (l, c) := x in prod.mk (literal.Neg p :: l) (c + 1)) e in list.append l1 l2 | (literal.Neg p :: r) := let e : list (list literal × nat) := explode_with_negated_count r, l1 := list.map (λx, let (l, c) := x in prod.mk (literal.Pos p :: l) (c : nat)) e, l2 := list.map (λx, let (l, c) := x in prod.mk (literal.Neg p :: l) (c + 1)) e in list.append l1 l2 def xor_to_cnf : list literal → list (list literal) | [] := [[]] | [literal.Pos p] := [[literal.Pos p]] | [literal.Neg p] := [[literal.Neg p]] | (literal.Pos p :: r) := let rx := explode_with_negated_count r in list.map (λx, let (l, (c : nat)) := x in cond (c % 2 = 0) (literal.Pos p :: l) (literal.Neg p :: l)) rx | (literal.Neg p :: r) := let rx := explode_with_negated_count r in list.map (λx, let (l, (c : nat)) := x in cond (c % 2 = 0) (literal.Pos p :: l) (literal.Neg p :: l)) rx end xor_gate namespace cnf def evaluate_clause (α : nat → bool) : list literal → bool | [] := false | (literal.Pos p :: r) := cond (α p) true (evaluate_clause r) | (literal.Neg p :: r) := cond (α p) (evaluate_clause r) true def evaluate_cnf (α : nat → bool) : list (list literal) → bool | [] := true | (l :: ls) := cond (cnf.evaluate_clause α l) (evaluate_cnf ls) false end cnf def g1 : list literal := [literal.Pos 1, literal.Pos 2] def g2 : list literal := [literal.Pos 1, literal.Pos 2, literal.Pos 3] def g3 : list literal := [literal.Pos 1, literal.Pos 2, literal.Pos 3, literal.Pos 4] def c1 : list (list literal) := xor_gate.xor_to_cnf g1 def c2 : list (list literal) := xor_gate.xor_to_cnf g2 def c3 : list (list literal) := xor_gate.xor_to_cnf g3 #reduce c1 #reduce c2 #reduce c3 def a1 : nat → bool | 1 := true | 2 := true | _ := false def a2 : nat → bool | 1 := true | 2 := false | 3 := false | _ := false def a3 : nat → bool | 1 := false | 2 := false | 3 := true | 4 := true | _ := false #reduce cnf.evaluate_cnf a1 c1 #reduce cnf.evaluate_cnf a2 c2 #reduce cnf.evaluate_cnf a3 c3 theorem alternate (g : list literal) (l : literal) (α : nat → bool) : cnf.evaluate_cnf α (xor_gate.xor_to_cnf (l :: g)) = bxor (α l) (cnf.evaluate_cnf α (xor_gate.xor_to_cnf g)) := begin induction g, have : xor_gate.xor_to_cnf list.nil = [[]], from rfl, rw this, end -- Now to prove that both encodings are correct theorem xor_to_cnf_valid (g : list literal) : ∀(α : nat → bool), xor_gate.evaluate_xor α g = cnf.evaluate_cnf α (xor_gate.xor_to_cnf g) := begin intro α, induction g, exact rfl, -- By unrolling of functions? How does lean compute this? -- Inductive case cases g_hd with pos_n neg_n, have : bxor (α pos_n) (xor_gate.evaluate_xor α g_tl) = xor_gate.evaluate_xor α (literal.Pos pos_n :: g_tl), from rfl, rw ← this, sorry, --have xor_add : (α pos_n) ⊕ (xor_gate.evaluate_xor α g_tl) = xor_gate.evaluate_xor α (litera) /- -- Positive literal case cases (α pos_n), -- Positive literal returns false -/ end
660705b5d27eda043c23a3757b89ae5a43f37d29
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/complex/basic.lean
ffaf30f827e6864c46af6261e6af7d40ebef7dad
[ "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
7,851
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.complex.module import data.complex.is_R_or_C /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `re_clm` * `im_clm` * `of_real_clm` * `conj_cle` They are bundled versions of the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate as continuous `ℝ`-linear maps. The last two are also bundled as linear isometries in `of_real_li` and `conj_lie`. We also register the fact that `ℂ` is an `is_R_or_C` field. -/ noncomputable theory namespace complex instance : has_norm ℂ := ⟨abs⟩ instance : normed_group ℂ := normed_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } instance {R : Type*} [normed_field R] [normed_algebra R ℝ] : normed_algebra R ℂ := { norm_algebra_map_eq := λ x, (abs_of_real $ algebra_map R ℝ x).trans (norm_algebra_map_eq ℝ x), to_algebra := complex.algebra } @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn @[continuity] lemma continuous_abs : continuous abs := continuous_norm @[continuity] lemma continuous_norm_sq : continuous norm_sq := by simpa [← norm_sq_eq_abs] using continuous_abs.pow 2 open continuous_linear_map /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_clm : ℂ →L[ℝ] ℝ := re_lm.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_re_le_abs]) @[continuity] lemma continuous_re : continuous re := re_clm.continuous @[simp] lemma re_clm_coe : (coe (re_clm) : ℂ →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply (z : ℂ) : (re_clm : ℂ → ℝ) z = z.re := rfl @[simp] lemma re_clm_norm : ∥re_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥re_clm 1∥ : by simp ... ≤ ∥re_clm∥ : unit_le_op_norm _ _ (by simp) /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def im_clm : ℂ →L[ℝ] ℝ := im_lm.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_im_le_abs]) @[continuity] lemma continuous_im : continuous im := im_clm.continuous @[simp] lemma im_clm_coe : (coe (im_clm) : ℂ →ₗ[ℝ] ℝ) = im_lm := rfl @[simp] lemma im_clm_apply (z : ℂ) : (im_clm : ℂ → ℝ) z = z.im := rfl @[simp] lemma im_clm_norm : ∥im_clm∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥im_clm I∥ : by simp ... ≤ ∥im_clm∥ : unit_le_op_norm _ _ (by simp) /-- The complex-conjugation function from `ℂ` to itself is an isometric linear equivalence. -/ def conj_lie : ℂ ≃ₗᵢ[ℝ] ℂ := ⟨conj_ae.to_linear_equiv, abs_conj⟩ @[simp] lemma conj_lie_apply (z : ℂ) : conj_lie z = conj z := rfl lemma isometry_conj : isometry (conj : ℂ → ℂ) := conj_lie.isometry @[continuity] lemma continuous_conj : continuous conj := conj_lie.continuous /-- Continuous linear equiv version of the conj function, from `ℂ` to `ℂ`. -/ def conj_cle : ℂ ≃L[ℝ] ℂ := conj_lie @[simp] lemma conj_cle_coe : conj_cle.to_linear_equiv = conj_ae.to_linear_equiv := rfl @[simp] lemma conj_cle_apply (z : ℂ) : conj_cle z = z.conj := rfl @[simp] lemma conj_cle_norm : ∥(conj_cle : ℂ →L[ℝ] ℂ)∥ = 1 := conj_lie.to_linear_isometry.norm_to_continuous_linear_map /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_li : ℝ →ₗᵢ[ℝ] ℂ := ⟨of_real_am.to_linear_map, norm_real⟩ lemma isometry_of_real : isometry (coe : ℝ → ℂ) := of_real_li.isometry @[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := of_real_li.continuous /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_clm : ℝ →L[ℝ] ℂ := of_real_li.to_continuous_linear_map @[simp] lemma of_real_clm_coe : (of_real_clm : ℝ →ₗ[ℝ] ℂ) = of_real_am.to_linear_map := rfl @[simp] lemma of_real_clm_apply (x : ℝ) : of_real_clm x = x := rfl @[simp] lemma of_real_clm_norm : ∥of_real_clm∥ = 1 := of_real_li.norm_to_continuous_linear_map noncomputable instance : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } end complex namespace is_R_or_C local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `conjC` := @is_R_or_C.conj ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end is_R_or_C
059c4dad3c135ccf32f9622daaa8c927f71ec651
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/holor.lean
1210d2d21fcbb66bc298c6e97c1a69296f876a30
[]
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,587
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.pi import Mathlib.algebra.big_operators.basic import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : List ℕ) := Subtype fun (is : List ℕ) => list.forall₂ Less is ds namespace holor_index def take {ds₂ : List ℕ} {ds₁ : List ℕ} : holor_index (ds₁ ++ ds₂) → holor_index ds₁ := sorry def drop {ds₂ : List ℕ} {ds₁ : List ℕ} : holor_index (ds₁ ++ ds₂) → holor_index ds₂ := sorry theorem cast_type {ds₁ : List ℕ} {ds₂ : List ℕ} (is : List ℕ) (eq : ds₁ = ds₂) (h : list.forall₂ Less is ds₁) : subtype.val (cast (congr_arg holor_index eq) { val := is, property := h }) = is := eq.drec (Eq.refl (subtype.val (cast (congr_arg holor_index (Eq.refl ds₁)) { val := is, property := h }))) eq def assoc_right {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast sorry def assoc_left {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast sorry theorem take_take {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : take (assoc_right t) = take (take t) := sorry theorem drop_take {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : take (drop (assoc_right t)) = drop (take t) := sorry theorem drop_drop {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : drop (drop (assoc_right t)) = drop t := sorry end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds : List ℕ) := holor_index ds → α namespace holor protected instance inhabited {α : Type} {ds : List ℕ} [Inhabited α] : Inhabited (holor α ds) := { default := fun (t : holor_index ds) => Inhabited.default } protected instance has_zero {α : Type} {ds : List ℕ} [HasZero α] : HasZero (holor α ds) := { zero := fun (t : holor_index ds) => 0 } protected instance has_add {α : Type} {ds : List ℕ} [Add α] : Add (holor α ds) := { add := fun (x y : holor α ds) (t : holor_index ds) => x t + y t } protected instance has_neg {α : Type} {ds : List ℕ} [Neg α] : Neg (holor α ds) := { neg := fun (a : holor α ds) (t : holor_index ds) => -a t } protected instance add_semigroup {α : Type} {ds : List ℕ} [add_semigroup α] : add_semigroup (holor α ds) := add_semigroup.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_semigroup.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry protected instance add_comm_semigroup {α : Type} {ds : List ℕ} [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := add_comm_semigroup.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_semigroup.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry sorry protected instance add_monoid {α : Type} {ds : List ℕ} [add_monoid α] : add_monoid (holor α ds) := add_monoid.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_monoid.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_monoid.zero) sorry sorry protected instance add_comm_monoid {α : Type} {ds : List ℕ} [add_comm_monoid α] : add_comm_monoid (holor α ds) := add_comm_monoid.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_monoid.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_comm_monoid.zero) sorry sorry sorry protected instance add_group {α : Type} {ds : List ℕ} [add_group α] : add_group (holor α ds) := add_group.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_group.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_group.zero) sorry sorry (fun (ᾰ : holor α ds) => id fun (ᾰ_1 : holor_index ds) => add_group.neg (ᾰ ᾰ_1)) (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_group.sub (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry protected instance add_comm_group {α : Type} {ds : List ℕ} [add_comm_group α] : add_comm_group (holor α ds) := add_comm_group.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_group.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_comm_group.zero) sorry sorry (fun (ᾰ : holor α ds) => id fun (ᾰ_1 : holor_index ds) => add_comm_group.neg (ᾰ ᾰ_1)) (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_group.sub (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry sorry /- scalar product -/ protected instance has_scalar {α : Type} {ds : List ℕ} [Mul α] : has_scalar α (holor α ds) := has_scalar.mk fun (a : α) (x : holor α ds) (t : holor_index ds) => a * x t protected instance semimodule {α : Type} {ds : List ℕ} [semiring α] : semimodule α (holor α ds) := pi.semimodule (holor_index ds) (fun (ᾰ : holor_index ds) => α) α /-- The tensor product of two holors. -/ def mul {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [s : Mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := fun (t : holor_index (ds₁ ++ ds₂)) => x (holor_index.take t) * y (holor_index.drop t) theorem cast_type {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = fun (t : holor_index ds₂) => a (cast (congr_arg holor_index (Eq.symm eq)) t) := eq.drec (Eq.refl (cast (congr_arg (holor α) (Eq.refl ds₁)) a)) eq def assoc_right {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast sorry def assoc_left {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast sorry theorem mul_assoc0 {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z = assoc_left (mul x (mul y z)) := sorry theorem mul_assoc {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == mul x (mul y z) := sorry theorem mul_left_distrib {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : mul x (y + z) = mul x y + mul x z := funext fun (t : holor_index (ds₁ ++ ds₂)) => left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t)) theorem mul_right_distrib {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : mul (x + y) z = mul x z + mul y z := funext fun (t : holor_index (ds₁ ++ ds₂)) => right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t)) @[simp] theorem zero_mul {ds₁ : List ℕ} {ds₂ : List ℕ} {α : Type} [ring α] (x : holor α ds₂) : mul 0 x = 0 := funext fun (t : holor_index (ds₁ ++ ds₂)) => zero_mul (x (holor_index.drop t)) @[simp] theorem mul_zero {ds₁ : List ℕ} {ds₂ : List ℕ} {α : Type} [ring α] (x : holor α ds₁) : mul x 0 = 0 := funext fun (t : holor_index (ds₁ ++ ds₂)) => mul_zero (x (holor_index.take t)) theorem mul_scalar_mul {α : Type} {ds : List ℕ} [monoid α] (x : holor α []) (y : holor α ds) : mul x y = x { val := [], property := list.forall₂.nil } • y := sorry /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice {α : Type} {d : ℕ} {ds : List ℕ} (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := fun (is : holor_index ds) => x { val := i :: subtype.val is, property := sorry } /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec {α : Type} [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := fun (ti : holor_index [d]) => ite (subtype.val ti = [j]) 1 0 theorem holor_index_cons_decomp {d : ℕ} {ds : List ℕ} (p : holor_index (d :: ds) → Prop) (t : holor_index (d :: ds)) : (∀ (i : ℕ) (is : List ℕ) (h : subtype.val t = i :: is), p { val := i :: is, property := eq.mpr (id (Eq._oldrec (Eq.refl (list.forall₂ Less (i :: is) (d :: ds))) (Eq.symm h))) (subtype.property t) }) → p t := sorry /-- Two holors are equal if all their slices are equal. -/ theorem slice_eq {α : Type} {d : ℕ} {ds : List ℕ} (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := sorry theorem slice_unit_vec_mul {α : Type} {d : ℕ} {ds : List ℕ} [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (mul (unit_vec d j) x) i hid = ite (i = j) x 0 := sorry theorem slice_add {α : Type} {d : ℕ} {ds : List ℕ} [Add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := sorry theorem slice_zero {α : Type} {d : ℕ} {ds : List ℕ} [HasZero α] (i : ℕ) (hid : i < d) : slice 0 i hid = 0 := rfl theorem slice_sum {α : Type} {d : ℕ} {ds : List ℕ} [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : (finset.sum s fun (x : β) => slice (f x) i hid) = slice (finset.sum s fun (x : β) => f x) i hid := sorry /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] theorem sum_unit_vec_mul_slice {α : Type} {d : ℕ} {ds : List ℕ} [ring α] (x : holor α (d :: ds)) : (finset.sum (finset.attach (finset.range d)) fun (i : Subtype fun (x : ℕ) => x ∈ finset.range d) => mul (unit_vec d ↑i) (slice x (↑i) (nat.succ_le_of_lt (iff.mp finset.mem_range (subtype.prop i))))) = x := sorry /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 {α : Type} [Mul α] : {ds : List ℕ} → holor α ds → Prop where | nil : ∀ (x : holor α []), cprank_max1 x | cons : ∀ {d : ℕ} {ds : List ℕ} (x : holor α [d]) (y : holor α ds), cprank_max1 y → cprank_max1 (mul x y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max {α : Type} [Mul α] [add_monoid α] : ℕ → {ds : List ℕ} → holor α ds → Prop where | zero : ∀ {ds : List ℕ}, cprank_max 0 0 | succ : ∀ (n : ℕ) {ds : List ℕ} (x y : holor α ds), cprank_max1 x → cprank_max n y → cprank_max (n + 1) (x + y) theorem cprank_max_nil {α : Type} [monoid α] [add_monoid α] (x : holor α []) : cprank_max 1 x := sorry theorem cprank_max_1 {α : Type} {ds : List ℕ} [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := sorry theorem cprank_max_add {α : Type} {ds : List ℕ} [monoid α] [add_monoid α] {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds} : cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) := sorry theorem cprank_max_mul {α : Type} {d : ℕ} {ds : List ℕ} [ring α] (n : ℕ) (x : holor α [d]) (y : holor α ds) : cprank_max n y → cprank_max n (mul x y) := sorry theorem cprank_max_sum {α : Type} {ds : List ℕ} [ring α] {β : Type u_1} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ (x : β), x ∈ s → cprank_max n (f x)) → cprank_max (finset.card s * n) (finset.sum s fun (x : β) => f x) := sorry theorem cprank_max_upper_bound {α : Type} [ring α] {ds : List ℕ} (x : holor α ds) : cprank_max (list.prod ds) x := sorry /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ def cprank {α : Type} {ds : List ℕ} [ring α] (x : holor α ds) : ℕ := nat.find sorry theorem cprank_upper_bound {α : Type} [ring α] {ds : List ℕ} (x : holor α ds) : cprank x ≤ list.prod ds := nat.find_min' (Exists.intro (list.prod ds) ((fun (this : cprank_max (list.prod ds) x) => this) (cprank_max_upper_bound x))) (cprank_max_upper_bound x)
9b5971d7a942ddec92a002f3e746ef1d98b17f17
ec5a7ae10c533e1b1f4b0bc7713e91ecf829a3eb
/ijcar16/examples/cc12.lean
87d8c5a0202af949dc29da050059afa65c793247
[ "MIT" ]
permissive
leanprover/leanprover.github.io
cf248934af7c7e9aeff17cf8df3c12c5e7e73f1a
071a20d2e059a2c3733e004c681d3949cac3c07a
refs/heads/master
1,692,621,047,417
1,691,396,994,000
1,691,396,994,000
19,366,263
18
27
MIT
1,693,989,071,000
1,399,006,345,000
Lean
UTF-8
Lean
false
false
894
lean
/- Example/test file for the congruence closure procedure described in the paper: "Congruence Closure for Intensional Type Theory" Daniel Selsam and Leonardo de Moura The tactic `by blast` has been configured in this file to use just the congruence closure procedure using the command set_option blast.strategy "cc" -/ set_option blast.strategy "cc" example (p : nat → nat → Prop) (f : nat → nat) (a b c d : nat) : p (f a) (f b) → a = c → b = d → b = c → p (f c) (f c) := by blast example (p : nat → nat → Prop) (a b c d : nat) : p a b → a = c → b = d → p c d := by blast example (p : nat → nat → Prop) (f : nat → nat) (a b c d : nat) : p (f (f (f (f (f (f a)))))) (f (f (f (f (f (f b)))))) → a = c → b = d → b = c → p (f (f (f (f (f (f c)))))) (f (f (f (f (f (f c)))))) := by blast
d08900a722bcc51f92716f4338835aa734ca80a0
46125763b4dbf50619e8846a1371029346f4c3db
/src/ring_theory/free_comm_ring.lean
a1e27a32d37f71ea4871a4f762acdb007ed92434
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
15,569
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import group_theory.free_abelian_group data.equiv.algebra data.equiv.functor data.polynomial import ring_theory.ideal_operations ring_theory.free_ring noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v variables (α : Type u) def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [comm_ring β] (f : α → β) def lift : free_comm_ring α → β := free_abelian_group.lift $ λ s, (s.map f).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv { to_lhs, dsimp only [(*), mul_zero_class.mul, semiring.mul, ring.mul, semigroup.mul, comm_ring.mul] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end instance : is_ring_hom (lift f) := { map_one := lift_one f, map_mul := lift_mul f, map_add := lift_add f } @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := is_semiring_hom.map_pow _ x n @[simp] lemma lift_comp_of (f : free_comm_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_comm_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) def map : free_comm_ring α → free_comm_ring β := lift $ of ∘ f @[simp] lemma map_zero : map f 0 = 0 := rfl @[simp] lemma map_one : map f 1 = 1 := rfl @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ @[simp] lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ @[simp] lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ @[simp] lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ @[simp] lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ @[simp] lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.mono_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem _ theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem _ theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported def restriction (s : set α) [decidable_pred s] (x : free_comm_ring α) : free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) x section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ @[simp] lemma restriction_zero : restriction s 0 = 0 := lift_zero _ @[simp] lemma restriction_one : restriction s 1 = 1 := lift_one _ @[simp] lemma restriction_add : restriction s (x + y) = restriction s x + restriction s y := lift_add _ _ _ @[simp] lemma restriction_neg : restriction s (-x) = -restriction s x := lift_neg _ _ @[simp] lemma restriction_sub : restriction s (x - y) = restriction s x - restriction s y := lift_sub _ _ _ @[simp] lemma restriction_mul : restriction s (x * y) = restriction s x * restriction s y := lift_mul _ _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin classical, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [lift_one], norm_cast }, { use -1, rw [lift_neg, lift_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [lift_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [lift_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw polynomial.int_cast_eq_C at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg one_ne_zero, polynomial.coeff_X, if_pos rfl] at this, apply_instance end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map subtype.val (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw restriction_one, refl }, { rw [restriction_neg, map_neg, restriction_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, restriction_of, dif_pos hps, map_mul, map_of, ih] }, { intros x y ihx ihy, rw [restriction_add, map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ finset.mem_singleton_self _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, set.finite_union hfs hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa finset.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) def to_free_comm_ring {α} : free_ring α → free_comm_ring α := free_ring.lift free_comm_ring.of instance to_free_comm_ring.is_ring_hom : is_ring_hom (@to_free_comm_ring α) := free_ring.is_ring_hom free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom _ @[simp] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := free_ring.lift_neg _ _ @[simp] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := free_ring.lift_add _ _ _ @[simp] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := free_ring.lift_sub _ _ _ @[simp] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := free_ring.lift_mul _ _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact free_ring.lift_add _ _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact free_ring.lift_mul _ _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := begin funext, apply @free_abelian_group.lift.ext _ _ _ (coe : free_ring α → free_comm_ring α) _ _ (free_abelian_group.lift.is_add_group_hom _), intros x, change free_ring.lift free_comm_ring.of (free_abelian_group.of x) = _, change _ = free_abelian_group.of (↑x), induction x with hd tl ih, {refl}, simp only [*, free_ring.lift, free_comm_ring.of, free_abelian_group.of, free_abelian_group.lift, free_group.of, free_group.to_group, free_group.to_group.aux, mul_one, free_group.quot_lift_mk, abelianization.lift.of, bool.cond_tt, list.prod_cons, cond, list.prod_nil, list.map] at *, refl end def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @ring_equiv.of' (free_ring α) (free_comm_ring α) _ _ (@functor.map_equiv _ _ free_abelian_group _ _ $ multiset.subsingleton_equiv α) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by rw [← (subsingleton_equiv_free_comm_ring α).left_inv (y * x), is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, mul_comm, ← is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, (subsingleton_equiv_free_comm_ring α).left_inv], .. free_ring.ring α } end free_ring def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ coe free_comm_ring.of, map_mul' := λ _ _, is_ring_hom.map_mul _, map_add' := λ _ _, is_ring_hom.map_add _, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := @@is_ring_hom.is_semiring_hom _ _ _ (@@int.cast.is_ring_hom _), refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, rw [free_abelian_group.lift.of], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ coe free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [free_comm_ring.lift_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [free_comm_ring.lift_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, int.cast_neg, int.cast_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [free_comm_ring.lift_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := @@is_ring_hom.is_semiring_hom _ _ _ (@@int.cast.is_ring_hom _), have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) ↑i = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [int.cast_zero, free_comm_ring.lift_zero, mv_polynomial.C_0]) (λ i ih, by rw [int.cast_add, int.cast_one, free_comm_ring.lift_add, free_comm_ring.lift_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [int.cast_sub, int.cast_one, free_comm_ring.lift_sub, free_comm_ring.lift_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, free_comm_ring.lift_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, free_comm_ring.lift_mul, free_comm_ring.lift_of, ih] } end } def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
72c67c35fd166cd6609f31b3617be30c15fe6af9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/special_functions/arctan.lean
2d10fb0a4c1894f22319f4e97a20d41d581825e2
[ "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
781
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.special_functions.trigonometric.arctan import measure_theory.constructions.borel_space.basic /-! # Measurability of arctan > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace real @[measurability] lemma measurable_arctan : measurable arctan := continuous_arctan.measurable end real section real_composition open real variables {α : Type*} {m : measurable_space α} {f : α → ℝ} (hf : measurable f) @[measurability] lemma measurable.arctan : measurable (λ x, arctan (f x)) := measurable_arctan.comp hf end real_composition
6ce1d9744c46721323c8c5b1e3d9bd0c898db3ff
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/equiv/transfer_instance.lean
82d66799c069ddbedb53bbcc7b7d60fd3ad0ff24
[ "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
16,384
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.algebra.basic import algebra.field.basic import algebra.group.type_tags import logic.equiv.basic import ring_theory.ideal.local_ring /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ## Tags equiv, group, ring, field, module, algebra -/ universes u v variables {α : Type u} {β : Type v} namespace equiv section instances variables (e : α ≃ β) /-- Transfer `has_one` across an `equiv` -/ @[to_additive "Transfer `has_zero` across an `equiv`"] protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ @[to_additive] lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl /-- Transfer `has_mul` across an `equiv` -/ @[to_additive "Transfer `has_add` across an `equiv`"] protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ @[to_additive] lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl /-- Transfer `has_div` across an `equiv` -/ @[to_additive "Transfer `has_sub` across an `equiv`"] protected def has_div [has_div β] : has_div α := ⟨λ x y, e.symm (e x / e y)⟩ @[to_additive] lemma div_def [has_div β] (x y : α) : @has_div.div _ (equiv.has_div e) x y = e.symm (e x / e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ @[to_additive "Transfer `has_neg` across an `equiv`"] protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ @[to_additive] lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl /-- Transfer `has_smul` across an `equiv` -/ protected def has_smul (R : Type*) [has_smul R β] : has_smul R α := ⟨λ r x, e.symm (r • (e x))⟩ lemma smul_def {R : Type*} [has_smul R β] (r : R) (x : α) : @has_smul.smul _ _ (e.has_smul R) r x = e.symm (r • (e x)) := rfl /-- Transfer `has_pow` across an `equiv` -/ @[to_additive has_smul] protected def has_pow (N : Type*) [has_pow β N] : has_pow α N := ⟨λ x n, e.symm (e x ^ n)⟩ lemma pow_def {N : Type*} [has_pow β N] (n : N) (x : α) : @has_pow.pow _ _ (e.has_pow N) x n = e.symm (e x ^ n) := rfl /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ @[to_additive "An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β` where the additive structure on `α` is the one obtained by transporting an additive structure on `β` back along `e`."] def mul_equiv (e : α ≃ β) [has_mul β] : by { letI := equiv.has_mul e, exact α ≃* β } := begin introsI, exact { map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) : (mul_equiv e) a = e a := rfl @[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) : by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } := begin intros, refl, end /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } := begin introsI, exact { map_add' := λ x y, by { apply e.symm.injective, simp, refl, }, map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) : (ring_equiv e) a = e a := rfl lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } := begin intros, refl, end /-- Transfer `semigroup` across an `equiv` -/ @[to_additive "Transfer `add_semigroup` across an `equiv`"] protected def semigroup [semigroup β] : semigroup α := let mul := e.has_mul in by resetI; apply e.injective.semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `semigroup_with_zero` across an `equiv` -/ protected def semigroup_with_zero [semigroup_with_zero β] : semigroup_with_zero α := let mul := e.has_mul, zero := e.has_zero in by resetI; apply e.injective.semigroup_with_zero _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semigroup` across an `equiv` -/ @[to_additive "Transfer `add_comm_semigroup` across an `equiv`"] protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := let mul := e.has_mul in by resetI; apply e.injective.comm_semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_class` across an `equiv` -/ protected def mul_zero_class [mul_zero_class β] : mul_zero_class α := let zero := e.has_zero, mul := e.has_mul in by resetI; apply e.injective.mul_zero_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_one_class` across an `equiv` -/ @[to_additive "Transfer `add_zero_class` across an `equiv`"] protected def mul_one_class [mul_one_class β] : mul_one_class α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.mul_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_one_class` across an `equiv` -/ protected def mul_zero_one_class [mul_zero_one_class β] : mul_zero_one_class α := let zero := e.has_zero, one := e.has_one,mul := e.has_mul in by resetI; apply e.injective.mul_zero_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `monoid` across an `equiv` -/ @[to_additive "Transfer `add_monoid` across an `equiv`"] protected def monoid [monoid β] : monoid α := let one := e.has_one, mul := e.has_mul, pow := e.has_pow ℕ in by resetI; apply e.injective.monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_monoid` across an `equiv` -/ @[to_additive "Transfer `add_comm_monoid` across an `equiv`"] protected def comm_monoid [comm_monoid β] : comm_monoid α := let one := e.has_one, mul := e.has_mul, pow := e.has_pow ℕ in by resetI; apply e.injective.comm_monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `group` across an `equiv` -/ @[to_additive "Transfer `add_group` across an `equiv`"] protected def group [group β] : group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div, npow := e.has_pow ℕ, zpow := e.has_pow ℤ in by resetI; apply e.injective.group _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_group` across an `equiv` -/ @[to_additive "Transfer `add_comm_group` across an `equiv`"] protected def comm_group [comm_group β] : comm_group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div, npow := e.has_pow ℕ, zpow := e.has_pow ℤ in by resetI; apply e.injective.comm_group _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_semiring` across an `equiv` -/ protected def non_unital_non_assoc_semiring [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, nsmul := e.has_smul ℕ in by resetI; apply e.injective.non_unital_non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_semiring` across an `equiv` -/ protected def non_unital_semiring [non_unital_semiring β] : non_unital_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, nsmul := e.has_smul ℕ in by resetI; apply e.injective.non_unital_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `add_monoid_with_one` across an `equiv` -/ protected def add_monoid_with_one [add_monoid_with_one β] : add_monoid_with_one α := { nat_cast := λ n, e.symm n, nat_cast_zero := show e.symm _ = _, by simp [zero_def], nat_cast_succ := λ n, show e.symm _ = e.symm (e (e.symm _) + _), by simp [add_def, one_def], .. e.add_monoid, .. e.has_one } /-- Transfer `add_group_with_one` across an `equiv` -/ protected def add_group_with_one [add_group_with_one β] : add_group_with_one α := { int_cast := λ n, e.symm n, int_cast_of_nat := λ n, by rw [int.cast_coe_nat]; refl, int_cast_neg_succ_of_nat := λ n, congr_arg e.symm $ (int.cast_neg_succ_of_nat _).trans $ congr_arg _ (e.apply_symm_apply _).symm, .. e.add_monoid_with_one, .. e.add_group } /-- Transfer `non_assoc_semiring` across an `equiv` -/ protected def non_assoc_semiring [non_assoc_semiring β] : non_assoc_semiring α := let mul := e.has_mul, add_monoid_with_one := e.add_monoid_with_one in by resetI; apply e.injective.non_assoc_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `semiring` across an `equiv` -/ protected def semiring [semiring β] : semiring α := let mul := e.has_mul, add_monoid_with_one := e.add_monoid_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_comm_semiring` across an `equiv` -/ protected def non_unital_comm_semiring [non_unital_comm_semiring β] : non_unital_comm_semiring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, nsmul := e.has_smul ℕ in by resetI; apply e.injective.non_unital_comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semiring` across an `equiv` -/ protected def comm_semiring [comm_semiring β] : comm_semiring α := let mul := e.has_mul, add_monoid_with_one := e.add_monoid_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_non_assoc_ring` across an `equiv` -/ protected def non_unital_non_assoc_ring [non_unital_non_assoc_ring β] : non_unital_non_assoc_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, nsmul := e.has_smul ℕ, zsmul := e.has_smul ℤ in by resetI; apply e.injective.non_unital_non_assoc_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_ring` across an `equiv` -/ protected def non_unital_ring [non_unital_ring β] : non_unital_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, nsmul := e.has_smul ℕ, zsmul := e.has_smul ℤ in by resetI; apply e.injective.non_unital_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_assoc_ring` across an `equiv` -/ protected def non_assoc_ring [non_assoc_ring β] : non_assoc_ring α := let add_group_with_one := e.add_group_with_one, mul := e.has_mul in by resetI; apply e.injective.non_assoc_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `ring` across an `equiv` -/ protected def ring [ring β] : ring α := let mul := e.has_mul, add_group_with_one := e.add_group_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.ring _; intros; exact e.apply_symm_apply _ /-- Transfer `non_unital_comm_ring` across an `equiv` -/ protected def non_unital_comm_ring [non_unital_comm_ring β] : non_unital_comm_ring α := let zero := e.has_zero, add := e.has_add, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, nsmul := e.has_smul ℕ, zsmul := e.has_smul ℤ in by resetI; apply e.injective.non_unital_comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_ring` across an `equiv` -/ protected def comm_ring [comm_ring β] : comm_ring α := let mul := e.has_mul, add_group_with_one := e.add_group_with_one, npow := e.has_pow ℕ in by resetI; apply e.injective.comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `nontrivial` across an `equiv` -/ protected theorem nontrivial [nontrivial β] : nontrivial α := e.surjective.nontrivial /-- Transfer `is_domain` across an `equiv` -/ protected theorem is_domain [ring α] [ring β] [is_domain β] (e : α ≃+* β) : is_domain α := function.injective.is_domain e.to_ring_hom e.injective /-- Transfer `has_rat_cast` across an `equiv` -/ protected def has_rat_cast [has_rat_cast β] : has_rat_cast α := { rat_cast := λ n, e.symm n } /-- Transfer `division_ring` across an `equiv` -/ protected def division_ring [division_ring β] : division_ring α := let add_group_with_one := e.add_group_with_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div, mul := e.has_mul, npow := e.has_pow ℕ, zpow := e.has_pow ℤ, rat_cast := e.has_rat_cast, qsmul := e.has_smul ℚ in by resetI; apply e.injective.division_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `field` across an `equiv` -/ protected def field [field β] : field α := let add_group_with_one := e.add_group_with_one, mul := e.has_mul, neg := e.has_neg, inv := e.has_inv, div := e.has_div, mul := e.has_mul, npow := e.has_pow ℕ, zpow := e.has_pow ℤ, rat_cast := e.has_rat_cast, qsmul := e.has_smul ℚ in by resetI; apply e.injective.field _; intros; exact e.apply_symm_apply _ section R variables (R : Type*) include R section variables [monoid R] /-- Transfer `mul_action` across an `equiv` -/ protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α := { one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_smul], ..e.has_smul R } /-- Transfer `distrib_mul_action` across an `equiv` -/ protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [distrib_mul_action R β], distrib_mul_action R α end := begin intros, letI := equiv.add_comm_monoid e, exact ( { smul_zero := by simp [zero_def, smul_def], smul_add := by simp [add_def, smul_def, smul_add], ..equiv.mul_action R e } : distrib_mul_action R α) end end section variables [semiring R] /-- Transfer `module` across an `equiv` -/ protected def module (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [module R β], module R α end := begin introsI, exact ( { zero_smul := by simp [zero_def, smul_def], add_smul := by simp [add_def, smul_def, add_smul], ..equiv.distrib_mul_action R e } : module R α) end /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linear_equiv (e : α ≃ β) [add_comm_monoid β] [module R β] : begin letI := equiv.add_comm_monoid e, letI := equiv.module R e, exact α ≃ₗ[R] β end := begin introsI, exact { map_smul' := λ r x, by { apply e.symm.injective, simp, refl, }, ..equiv.add_equiv e } end end section variables [comm_semiring R] /-- Transfer `algebra` across an `equiv` -/ protected def algebra (e : α ≃ β) [semiring β] : begin letI := equiv.semiring e, exact Π [algebra R β], algebra R α end := begin introsI, fapply ring_hom.to_algebra', { exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), }, { intros r x, simp only [function.comp_app, ring_hom.coe_comp], have p := ring_equiv_symm_apply e, dsimp at p, erw p, clear p, apply (ring_equiv e).injective, simp only [(ring_equiv e).map_mul], simp [algebra.commutes], } end /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] : begin letI := equiv.semiring e, letI := equiv.algebra R e, exact α ≃ₐ[R] β end := begin introsI, exact { commutes' := λ r, by { apply e.symm.injective, simp, refl, }, ..equiv.ring_equiv e } end end end R end instances end equiv namespace ring_equiv protected lemma local_ring {A B : Type*} [comm_semiring A] [local_ring A] [comm_semiring B] (e : A ≃+* B) : local_ring B := begin haveI := e.symm.to_equiv.nontrivial, exact local_ring.of_surjective (e : A →+* B) e.surjective end end ring_equiv
155e0c1920afadebfa6c23d1580614e86f991f2d
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/data/holor.lean
9f4f037306ded9e339ff8e163e042ae0125b7365
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
14,342
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.pi_instances /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in https://www.isa-afp.org/entries/Deep_Learning.html. ## References * https://en.wikipedia.org/wiki/Tensor_rank_decomposition -/ universes u open list /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [ring α] : module α (holor α ds) := pi.module α instance [discrete_field α] : vector_space α (holor α ds) := ⟨α, holor α ds⟩ /-- The tensor product of two holors. -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) : Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := funext (λ t, by simp [slice]; refl) lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : finset.sum s (λ x, slice (f x) i hid) = slice (finset.sum s f) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : (finset.range d).attach.sum (λ i, unit_vec d i.1 ⊗ slice x i.1 (nat.succ_le_of_lt (finset.mem_range.1 i.2))) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i _), { simp, refl }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b.val, { apply not.imp hbi, { assume h0 : i = b.val, apply subtype.eq, simp only [h0] }, { exact finset.mem_range.2 hid } }, simp [hbi']}, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (finset.sum s f) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (finset.sum s f), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
0a972c1eed9f567cb0fa32bbbf841c569c119d12
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/direct_sum/algebra.lean
23d6d4979d8be8d66e1f72065ebc346a61c40a8e
[ "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
7,059
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.direct_sum.ring import algebra.direct_sum.module /-! # Additively-graded algebra structures on `⨁ i, A i` This file provides `R`-algebra structures on external direct sums of `R`-modules. Recall that if `A i` are a family of `add_comm_monoid`s indexed by an `add_monoid`, then an instance of `direct_sum.gmonoid A` is a multiplication `A i → A j → A (i + j)` giving `⨁ i, A i` the structure of a semiring. In this file, we introduce the `direct_sum.galgebra R A` class for the case where all `A i` are `R`-modules. This is the extra structure needed to promote `⨁ i, A i` to an `R`-algebra. ## Main definitions * `direct_sum.galgebra R A`, the typeclass. * `direct_sum.galgebra.of_submodules`, for creating the above instance from a collection of submodules. * `direct_sum.to_algebra` extends `direct_sum.to_semiring` to produce an `alg_hom`. ## Direct sums of subobjects Additionally, this module provides the instance `direct_sum.galgebra.of_submodules` which promotes any instance constructed with `direct_sum.gmonoid.of_submodules` to an `R`-algebra. -/ universes uι uR uA uB variables {ι : Type uι} namespace direct_sum open_locale direct_sum variables (R : Type uR) (A : ι → Type uA) {B : Type uB} [decidable_eq ι] variables [comm_semiring R] [Π i, add_comm_monoid (A i)] [Π i, module R (A i)] variables [add_monoid ι] [gmonoid A] section local attribute [instance] ghas_one.to_sigma_has_one local attribute [instance] ghas_mul.to_sigma_has_mul /-- A graded version of `algebra`. An instance of `direct_sum.galgebra R A` endows `(⨁ i, A i)` with an `R`-algebra structure. -/ class galgebra := (to_fun : R →+ A 0) (map_one : to_fun 1 = ghas_one.one) (map_mul : ∀ r s, (⟨_, to_fun (r * s)⟩ : Σ i, A i) = ⟨_, ghas_mul.mul (to_fun r) (to_fun s)⟩) (commutes : ∀ r x, (⟨_, to_fun (r)⟩ : Σ i, A i) * x = x * ⟨_, to_fun (r)⟩) (smul_def : ∀ r (x : Σ i, A i), (⟨x.1, r • x.2⟩ : Σ i, A i) = ⟨_, to_fun (r)⟩ * x) end variables [semiring B] [galgebra R A] [algebra R B] instance : algebra R (⨁ i, A i) := { to_fun := (direct_sum.of A 0).comp galgebra.to_fun, map_zero' := add_monoid_hom.map_zero _, map_add' := add_monoid_hom.map_add _, map_one' := (direct_sum.of A 0).congr_arg galgebra.map_one, map_mul' := λ a b, begin simp only [add_monoid_hom.comp_apply], rw of_mul_of, apply dfinsupp.single_eq_of_sigma_eq (galgebra.map_mul a b), end, commutes' := λ r x, begin change add_monoid_hom.mul (direct_sum.of _ _ _) x = add_monoid_hom.mul.flip (direct_sum.of _ _ _) x, apply add_monoid_hom.congr_fun _ x, ext i xi : 2, dsimp only [add_monoid_hom.comp_apply, add_monoid_hom.mul_apply, add_monoid_hom.flip_apply], rw [of_mul_of, of_mul_of], apply dfinsupp.single_eq_of_sigma_eq (galgebra.commutes r ⟨i, xi⟩), end, smul_def' := λ r x, begin change distrib_mul_action.to_add_monoid_hom _ r x = add_monoid_hom.mul (direct_sum.of _ _ _) x, apply add_monoid_hom.congr_fun _ x, ext i xi : 2, dsimp only [add_monoid_hom.comp_apply, distrib_mul_action.to_add_monoid_hom_apply, add_monoid_hom.mul_apply], rw [direct_sum.of_mul_of, ←of_smul], apply dfinsupp.single_eq_of_sigma_eq (galgebra.smul_def r ⟨i, xi⟩), end } lemma algebra_map_apply (r : R) : algebra_map R (⨁ i, A i) r = direct_sum.of A 0 (galgebra.to_fun r) := rfl lemma algebra_map_to_add_monoid_hom : ↑(algebra_map R (⨁ i, A i)) = (direct_sum.of A 0).comp (galgebra.to_fun : R →+ A 0) := rfl section -- for `simps` local attribute [simp] linear_map.cod_restrict /-- A `direct_sum.gmonoid` instance produced by `direct_sum.gmonoid.of_submodules` is automatically a `direct_sum.galgebra`. -/ @[simps to_fun_apply {simp_rhs := tt}] instance galgebra.of_submodules (carriers : ι → submodule R B) (one_mem : (1 : B) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : B) ∈ carriers (i + j)) : by haveI : gmonoid (λ i, carriers i) := gmonoid.of_submodules carriers one_mem mul_mem; exact galgebra R (λ i, carriers i) := by exact { to_fun := begin refine ((algebra.linear_map R B).cod_restrict (carriers 0) $ λ r, _).to_add_monoid_hom, exact submodule.one_le.mpr one_mem (submodule.algebra_map_mem _), end, map_one := subtype.ext $ by exact (algebra_map R B).map_one, map_mul := λ x y, sigma.subtype_ext (add_zero 0).symm $ (algebra_map R B).map_mul _ _, commutes := λ r ⟨i, xi⟩, sigma.subtype_ext ((zero_add i).trans (add_zero i).symm) $ algebra.commutes _ _, smul_def := λ r ⟨i, xi⟩, sigma.subtype_ext (zero_add i).symm $ algebra.smul_def _ _ } end /-- A family of `linear_map`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` describes an `alg_hom` on `⨁ i, A i`. This is a stronger version of `direct_sum.to_semiring`. Of particular interest is the case when `A i` are bundled subojects, `f` is the family of coercions such as `submodule.subtype (A i)`, and the `[gmonoid A]` structure originates from `direct_sum.gmonoid.of_add_submodules`, in which case the proofs about `ghas_one` and `ghas_mul` can be discharged by `rfl`. -/ @[simps] def to_algebra (f : Π i, A i →ₗ[R] B) (hone : f _ (ghas_one.one) = 1) (hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (ghas_mul.mul ai aj) = f _ ai * f _ aj) (hcommutes : ∀ r, (f 0) (galgebra.to_fun r) = (algebra_map R B) r) : (⨁ i, A i) →ₐ[R] B := { to_fun := to_semiring (λ i, (f i).to_add_monoid_hom) hone @hmul, commutes' := λ r, (direct_sum.to_semiring_of _ _ _ _ _).trans (hcommutes r), .. to_semiring (λ i, (f i).to_add_monoid_hom) hone @hmul} /-- Two `alg_hom`s out of a direct sum are equal if they agree on the generators. See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext ⦃f g : (⨁ i, A i) →ₐ[R] B⦄ (h : ∀ i, f.to_linear_map.comp (lof _ _ A i) = g.to_linear_map.comp (lof _ _ A i)) : f = g := alg_hom.coe_ring_hom_injective $ direct_sum.ring_hom_ext $ λ i, add_monoid_hom.ext $ linear_map.congr_fun (h i) end direct_sum /-! ### Concrete instances -/ /-- A direct sum of copies of a `algebra` inherits the algebra structure. -/ @[simps] instance algebra.direct_sum_galgebra {R A : Type*} [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A] : direct_sum.galgebra R (λ i : ι, A) := { to_fun := (algebra_map R A).to_add_monoid_hom, map_one := (algebra_map R A).map_one, map_mul := λ a b, sigma.ext (zero_add _).symm (heq_of_eq $ (algebra_map R A).map_mul a b), commutes := λ r ⟨ai, a⟩, sigma.ext ((zero_add _).trans (add_zero _).symm) (heq_of_eq $ algebra.commutes _ _), smul_def := λ r ⟨ai, a⟩, sigma.ext (zero_add _).symm (heq_of_eq $ algebra.smul_def _ _) } namespace submodule variables {R A : Type*} [comm_semiring R] end submodule
e60d234853192d66c1be8e90b058387bd40c7e68
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/giry_monad.lean
5b0ecc62bdb3c1fcccbfdaa62da1be16d10c0f8d
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,007
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import measure_theory.integration /-! # The Giry monad Let X be a measurable space. The collection of all measures on X again forms a measurable space. This construction forms a monad on measurable spaces and measurable functions, called the Giry monad. Note that most sources use the term "Giry monad" for the restriction to *probability* measures. Here we include all measures on X. See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level monad to an honest monad of the functor `Measure : Meas ⥤ Meas`. ## References * <https://ncatlab.org/nlab/show/Giry+monad> ## Tags giry monad -/ noncomputable theory open_locale classical big_operators open classical set filter variables {α β γ δ ε : Type*} namespace measure_theory namespace measure variables [measurable_space α] [measurable_space β] /-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/ instance : measurable_space (measure α) := ⨆ (s : set α) (hs : is_measurable s), (borel ennreal).comap (λμ, μ s) lemma measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : measure α, μ s) := measurable.of_comap_le $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _ lemma measurable_of_measurable_coe (f : β → measure α) (h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) : measurable f := measurable.of_le_map $ bsupr_le $ assume s hs, measurable_space.comap_le_iff_le_map.2 $ by rw [measurable_space.map_comp]; exact h s hs lemma measurable_measure {μ : α → measure β} : measurable μ ↔ ∀(s : set β) (hs : is_measurable s), measurable (λb, μ b s) := ⟨λ hμ s hs, (measurable_coe hs).comp hμ, measurable_of_measurable_coe μ⟩ lemma measurable_map (f : α → β) (hf : measurable f) : measurable (λμ : measure α, map f μ) := measurable_of_measurable_coe _ $ assume s hs, suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)), by simpa [map_apply, hs, hf], measurable_coe (hf hs) lemma measurable_dirac : measurable (measure.dirac : α → measure α) := measurable_of_measurable_coe _ $ assume s hs, begin simp only [dirac_apply', hs], exact measurable_one.indicator hs end lemma measurable_lintegral {f : α → ennreal} (hf : measurable f) : measurable (λμ : measure α, ∫⁻ x, f x ∂μ) := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, simple_func.lintegral], refine measurable_supr (λ n, finset.measurable_sum _ (λ i, _)), refine measurable_const.ennreal_mul _, exact measurable_coe ((simple_func.eapprox f n).is_measurable_preimage _) end /-- Monadic join on `measure` in the category of measurable spaces and measurable functions. -/ def join (m : measure (measure α)) : measure α := measure.of_measurable (λs hs, ∫⁻ μ, μ s ∂m) (by simp) begin assume f hf h, simp [measure_Union h hf], apply lintegral_tsum, assume i, exact measurable_coe (hf i) end @[simp] lemma join_apply {m : measure (measure α)} : ∀{s : set α}, is_measurable s → join m s = ∫⁻ μ, μ s ∂m := measure.of_measurable_apply lemma measurable_join : measurable (join : measure (measure α) → measure α) := measurable_of_measurable_coe _ $ assume s hs, by simp only [join_apply hs]; exact measurable_lintegral (measurable_coe hs) lemma lintegral_join {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) : ∫⁻ x, f x ∂(join m) = ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m := begin rw [lintegral_eq_supr_eapprox_lintegral hf], have : ∀n x, join m (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) = ∫⁻ μ, μ ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x})) ∂m := assume n x, join_apply (simple_func.is_measurable_preimage _ _), simp only [simple_func.lintegral, this], transitivity, have : ∀(s : ℕ → finset ennreal) (f : ℕ → ennreal → measure α → ennreal) (hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, ∑ r in s n, r * f n r μ)), (⨆n:ℕ, ∑ r in s n, r * ∫⁻ μ, f n r μ ∂m) = ∫⁻ μ, ⨆n:ℕ, ∑ r in s n, r * f n r μ ∂m, { assume s f hf hm, symmetry, transitivity, apply lintegral_supr, { assume n, exact finset.measurable_sum _ (assume r, measurable_const.ennreal_mul (hf _ _)) }, { exact hm }, congr, funext n, transitivity, apply lintegral_finset_sum, { assume r, exact measurable_const.ennreal_mul (hf _ _) }, congr, funext r, apply lintegral_const_mul, exact hf _ _ }, specialize this (λn, simple_func.range (simple_func.eapprox f n)), specialize this (λn r μ, μ (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})), refine this _ _; clear this, { assume n r, apply measurable_coe, exact simple_func.is_measurable_preimage _ _ }, { change monotone (λn μ, (simple_func.eapprox f n).lintegral μ), assume n m h μ, refine simple_func.lintegral_mono _ (le_refl _), apply simple_func.monotone_eapprox, assumption }, congr, funext μ, symmetry, apply lintegral_eq_supr_eapprox_lintegral, exact hf end /-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind (m : measure α) (f : α → measure β) : measure β := join (map f m) @[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β} (hs : is_measurable s) (hf : measurable f) : bind m f s = ∫⁻ a, f a s ∂m := by rw [bind, join_apply hs, lintegral_map (measurable_coe hs) hf] lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) := measurable_join.comp (measurable_map _ hg) lemma lintegral_bind {m : measure α} {μ : α → measure β} {f : β → ennreal} (hμ : measurable μ) (hf : measurable f) : ∫⁻ x, f x ∂ (bind m μ) = ∫⁻ a, ∫⁻ x, f x ∂(μ a) ∂m:= (lintegral_join hf).trans (lintegral_map (measurable_lintegral hf) hμ) lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ} (hf : measurable f) (hg : measurable g) : bind (bind m f) g = bind m (λa, bind (f a) g) := measure.ext $ assume s hs, begin rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), lintegral_bind hf], { congr, funext a, exact (bind_apply hs hg).symm }, exact (measurable_coe hs).comp hg end lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a := measure.ext $ λ s hs, by rw [bind_apply hs hf, lintegral_dirac' a ((measurable_coe hs).comp hf)] lemma dirac_bind {m : measure α} : bind m dirac = m := measure.ext $ assume s hs, by simp [bind_apply hs measurable_dirac, dirac_apply' _ hs, lintegral_indicator 1 hs] lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id := by rw [bind, map_id] lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) : join (map (map f) μ) = map f (join μ) := measure.ext $ assume s hs, begin rw [join_apply hs, map_apply hf hs, join_apply, lintegral_map (measurable_coe hs) (measurable_map f hf)], { congr, funext ν, exact map_apply hf hs }, exact hf hs end lemma join_map_join (μ : measure (measure (measure α))) : join (map join μ) = join (join μ) := begin show bind μ join = join (join μ), rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id], apply congr_arg (bind μ), funext ν, exact join_eq_bind ν end lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ := dirac_bind lemma join_dirac (μ : measure α) : join (dirac μ) = μ := eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _) end measure end measure_theory
584658a6eb5fdde931846f2d1ec433101106beac
cb3da1b91380e7462b579b426a278072c688954a
/src/main.lean
18df07057b7333bac492f5abaa943ee79e419e17
[]
no_license
hcheval/tikhonov-mann
35c93e46a8287f6479a848a9d4f02013e0bc2035
6ab7fcefe9e1156c20bd5d1998a7deabd1eeb018
refs/heads/master
1,689,232,126,344
1,630,182,255,000
1,630,182,255,000
399,859,996
0
0
null
null
null
null
UTF-8
Lean
false
false
31
lean
import iteration #check @l_5_3
d925526c2893dcc8245b468376b7aa16c14ee918
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/pseudo_normed_group/breen_deligne.lean
0e2b5bb7fa04b97df8c14b7f30dc3c16561b6e5c
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,708
lean
import pseudo_normed_group.basic import breen_deligne noncomputable theory local attribute [instance] type_pow open_locale nnreal big_operators matrix namespace breen_deligne namespace basic_universal_map variables {m n : ℕ} (f : basic_universal_map m n) variables (M : Type*) [pseudo_normed_group M] open add_monoid_hom pseudo_normed_group def eval_png : (M^m) →+ (M^n) := mk_to_pi $ λ j, mk_from_pi $ λ i, const_smul_hom _ $ f j i lemma eval_png_apply (x : M^m) : f.eval_png M x = λ j, ∑ i, f j i • (x i) := begin ext j, simp only [eval_png, coe_mk_from_pi, add_monoid_hom.apply_apply, mk_to_pi_apply, add_monoid_hom.to_fun_eq_coe, fintype.sum_apply, function.comp_app, coe_gsmul, @mk_from_pi_apply M _ (fin m) _ (λ _, M) _ _ x, const_smul_hom_apply] end @[simp] lemma eval_png_zero : (0 : basic_universal_map m n).eval_png M = 0 := by { ext, simp only [eval_png_apply, zero_smul, finset.sum_const_zero, matrix.zero_apply], refl } lemma eval_png_mem_filtration : (f.eval_png M) ∈ filtration ((M^m) →+ (M^n)) (finset.univ.sup $ λ i, ∑ j, (f i j).nat_abs) := begin apply mk_to_pi_mem_filtration, intro j, refine filtration_mono (finset.le_sup (finset.mem_univ j)) (mk_from_pi_mem_filtration _ _), intros i, exact const_smul_hom_int_mem_filtration _ _ le_rfl end lemma eval_png_comp {l m n} (g : basic_universal_map m n) (f : basic_universal_map l m) : (g.comp f).eval_png M = (g.eval_png M).comp (f.eval_png M) := begin ext x j, simp only [eval_png_apply, function.comp_app, coe_comp, basic_universal_map.comp, matrix.mul_apply, finset.smul_sum, finset.sum_smul, mul_smul], rw finset.sum_comm end end basic_universal_map end breen_deligne
ac463af0bd75b6f9fa9a5157418112e18af5ec8b
534c92d7322a8676cfd1583e26f5946134561b54
/src/Exercises/01_Propositions/Q0106/S0006.lean
4d7851c3d7cb6ca392500d047d0e3d77f21305ec
[ "Apache-2.0" ]
permissive
kbuzzard/mathematics-in-lean
53f387174f04d6077f434e27c407aee9425837f7
3fad7bb7e888dabef94921101af8671b78a4304a
refs/heads/master
1,586,812,457,439
1,546,893,744,000
1,546,893,744,000
163,450,734
8
0
null
null
null
null
UTF-8
Lean
false
false
54
lean
theorem very_easy : true := begin exact trivial end
3d305102f0a35be6d633433aac11598ef2056b04
36938939954e91f23dec66a02728db08a7acfcf9
/lean/file_input.lean
fd78a124622305d442250ffa26f390da15995af8
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
1,162
lean
import system.io -- init.category.lift structure file_input_state := (handle : io.handle) (pos : ℕ) (filename : string) -- for reopening /- A monad for dealing with the fact that lean doesn't support seeking backwards -/ @[reducible] def file_input := state_t file_input_state (except_t string io) namespace file_input def new_state (filename : string) : io file_input_state := do hdl <- io.mk_file_handle filename io.mode.read tt, return { handle := hdl, pos := 0, filename := filename } def run_file_input {a} (filename : string) (fr : file_input a) : io (except string a) := do st <- new_state filename, rv <- (fr.run st).run, return (rv.map prod.fst) def read (n:ℕ) : file_input char_buffer := do s <- get, bs <- monad_lift (io.fs.read s.handle n), put { s with pos := s.pos + n }, return bs def seek (n : ℕ) : file_input unit := do s <- get, if s.pos ≤ n then monad_lift (io.fs.read s.handle (n - s.pos)) >> put { pos := n, ..s } else monad_lift (do s' <- new_state s.filename, _ <- io.fs.read s'.handle n, return { pos := n, ..s'}) >>= put end file_input
b2149b2e3d772e0904f617e8d3cf9cd836c9c926
d744d97b07fc1e61b0ebea192b2d624125898128
/src/tree.lean
a562dae273621c853a67fd8d2dffb543244bb3eb
[ "MIT" ]
permissive
parkersullivan/leanstuff
019c757848dd8f5db185e6973969141aee6fef7c
3da132c44d365ecd933de64fa04ba66b9e620683
refs/heads/master
1,599,036,040,845
1,573,316,625,000
1,573,316,625,000
219,181,711
0
0
null
null
null
null
UTF-8
Lean
false
false
890
lean
namespace my_tree inductive tree (α : Type) : Type | empty {} : tree | node : α → tree → tree → tree def sum_node {α : Type} : tree α → ℕ | tree.empty := 0 | (tree.node n t1 t2) := (1 + (sum_node t1) + (sum_node t2)) def tree_map {α β : Type} : (α → β) → tree α → tree β | f tree.empty := tree.empty | f (tree.node n t1 t2) := (tree.node (f n) (tree_map f t1) (tree_map f t2)) def longest_branch {α : Type} : tree α → ℕ | tree.empty := 0 | (tree.node n t1 t2) := 1 + (max (longest_branch t1) (longest_branch t2)) def is_in {α : Type} [decidable_eq α]: tree α → α → bool | tree.empty x := ff | (tree.node n t1 t2) x := if (n = x) then tt else if (is_in t1 x) then tt else if (is_in t2 x) then tt else ff end my_tree
1c3fb7474051f593674ac8d3575b9d8cb0fcbfba
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/path_connected.lean
8dd3653c9473af92ab817a392ed88e12565ff354
[ "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
36,448
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.instances.real /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `I_extend` that will extend any continuous map `γ : I → X` into a continuous map `I_extend γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter open filter set function variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*} /-! ### The unit interval -/ local notation `I` := Icc (0 : ℝ) 1 lemma Icc_zero_one_symm {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance I_has_zero : has_zero I := ⟨⟨0, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_zero : ((0 : I) : ℝ) = 0 := rfl instance I_has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_one : ((1 : I) : ℝ) = 1 := rfl /-- Unit interval central symmetry. -/ def I_symm : I → I := λ t, ⟨1 - t.val, Icc_zero_one_symm.mp t.property⟩ local notation `σ` := I_symm @[simp] lemma I_symm_zero : σ 0 = 1 := subtype.ext $ by simp [I_symm] @[simp] lemma I_symm_one : σ 1 = 0 := subtype.ext $ by simp [I_symm] @[continuity] lemma continuous_I_symm : continuous σ := by continuity! /-- Projection of `ℝ` onto its unit interval. -/ def proj_I : ℝ → I := λ t, if h : t ≤ 0 then ⟨0, left_mem_Icc.mpr zero_le_one⟩ else if h' : t ≤ 1 then ⟨t, ⟨le_of_lt $ not_le.mp h, h'⟩⟩ else ⟨1, right_mem_Icc.mpr zero_le_one⟩ lemma proj_I_I {t : ℝ} (h : t ∈ I) : proj_I t = ⟨t, h⟩ := begin unfold proj_I, rw mem_Icc at h, split_ifs, { simp [show t = 0, by linarith] }, { refl }, { exfalso, linarith } end lemma proj_I_zero : proj_I 0 = 0 := proj_I_I (⟨le_refl 0, zero_le_one⟩) lemma proj_I_one : proj_I 1 = 1 := proj_I_I (⟨zero_le_one, le_refl 1⟩) lemma surjective_proj_I : surjective proj_I := λ ⟨t, t_in⟩, ⟨t, proj_I_I t_in⟩ lemma range_proj_I : range proj_I = univ := surjective_proj_I.range_eq @[continuity] lemma continuous_proj_I : continuous proj_I := begin refine continuous_induced_rng' (coe : I → ℝ) rfl _, have : continuous (λ t : ℝ, if t ≤ 0 then 0 else if t ≤ 1 then t else 1), { refine continuous_if _ continuous_const (continuous_if _ continuous_id continuous_const) ; simp [Iic_def, zero_le_one] }, convert this, ext, dsimp [proj_I], split_ifs ; refl end variables {β : Type*} /-- Extension of a function defined on the unit interval to `ℝ`, by precomposing with the projection. -/ def I_extend {β : Type*} (f : I → β) : ℝ → β := f ∘ proj_I @[continuity] lemma continuous.I_extend {f : I → X} (hf : continuous f) : continuous (I_extend f) := hf.comp continuous_proj_I lemma I_extend_extends (f : I → β) {t : ℝ} (ht : t ∈ I) : I_extend f t = f ⟨t, ht⟩ := by simp [I_extend, proj_I_I, ht] @[simp] lemma I_extend_zero (f : I → β) : I_extend f 0 = f 0 := I_extend_extends _ _ @[simp] lemma I_extend_one (f : I → β) : I_extend f 1 = f 1 := I_extend_extends _ _ @[simp] lemma I_extend_range (f : I → β) : range (I_extend f) = range f := surjective_proj_I.range_comp f instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ instance : compact_space I := compact_iff_compact_space.1 compact_Icc /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_inhabited_instance] structure path (x y : X) := (to_fun : I → X) (continuous' : continuous to_fun) (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) := ⟨_, path.to_fun⟩ @[ext] protected lemma path.ext {X : Type*} [topological_space X] {x y : X} : ∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂ | ⟨x, h11, h12, h13⟩ ⟨.(x), h21, h22, h23⟩ rfl := rfl namespace path variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous' @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/ instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} : has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X := ⟨λ φ p, φ p.1 p.2⟩ /-- The constant path from a point to itself -/ @[refl] def refl (x : X) : path x x := { to_fun := λ t, x, continuous' := continuous_const, source' := rfl, target' := rfl } @[simp] lemma refl_range {X : Type*} [topological_space X] {a : X} : range (path.refl a) = {a} := by simp [path.refl, has_coe_to_fun.coe, coe_fn] /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous' := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } @[simp] lemma refl_symm {X : Type*} [topological_space X] {a : X} : (path.refl a).symm = path.refl a := by { ext, refl } @[simp] lemma symm_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.symm = range γ := begin ext x, simp only [ mem_range, path.symm, has_coe_to_fun.coe, coe_fn, I_symm, set_coe.exists, comp_app, subtype.coe_mk, subtype.val_eq_coe ], split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, Icc_zero_one_symm.mp hy, _⟩; convert hxy, exact sub_sub_cancel _ _ end /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := I_extend γ lemma continuous_extend : continuous γ.extend := γ.continuous.I_extend @[simp] lemma extend_zero : γ.extend 0 = x := by simp [extend] @[simp] lemma extend_one : γ.extend 1 = y := by simp [extend] @[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ := I_extend_extends γ.to_fun ht @[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend ↑t = γ t := by { convert γ.extend_extends t.2, rw subtype.ext_iff_val } @[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.extend = range γ := I_extend_range γ.to_fun lemma extend_le_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a := begin have := γ.source, simpa [path.extend, I_extend, proj_I, ht] end lemma extend_one_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b := begin simp only [path.extend, I_extend, proj_I, comp_app], split_ifs, { exfalso, linarith }, { convert γ.target, linarith }, { exact γ.target } end @[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} : (path.refl a).extend = λ _, a := rfl /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous' := hf.comp_continuous continuous_subtype_coe (by rw subtype.range_coe), source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous' := begin apply (continuous_if _ _ _).comp continuous_subtype_coe, { norm_num }, -- TODO: the following are provable by `continuity` but it is too slow { exact ((path.continuous γ).comp continuous_proj_I).comp (continuous_const.mul continuous_id')}, { exact ((path.continuous γ').comp continuous_proj_I).comp ((continuous_const.mul continuous_id').sub continuous_const) } end, source' := by norm_num, target' := by norm_num } @[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} : (path.refl a).trans (path.refl a) = path.refl a := begin ext, simp only [path.trans, if_t_t, one_div, path.refl_extend], refl end lemma trans_range {X : Type*} [topological_space X] {a b c : X} (γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ := begin rw path.trans, apply eq_of_subset_of_subset, { rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩, by_cases h : t ≤ 1/2, { left, use [2*t, ⟨by linarith, by linarith⟩], rw ← γ₁.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_true] at hxt, exact hxt }, { right, use [2*t-1, ⟨by linarith, by linarith⟩], rw ← γ₂.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_false] at hxt, exact hxt } }, { rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩), { use ⟨t/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, have : t/2 ≤ 1/2 := by linarith, simp only [this, comp_app, if_true], ring, rwa γ₁.extend_extends }, { by_cases h : t = 0, { use ⟨1/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (@two_ne_zero ℝ _)], rw γ₁.extend_one, rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt }, { use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, change t ≠ 0 at h, have ht0 := lt_of_le_of_ne ht0 h.symm, have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith}, simp only [comp_app, if_false, this], ring, rwa γ₂.extend_extends } } } end /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous' := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous' := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X} (γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) : (γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl @[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X} (γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) : (γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).symm) := h.comp (continuous_id.prod_map continuous_I_symm) lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).extend) := h.comp (continuous_id.prod_map continuous_proj_I) lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b c : ι → X} (γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁) (γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) : continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) := begin have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁, have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂, simp [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans], apply continuous_if _ _ _, { rintros st hst, have := frontier_le_subset_eq (continuous_subtype_coe.comp continuous_snd) continuous_const hst, simp only [mem_set_of_eq, comp_app] at this, simp [this, mul_inv_cancel (@two_ne_zero ℝ _)] }, { change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))), exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) }, { change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))), exact h₂'.comp (continuous_id.prod_map $ (continuous_const.mul continuous_subtype_coe).sub continuous_const) }, end /-! #### Truncating a path -/ /-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the time interval `[t₀, t₁]` and stays still otherwise. -/ def truncate {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) := { to_fun := λ s, γ.extend (min (max s t₀) t₁), continuous' := γ.continuous_extend.comp ((continuous_subtype_coe.max continuous_const).min continuous_const), source' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃ h₄, { simp [γ.extend_le_zero h₁] }, { congr, linarith }, { have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂), simp [γ.extend_le_zero h₄, γ.extend_le_zero h₁] }, all_goals { refl } end, target' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃, { simp [γ.extend_one_le h₂] }, { refl }, { have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁), simp [γ.extend_one_le h₄, γ.extend_one_le (h₄.trans h₃)] }, { refl } end } /-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁` casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/ def truncate_of_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) := (γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl lemma truncate_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ := begin rw ← γ.extend_range, simp only [range_subset_iff, set_coe.exists, set_coe.forall], intros x hx, simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self] end /-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/ lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) := (γ.continuous.comp continuous_proj_I).comp (((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min (continuous_fst.comp continuous_snd)) /- TODO : When `continuity` gets quicker, change the proof back to : `begin` `simp only [has_coe_to_fun.coe, coe_fn, path.truncate],` `continuity,` `exact continuous_subtype_coe` `end` -/ lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) := have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id, by convert γ.truncate_continuous_family.comp key @[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min, max], split_ifs with h₁ h₂; congr, linarith end @[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero := by convert γ.truncate_self 0; exact γ.extend_zero.symm @[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one := by convert γ.truncate_self 1; exact γ.extend_one.symm @[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min, max, extend, I_extend, comp_app], congr, have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2, simp [this.1, this.2, proj_I_I this] end end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous' := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, subset_connected_component (is_connected_range h.some_path.continuous).2 ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x y x_in y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x y xU yU).mono (subset_union_left U V) }, { exact (hV.joined_in x y xV yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end lemma is_path_connected.exists_path_through_family {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) := begin let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩, obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s, { have hp' : ∀ i ≤ n, p' i ∈ s, { intros i hi, simp [p', nat.lt_succ_of_le hi, hp] }, clear_value p', clear hp p, induction n with n hn, { use (λ _, p' 0), { continuity }, { split, { rintros i hi, rw nat.le_zero_iff.mp hi, exact ⟨0, rfl⟩ }, { rw range_subset_iff, rintros x, exact hp' 0 (le_refl _) } } }, { rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩, rcases h.joined_in (p' n) (p' $ n+1) (hp' n n.le_succ) (hp' (n+1) $ le_refl _) with ⟨γ₁, hγ₁⟩, let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁, use γ, have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁, split, { rintros i hi, by_cases hi' : i ≤ n, { rw range_eq, left, exact hγ₀.1 i hi' }, { rw [not_le, ← nat.succ_le_iff] at hi', have : i = n.succ := by linarith, rw this, use 1, exact γ.target } }, { rw range_eq, apply union_subset hγ₀.2, rw range_subset_iff, exact hγ₁ } } }, have hpp' : ∀ k < n+1, p k = p' k, { intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast }, use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self), simp only [γ.cast_coe], refine and.intro hγ.2 _, rintros ⟨i, hi⟩, convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi, congr, ext, rw fin.coe_coe_of_lt hi, norm_cast end lemma is_path_connected.exists_path_through_family' {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := begin rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩, rcases hγ with ⟨h₁, h₂⟩, simp only [range, mem_set_of_eq] at h₂, rw range_subset_iff at h₁, choose! t ht using h₂, exact ⟨γ, t, h₁, ht⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) attribute [instance, priority 50] path_connected_space.nonempty lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y z y_in z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, inhabit X, refine ⟨default X, mem_univ _, _⟩, simpa using path_connected_space.joined (default X) }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end namespace path_connected_space variables [path_connected_space X] lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) : ∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩, exact ⟨γ, h⟩ end lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩, exact ⟨γ, t, h⟩ end end path_connected_space /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, inhabit X, let x₀ := default X, rw path_connected_space_iff_eq, use x₀, refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩, { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_sets_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z y hz $ mem_of_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (mem_nhds_sets h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_sets (mem_nhds_sets h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
60d648051356df663d1f666e8928a1137a0e6023
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/mv_polynomial/funext.lean
cf1dea8a567639aba485c881624be8d6eb0f1128
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,402
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.polynomial.ring_division import data.mv_polynomial.rename import ring_theory.polynomial.basic import data.mv_polynomial.polynomial /-! ## Function extensionality for multivariate polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we show that two multivariate polynomials over an infinite integral domain are equal if they are equal upon evaluating them on an arbitrary assignment of the variables. # Main declaration * `mv_polynomial.funext`: two polynomials `φ ψ : mv_polynomial σ R` over an infinite integral domain `R` are equal if `eval x φ = eval x ψ` for all `x : σ → R`. -/ namespace mv_polynomial variables {R : Type*} [comm_ring R] [is_domain R] [infinite R] private lemma funext_fin {n : ℕ} {p : mv_polynomial (fin n) R} (h : ∀ x : fin n → R, eval x p = 0) : p = 0 := begin induction n with n ih, { apply (mv_polynomial.is_empty_ring_equiv R (fin 0)).injective, rw [ring_equiv.map_zero], convert h _, }, { apply (fin_succ_equiv R n).injective, simp only [alg_equiv.map_zero], refine polynomial.funext (λ q, _), rw [polynomial.eval_zero], apply ih (λ x, _), calc _ = _ : eval_polynomial_eval_fin_succ_equiv p _ _ ... = 0 : h _, } end /-- Two multivariate polynomials over an infinite integral domain are equal if they are equal upon evaluating them on an arbitrary assignment of the variables. -/ lemma funext {σ : Type*} {p q : mv_polynomial σ R} (h : ∀ x : σ → R, eval x p = eval x q) : p = q := begin suffices : ∀ p, (∀ (x : σ → R), eval x p = 0) → p = 0, { rw [← sub_eq_zero, this (p - q)], simp only [h, ring_hom.map_sub, forall_const, sub_self] }, clear h p q, intros p h, obtain ⟨n, f, hf, p, rfl⟩ := exists_fin_rename p, suffices : p = 0, { rw [this, alg_hom.map_zero] }, apply funext_fin, intro x, classical, convert h (function.extend f x 0), simp only [eval, eval₂_hom_rename, function.extend_comp hf] end lemma funext_iff {σ : Type*} {p q : mv_polynomial σ R} : p = q ↔ (∀ x : σ → R, eval x p = eval x q) := ⟨by rintro rfl; simp only [forall_const, eq_self_iff_true], funext⟩ end mv_polynomial
f1461d8e18875c4445b6af5582512291837021af
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex18.lean
9c02c5c5bb139c12e0960d88481d3dc49ff8076d
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
424
lean
def compose (A B C : Type) (g : B → C) (f : A → B) (x : A) : C := g (f x) def do_twice (A : Type) (h : A → A) (x : A) : A := h (h x) def do_thrice (A : Type) (h : A → A) (x : A) : A := h (h (h x)) /- Variables -/ variables (A B C : Type) def compose' (g : B → C) (f : A → B) (x : A) : C := g (f x) def do_twice' (h : A → A) (x : A) : A := h (h x) def do_thrice' (h : A → A) (x : A) : A := h (h (h x))
97369787e5efa4883c7d0f95b78bc61910c213c3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/equiv/fintype.lean
a04aa3628a1a4b9c906524b1ba3d358dd8427848
[ "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
5,409
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.fintype.basic import group_theory.perm.sign import logic.equiv.basic /-! # Equivalence between fintypes This file contains some basic results on equivalences where one or both sides of the equivalence are `fintype`s. # Main definitions - `function.embedding.to_equiv_range`: computably turn an embedding of a fintype into an `equiv` of the domain to its range - `equiv.perm.via_fintype_embedding : perm α → (α ↪ β) → perm β` extends the domain of a permutation, fixing everything outside the range of the embedding # Implementation details - `function.embedding.to_equiv_range` uses a computable inverse, but one that has poor computational performance, since it operates by exhaustive search over the input `fintype`s. -/ variables {α β : Type*} [fintype α] [decidable_eq β] (e : equiv.perm α) (f : α ↪ β) /-- Computably turn an embedding `f : α ↪ β` into an equiv `α ≃ set.range f`, if `α` is a `fintype`. Has poor computational performance, due to exhaustive searching in constructed inverse. When a better inverse is known, use `equiv.of_left_inverse'` or `equiv.of_left_inverse` instead. This is the computable version of `equiv.of_injective`. -/ def function.embedding.to_equiv_range : α ≃ set.range f := ⟨λ a, ⟨f a, set.mem_range_self a⟩, f.inv_of_mem_range, λ _, by simp, λ _, by simp⟩ @[simp] lemma function.embedding.to_equiv_range_apply (a : α) : f.to_equiv_range a = ⟨f a, set.mem_range_self a⟩ := rfl @[simp] lemma function.embedding.to_equiv_range_symm_apply_self (a : α) : f.to_equiv_range.symm ⟨f a, set.mem_range_self a⟩ = a := by simp [equiv.symm_apply_eq] lemma function.embedding.to_equiv_range_eq_of_injective : f.to_equiv_range = equiv.of_injective f f.injective := by { ext, simp } /-- Extend the domain of `e : equiv.perm α`, mapping it through `f : α ↪ β`. Everything outside of `set.range f` is kept fixed. Has poor computational performance, due to exhaustive searching in constructed inverse due to using `function.embedding.to_equiv_range`. When a better `α ≃ set.range f` is known, use `equiv.perm.via_set_range`. When `[fintype α]` is not available, a noncomputable version is available as `equiv.perm.via_embedding`. -/ def equiv.perm.via_fintype_embedding : equiv.perm β := e.extend_domain f.to_equiv_range @[simp] lemma equiv.perm.via_fintype_embedding_apply_image (a : α) : e.via_fintype_embedding f (f a) = f (e a) := begin rw equiv.perm.via_fintype_embedding, convert equiv.perm.extend_domain_apply_image e _ _ end lemma equiv.perm.via_fintype_embedding_apply_mem_range {b : β} (h : b ∈ set.range f) : e.via_fintype_embedding f b = f (e (f.inv_of_mem_range ⟨b, h⟩)) := by simpa [equiv.perm.via_fintype_embedding, equiv.perm.extend_domain_apply_subtype, h] lemma equiv.perm.via_fintype_embedding_apply_not_mem_range {b : β} (h : b ∉ set.range f) : e.via_fintype_embedding f b = b := by rwa [equiv.perm.via_fintype_embedding, equiv.perm.extend_domain_apply_not_subtype] @[simp] lemma equiv.perm.via_fintype_embedding_sign [decidable_eq α] [fintype β] : equiv.perm.sign (e.via_fintype_embedding f) = equiv.perm.sign e := by simp [equiv.perm.via_fintype_embedding] namespace equiv variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.to_compl` is an equivalence between the complement of those subtypes. See also `equiv.compl`, for a computable version when a term of type `{e' : α ≃ α // ∀ x : {x // p x}, e' x = e x}` is known. -/ noncomputable def to_compl (e : {x // p x} ≃ {x // q x}) : {x // ¬ p x} ≃ {x // ¬ q x} := classical.choice (fintype.card_eq.mp (fintype.card_compl_eq_card_compl _ _ (fintype.card_congr e))) /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.extend_subtype` is a permutation of `α` acting like `e` on the subtypes and doing something arbitrary outside. Note that when `p = q`, `equiv.perm.subtype_congr e (equiv.refl _)` can be used instead. -/ noncomputable abbreviation extend_subtype (e : {x // p x} ≃ {x // q x}) : perm α := subtype_congr e e.to_compl lemma extend_subtype_apply_of_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : p x) : e.extend_subtype x = e ⟨x, hx⟩ := by { dunfold extend_subtype, simp only [subtype_congr, equiv.trans_apply, equiv.sum_congr_apply], rw [sum_compl_apply_symm_of_pos _ _ hx, sum.map_inl, sum_compl_apply_inl] } lemma extend_subtype_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : p x) : q (e.extend_subtype x) := by { convert (e ⟨x, hx⟩).2, rw [e.extend_subtype_apply_of_mem _ hx, subtype.val_eq_coe] } lemma extend_subtype_apply_of_not_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : ¬ p x) : e.extend_subtype x = e.to_compl ⟨x, hx⟩ := by { dunfold extend_subtype, simp only [subtype_congr, equiv.trans_apply, equiv.sum_congr_apply], rw [sum_compl_apply_symm_of_neg _ _ hx, sum.map_inr, sum_compl_apply_inr] } lemma extend_subtype_not_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : ¬ p x) : ¬ q (e.extend_subtype x) := by { convert (e.to_compl ⟨x, hx⟩).2, rw [e.extend_subtype_apply_of_not_mem _ hx, subtype.val_eq_coe] } end equiv
af271911eb01a385550601866837e680da82f5a8
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/assert_tac1.lean
a1c110441e511ad9b383d134b800a1ae6db839c1
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
608
lean
open tactic definition tst1 (a : nat) : a = a := by do define `x (expr.const `nat []), trace_state, a ← get_local `a, exact a, x ← get_local `x, mk_app `eq.refl [x] >>= exact print tst1 definition tst2 (a : nat) : a = a := by do define `x (expr.const `nat []), a ← get_local `a, exact a, trace "------------", trace_state, get_local `x >>= revert, intro `y, trace_state, y ← get_local `y, mk_app `eq.refl [y] >>= exact print tst2 definition tst3 (a : nat) : a = a := begin define x : nat, exact a, revert x, intro y, apply eq.refl y end
f2bf6b37fbbed63a3457213268ef70666545bf0f
c86b74188c4b7a462728b1abd659ab4e5828dd61
/src/Lean/Elab/InfoTree.lean
88bbc6ba644e3ff42e7f6e2f69736b0d296cf76f
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,158
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.Position import Lean.Expr import Lean.Message import Lean.Data.Json import Lean.Meta.Basic import Lean.Meta.PPGoal namespace Lean.Elab open Std (PersistentArray PersistentArray.empty PersistentHashMap) /- Context after executing `liftTermElabM`. Note that the term information collected during elaboration may contain metavariables, and their assignments are stored at `mctx`. -/ structure ContextInfo where env : Environment fileMap : FileMap mctx : MetavarContext := {} options : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] deriving Inhabited /-- An elaboration step -/ structure ElabInfo where elaborator : Name stx : Syntax deriving Inhabited structure TermInfo extends ElabInfo where lctx : LocalContext -- The local context when the term was elaborated. expectedType? : Option Expr expr : Expr deriving Inhabited structure CommandInfo extends ElabInfo where deriving Inhabited inductive CompletionInfo where | dot (termInfo : TermInfo) (field? : Option Syntax) (expectedType? : Option Expr) | id (stx : Syntax) (id : Name) (danglingDot : Bool) (lctx : LocalContext) (expectedType? : Option Expr) | namespaceId (stx : Syntax) | option (stx : Syntax) | endSection (stx : Syntax) (scopeNames : List String) | tactic (stx : Syntax) (goals : List MVarId) -- TODO `import` def CompletionInfo.stx : CompletionInfo → Syntax | dot i .. => i.stx | id stx .. => stx | namespaceId stx => stx | option stx => stx | endSection stx .. => stx | tactic stx .. => stx structure FieldInfo where name : Name lctx : LocalContext val : Expr stx : Syntax deriving Inhabited /- We store the list of goals before and after the execution of a tactic. We also store the metavariable context at each time since, we want to unassigned metavariables at tactic execution time to be displayed as `?m...`. -/ structure TacticInfo extends ElabInfo where mctxBefore : MetavarContext goalsBefore : List MVarId mctxAfter : MetavarContext goalsAfter : List MVarId deriving Inhabited structure MacroExpansionInfo where lctx : LocalContext -- The local context when the macro was expanded. stx : Syntax output : Syntax deriving Inhabited inductive Info where | ofTacticInfo (i : TacticInfo) | ofTermInfo (i : TermInfo) | ofCommandInfo (i : CommandInfo) | ofMacroExpansionInfo (i : MacroExpansionInfo) | ofFieldInfo (i : FieldInfo) | ofCompletionInfo (i : CompletionInfo) deriving Inhabited inductive InfoTree where | context (i : ContextInfo) (t : InfoTree) -- The context object is created by `liftTermElabM` at `Command.lean` | node (i : Info) (children : PersistentArray InfoTree) -- The children contains information for nested term elaboration and tactic evaluation | ofJson (j : Json) -- For user data | hole (mvarId : MVarId) -- The elaborator creates holes (aka metavariables) for tactics and postponed terms deriving Inhabited partial def InfoTree.findInfo? (p : Info → Bool) (t : InfoTree) : Option InfoTree := match t with | context _ t => findInfo? p t | node i ts => if p i then some t else ts.findSome? (findInfo? p) | _ => none structure InfoState where enabled : Bool := false assignment : PersistentHashMap MVarId InfoTree := {} -- map from holeId to InfoTree trees : PersistentArray InfoTree := {} deriving Inhabited class MonadInfoTree (m : Type → Type) where getInfoState : m InfoState modifyInfoState : (InfoState → InfoState) → m Unit export MonadInfoTree (getInfoState modifyInfoState) instance [MonadLift m n] [MonadInfoTree m] : MonadInfoTree n where getInfoState := liftM (getInfoState : m _) modifyInfoState f := liftM (modifyInfoState f : m _) partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree := match tree with | node i c => node i <| c.map (substitute · assignment) | context i t => context i (substitute t assignment) | ofJson j => ofJson j | hole id => match assignment.find? id with | none => hole id | some tree => substitute tree assignment def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do let x := x.run { lctx := lctx } { mctx := info.mctx } let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } { env := info.env } return a def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext := { env := info.env, mctx := info.mctx, lctx := lctx, opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do ppTerm (info.toPPContext lctx) stx private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format := do let pos := stx.getPos?.getD 0 let endPos := stx.getTailPos?.getD pos return f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}" where fmtPos pos info := let pos := format <| ctx.fileMap.toPosition pos match info with | SourceInfo.original .. => pos | _ => f!"{pos}†" private def formatElabInfo (ctx : ContextInfo) (info : ElabInfo) : Format := if info.elaborator.isAnonymous then formatStxRange ctx info.stx else f!"{formatStxRange ctx info.stx} @ {info.elaborator}" def TermInfo.runMetaM (info : TermInfo) (ctx : ContextInfo) (x : MetaM α) : IO α := ctx.runMetaM info.lctx x def TermInfo.format (ctx : ContextInfo) (info : TermInfo) : IO Format := do info.runMetaM ctx do try return f!"{← Meta.ppExpr info.expr} : {← Meta.ppExpr (← Meta.inferType info.expr)} @ {formatElabInfo ctx info.toElabInfo}" catch _ => return f!"{← Meta.ppExpr info.expr} : <failed-to-infer-type> @ {formatElabInfo ctx info.toElabInfo}" def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format := match info with | CompletionInfo.dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}" | CompletionInfo.id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {stx} : {expectedType?} @ {formatStxRange ctx info.stx}" | _ => return f!"[.] {info.stx} @ {formatStxRange ctx info.stx}" def CommandInfo.format (ctx : ContextInfo) (info : CommandInfo) : IO Format := do return f!"command @ {formatElabInfo ctx info.toElabInfo}" def FieldInfo.format (ctx : ContextInfo) (info : FieldInfo) : IO Format := do ctx.runMetaM info.lctx do return f!"{info.name} : {← Meta.ppExpr (← Meta.inferType info.val)} := {← Meta.ppExpr info.val} @ {formatStxRange ctx info.stx}" def ContextInfo.ppGoals (ctx : ContextInfo) (goals : List MVarId) : IO Format := if goals.isEmpty then return "no goals" else ctx.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM Meta.ppGoal)) def TacticInfo.format (ctx : ContextInfo) (info : TacticInfo) : IO Format := do let ctxB := { ctx with mctx := info.mctxBefore } let ctxA := { ctx with mctx := info.mctxAfter } let goalsBefore ← ctxB.ppGoals info.goalsBefore let goalsAfter ← ctxA.ppGoals info.goalsAfter return f!"Tactic @ {formatElabInfo ctx info.toElabInfo}\n{info.stx}\nbefore {goalsBefore}\nafter {goalsAfter}" def MacroExpansionInfo.format (ctx : ContextInfo) (info : MacroExpansionInfo) : IO Format := do let stx ← ctx.ppSyntax info.lctx info.stx let output ← ctx.ppSyntax info.lctx info.output return f!"Macro expansion\n{stx}\n===>\n{output}" def Info.format (ctx : ContextInfo) : Info → IO Format | ofTacticInfo i => i.format ctx | ofTermInfo i => i.format ctx | ofCommandInfo i => i.format ctx | ofMacroExpansionInfo i => i.format ctx | ofFieldInfo i => i.format ctx | ofCompletionInfo i => i.format ctx def Info.toElabInfo? : Info → Option ElabInfo | ofTacticInfo i => some i.toElabInfo | ofTermInfo i => some i.toElabInfo | ofCommandInfo i => some i.toElabInfo | ofMacroExpansionInfo i => none | ofFieldInfo i => none | ofCompletionInfo i => none /-- Helper function for propagating the tactic metavariable context to its children nodes. We need this function because we preserve `TacticInfo` nodes during backtracking *and* their children. Moreover, we backtrack the metavariable context to undo metavariable assignments. `TacticInfo` nodes save the metavariable context before/after the tactic application, and can be pretty printed without any extra information. This is not the case for `TermInfo` nodes. Without this function, the formatting method would often fail when processing `TermInfo` nodes that are children of `TacticInfo` nodes that have been preserved during backtracking. Saving the metavariable context at `TermInfo` nodes is also not a good option because at `TermInfo` creation time, the metavariable context often miss information, e.g., a TC problem has not been resolved, a postponed subterm has not been elaborated, etc. See `Term.SavedState.restore`. -/ def Info.updateContext? : Option ContextInfo → Info → Option ContextInfo | some ctx, ofTacticInfo i => some { ctx with mctx := i.mctxAfter } | ctx?, _ => ctx? partial def InfoTree.format (tree : InfoTree) (ctx? : Option ContextInfo := none) : IO Format := do match tree with | ofJson j => return toString j | hole id => return toString id | context i t => format t i | node i cs => match ctx? with | none => return "<context-not-available>" | some ctx => let fmt ← i.format ctx if cs.size == 0 then return fmt else let ctx? := i.updateContext? ctx? return f!"{fmt}{Std.Format.nestD <| Std.Format.prefixJoin "\n" (← cs.toList.mapM fun c => format c ctx?)}" section variable [Monad m] [MonadInfoTree m] @[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit := modifyInfoState fun s => { s with trees := f s.trees } private def getResetInfoTrees : m (PersistentArray InfoTree) := do let trees := (← getInfoState).trees modifyInfoTrees fun _ => {} return trees def pushInfoTree (t : InfoTree) : m Unit := do if (← getInfoState).enabled then modifyInfoTrees fun ts => ts.push t def pushInfoLeaf (t : Info) : m Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) t def addCompletionInfo (info : CompletionInfo) : m Unit := do pushInfoLeaf <| Info.ofCompletionInfo info def resolveGlobalConstNoOverloadWithInfo [MonadResolveName m] [MonadEnv m] [MonadError m] (stx : Syntax) (id := stx.getId) (expectedType? : Option Expr := none) : m Name := do let n ← resolveGlobalConstNoOverload id if (← getInfoState).enabled then -- we do not store a specific elaborator since identifiers are special-cased by the server anyway pushInfoLeaf <| Info.ofTermInfo { elaborator := Name.anonymous, lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx, expectedType? } return n def resolveGlobalConstWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (stx : Syntax) (id := stx.getId) (expectedType? : Option Expr := none) : m (List Name) := do let ns ← resolveGlobalConst id if (← getInfoState).enabled then for n in ns do pushInfoLeaf <| Info.ofTermInfo { elaborator := Name.anonymous, lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx, expectedType? } return ns @[inline] def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => do match a? with | none => modifyInfoTrees fun _ => treesSaved | some a => let info ← mkInfo a modifyInfoTrees fun trees => match info with | Sum.inl info => treesSaved.push <| InfoTree.node info trees | Sum.inr mvaId => treesSaved.push <| InfoTree.hole mvaId else x @[inline] def withInfoTreeContext [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let tree ← mkInfoTree st.trees modifyInfoTrees fun _ => treesSaved.push tree else x @[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees) @[inline] def withSaveInfoContext [MonadFinally m] [MonadEnv m] [MonadOptions m] [MonadMCtx m] [MonadResolveName m] [MonadFileMap m] (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let trees ← st.trees.mapM fun tree => do let tree := tree.substitute st.assignment InfoTree.context { env := (← getEnv), fileMap := (← getFileMap), mctx := (← getMCtx), currNamespace := (← getCurrNamespace), openDecls := (← getOpenDecls), options := (← getOptions) } tree modifyInfoTrees fun _ => treesSaved ++ trees else x def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) := return (← getInfoState).assignment[mvarId] def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do assert! (← getInfoHoleIdAssignment? mvarId).isNone modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree } end def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (stx output : Syntax) (x : m α) : m α := let mkInfo : m Info := do return Info.ofMacroExpansionInfo { lctx := (← getLCtx) stx, output } withInfoContext x mkInfo @[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => modifyInfoState fun s => if s.trees.size > 0 then { s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[s.trees.size - 1] } else { s with trees := treesSaved } else x def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit := modifyInfoState fun s => { s with enabled := flag } def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) := return (← getInfoState).trees end Lean.Elab
99f03991f2b46ec4a562481e8b150ce6f9e80359
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/logic/axioms/examples/leftinv_of_inj.lean
228c05c7d94cd93cc1e6785172207b3daa21f601
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,251
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Classical proof that if f is injective, then f has a left inverse (if domain is not empty). The proof uses the classical axioms: choice and excluded middle. The excluded middle is being used "behind the scenes" to allow us to write the if-then-else expression with (∃ a : A, f a = b). -/ import algebra.function logic.axioms.classical open function definition mk_left_inv {A B : Type} [h : nonempty A] (f : A → B) : B → A := λ b : B, if ex : (∃ a : A, f a = b) then some ex else inhabited.value (inhabited_of_nonempty h) theorem has_left_inverse_of_injective {A B : Type} {f : A → B} : nonempty A → injective f → has_left_inverse f := assume h : nonempty A, assume inj : ∀ a₁ a₂, f a₁ = f a₂ → a₁ = a₂, let finv : B → A := mk_left_inv f in have linv : finv ∘ f = id, from funext (λ a, assert ex : ∃ a₁ : A, f a₁ = f a, from exists.intro a rfl, assert h₁ : f (some ex) = f a, from !some_spec, begin esimp [mk_left_inv, compose, id], rewrite [dif_pos ex], exact (!inj h₁) end), exists.intro finv linv
e377c6a4672e22a906823292a07167f2bc00d721
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/analytic/basic.lean
f620f42501c54d0da2cd47b115dc26690e9e7b0b
[ "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
60,526
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, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import analysis.specific_limits.normed import logic.equiv.fin /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. * `analytic_on 𝕜 f s`: the function `f` is analytic at every point of `s`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 E F G : Type*} open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics namespace formal_multilinear_series variables [ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] variables [topological_space E] [topological_space F] variables [topological_add_group E] [topological_add_group F] variables [has_continuous_const_smul 𝕜 E] [has_continuous_const_smul 𝕜 F] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### The radius of a formal multilinear series -/ variables [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] [normed_group G] [normed_space 𝕜 G] namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥₊ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : (λ n, ∥p n∥ * r^n) =O[at_top] (λ n, (1 : ℝ))) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma le_radius_of_eventually_le (C) (h : ∀ᶠ n in at_top, ∥p n∥ * r ^ n ≤ C) : ↑r ≤ p.radius := p.le_radius_of_is_O $ is_O.of_bound C $ h.mono $ λ n hn, by simpa lemma le_radius_of_summable_nnnorm (h : summable (λ n, ∥p n∥₊ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_bound_nnreal (∑' n, ∥p n∥₊ * r ^ n) $ λ n, le_tsum' h _ lemma le_radius_of_summable (h : summable (λ n, ∥p n∥ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_summable_nnnorm $ by { simp only [← coe_nnnorm] at h, exact_mod_cast h } lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, (λ n, ∥p n∥ * r^n) =O[at_top] (λ n, (1 : ℝ))) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, tsub_add_cancel_of_le hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, (λ n, ∥p n∥ * r ^ n) =o[at_top] (pow a) := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc |∥p n∥ * r ^ n| = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : (λ n, ∥p n∥ * r ^ n) =o[at_top] (λ _, 1 : ℕ → ℝ) := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : (λ n, ∥p n∥ * r ^ n) =O[at_top] (pow a)) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, rw [← pos_iff_ne_zero, ← nnreal.coe_pos] at h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := by simpa only [div_one] using (div_lt_div_left h₀ zero_lt_one ha.1).2 ha.2, norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥₊ * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (h.is_O_one _) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < ∥x∥₊) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥ * r ^ n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, exact summable_of_nonneg_of_le (λ n, mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg _)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _), end lemma summable_norm_apply (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, ∥p n (λ _, x)∥) := begin rw mem_emetric_ball_zero_iff at hx, refine summable_of_nonneg_of_le (λ _, norm_nonneg _) (λ n, ((p n).le_op_norm _).trans_eq _) (p.summable_norm_mul_pow hx), simp end lemma summable_nnnorm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥₊ * r ^ n) := by { rw ← nnreal.summable_coe, push_cast, exact p.summable_norm_mul_pow h } protected lemma summable [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, p n (λ _, x)) := summable_of_summable_norm (p.summable_norm_apply hx) lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, norm_mul, norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] protected lemma has_sum [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : has_sum (λ n : ℕ, p n (λ _, x)) (p.sum x) := (p.summable hx).has_sum lemma radius_le_radius_continuous_linear_map_comp (p : formal_multilinear_series 𝕜 E F) (f : F →L[𝕜] G) : p.radius ≤ (f.comp_formal_multilinear_series p).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), apply le_radius_of_is_O, apply (is_O.trans_is_o _ (p.is_o_one_of_lt_radius hr)).is_O, refine is_O.mul (@is_O_with.is_O _ _ _ _ _ (∥f∥) _ _ _ _) (is_O_refl _ _), apply is_O_with.of_bound (eventually_of_forall (λ n, _)), simpa only [norm_norm] using f.norm_comp_continuous_multilinear_map_le (p n) end end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x /-- Given a function `f : E → F`, we say that `f` is analytic on a set `s` if it is analytic around every point of `s`. -/ def analytic_on (f : E → F) (s : set E) := ∀ x, x ∈ s → analytic_at 𝕜 f x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.congr (hf : has_fpower_series_on_ball f p x r) (hg : eq_on f g (emetric.ball x r)) : has_fpower_series_on_ball g p x r := { r_le := hf.r_le, r_pos := hf.r_pos, has_sum := λ y hy, begin convert hf.has_sum hy, apply hg.symm, simpa [edist_eq_coe_nnnorm_sub] using hy, end } /-- If a function `f` has a power series `p` around `x`, then the function `z ↦ f (z - y)` has the same power series around `x + y`. -/ lemma has_fpower_series_on_ball.comp_sub (hf : has_fpower_series_on_ball f p x r) (y : E) : has_fpower_series_on_ball (λ z, f (z - y)) p (x + y) r := { r_le := hf.r_le, r_pos := hf.r_pos, has_sum := λ z hz, by { convert hf.has_sum hz, abel } } lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[>] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function `f` has a power series `p` on a ball and `g` is linear, then `g ∘ f` has the power series `g ∘ p` on the same ball. -/ lemma _root_.continuous_linear_map.comp_has_fpower_series_on_ball (g : F →L[𝕜] G) (h : has_fpower_series_on_ball f p x r) : has_fpower_series_on_ball (g ∘ f) (g.comp_formal_multilinear_series p) x r := { r_le := h.r_le.trans (p.radius_le_radius_continuous_linear_map_comp _), r_pos := h.r_pos, has_sum := λ y hy, by simpa only [continuous_linear_map.comp_formal_multilinear_series_apply, continuous_linear_map.comp_continuous_multilinear_map_coe, function.comp_app] using g.has_sum (h.has_sum hy) } /-- If a function `f` is analytic on a set `s` and `g` is linear, then `g ∘ f` is analytic on `s`. -/ lemma _root_.continuous_linear_map.comp_analytic_on {s : set E} (g : F →L[𝕜] G) (h : analytic_on 𝕜 f s) : analytic_on 𝕜 (g ∘ f) s := begin rintros x hx, rcases h x hx with ⟨p, r, hp⟩, exact ⟨g.comp_formal_multilinear_series p, r, g.comp_has_fpower_series_on_ball hp⟩, end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_zero_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_zero_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2]; apply_instance }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_zero_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : (λ y : E, f (x + y) - p.partial_sum n y) =O[𝓝 0] (λ y, ∥y∥ ^ n) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0] with y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) =O[𝓟 (emetric.ball (x, x) r')] (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp only [is_O_bot, emetric.ball_zero, principal_empty, ennreal.coe_zero] }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ emetric.ball x r ×ˢ emetric.ball x r, { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)) using 1, rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa only [fintype.card_fin, pi_norm_const (_ : E), prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ring } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp only [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : L =O[𝓟 (emetric.ball (x, x) r')] (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp, @forall_swap (_ < _) E] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) =O[𝓝 (x, x)] (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ protected lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ eventually_of_forall $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on protected lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) protected lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at protected lemma analytic_on.continuous_on {s : set E} (hf : analytic_on 𝕜 f s) : continuous_on f s := λ x hx, (hf x hx).continuous_at.continuous_within_at /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ protected lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_rfl, r_pos := h, has_sum := λ y hy, by { rw zero_add, exact p.has_sum hy } } lemma has_fpower_series_on_ball.sum (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := (h.has_sum hy).tsum_eq.symm /-- The sum of a converging power series is continuous in its disk of convergence. -/ protected lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Uniqueness of power series If a function `f : E → F` has two representations as power series at a point `x : E`, corresponding to formal multilinear series `p₁` and `p₂`, then these representations agree term-by-term. That is, for any `n : ℕ` and `y : E`, `p₁ n (λ i, y) = p₂ n (λ i, y)`. In the one-dimensional case, when `f : 𝕜 → E`, the continuous multilinear maps `p₁ n` and `p₂ n` are given by `formal_multilinear_series.mk_pi_field`, and hence are determined completely by the value of `p₁ n (λ i, 1)`, so `p₁ = p₂`. Consequently, the radius of convergence for one series can be transferred to the other. -/ section uniqueness open continuous_multilinear_map lemma asymptotics.is_O.continuous_multilinear_map_apply_eq_zero {n : ℕ} {p : E [×n]→L[𝕜] F} (h : (λ y, p (λ i, y)) =O[𝓝 0] (λ y, ∥y∥ ^ (n + 1))) (y : E) : p (λ i, y) = 0 := begin obtain ⟨c, c_pos, hc⟩ := h.exists_pos, obtain ⟨t, ht, t_open, z_mem⟩ := eventually_nhds_iff.mp (is_O_with_iff.mp hc), obtain ⟨δ, δ_pos, δε⟩ := (metric.is_open_iff.mp t_open) 0 z_mem, clear h hc z_mem, cases n, { exact norm_eq_zero.mp (by simpa only [fin0_apply_norm, norm_eq_zero, norm_zero, zero_pow', ne.def, nat.one_ne_zero, not_false_iff, mul_zero, norm_le_zero_iff] using ht 0 (δε (metric.mem_ball_self δ_pos))), }, { refine or.elim (em (y = 0)) (λ hy, by simpa only [hy] using p.map_zero) (λ hy, _), replace hy := norm_pos_iff.mpr hy, refine norm_eq_zero.mp (le_antisymm (le_of_forall_pos_le_add (λ ε ε_pos, _)) (norm_nonneg _)), have h₀ := mul_pos c_pos (pow_pos hy (n.succ + 1)), obtain ⟨k, k_pos, k_norm⟩ := normed_field.exists_norm_lt 𝕜 (lt_min (mul_pos δ_pos (inv_pos.mpr hy)) (mul_pos ε_pos (inv_pos.mpr h₀))), have h₁ : ∥k • y∥ < δ, { rw norm_smul, exact inv_mul_cancel_right₀ hy.ne.symm δ ▸ mul_lt_mul_of_pos_right (lt_of_lt_of_le k_norm (min_le_left _ _)) hy }, have h₂ := calc ∥p (λ i, k • y)∥ ≤ c * ∥k • y∥ ^ (n.succ + 1) : by simpa only [norm_pow, norm_norm] using ht (k • y) (δε (mem_ball_zero_iff.mpr h₁)) ... = ∥k∥ ^ n.succ * (∥k∥ * (c * ∥y∥ ^ (n.succ + 1))) : by { simp only [norm_smul, mul_pow], rw pow_succ, ring }, have h₃ : ∥k∥ * (c * ∥y∥ ^ (n.succ + 1)) < ε, from inv_mul_cancel_right₀ h₀.ne.symm ε ▸ mul_lt_mul_of_pos_right (lt_of_lt_of_le k_norm (min_le_right _ _)) h₀, calc ∥p (λ i, y)∥ = ∥(k⁻¹) ^ n.succ∥ * ∥p (λ i, k • y)∥ : by simpa only [inv_smul_smul₀ (norm_pos_iff.mp k_pos), norm_smul, finset.prod_const, finset.card_fin] using congr_arg norm (p.map_smul_univ (λ (i : fin n.succ), k⁻¹) (λ (i : fin n.succ), k • y)) ... ≤ ∥(k⁻¹) ^ n.succ∥ * (∥k∥ ^ n.succ * (∥k∥ * (c * ∥y∥ ^ (n.succ + 1)))) : mul_le_mul_of_nonneg_left h₂ (norm_nonneg _) ... = ∥(k⁻¹ * k) ^ n.succ∥ * (∥k∥ * (c * ∥y∥ ^ (n.succ + 1))) : by { rw ←mul_assoc, simp [norm_mul, mul_pow] } ... ≤ 0 + ε : by { rw inv_mul_cancel (norm_pos_iff.mp k_pos), simpa using h₃.le }, }, end /-- If a formal multilinear series `p` represents the zero function at `x : E`, then the terms `p n (λ i, y)` appearing the in sum are zero for any `n : ℕ`, `y : E`. -/ lemma has_fpower_series_at.apply_eq_zero {p : formal_multilinear_series 𝕜 E F} {x : E} (h : has_fpower_series_at 0 p x) (n : ℕ) : ∀ y : E, p n (λ i, y) = 0 := begin refine nat.strong_rec_on n (λ k hk, _), have psum_eq : p.partial_sum (k + 1) = (λ y, p k (λ i, y)), { funext z, refine finset.sum_eq_single _ (λ b hb hnb, _) (λ hn, _), { have := finset.mem_range_succ_iff.mp hb, simp only [hk b (this.lt_of_ne hnb), pi.zero_apply, zero_apply] }, { exact false.elim (hn (finset.mem_range.mpr (lt_add_one k))) } }, replace h := h.is_O_sub_partial_sum_pow k.succ, simp only [psum_eq, zero_sub, pi.zero_apply, asymptotics.is_O_neg_left] at h, exact h.continuous_multilinear_map_apply_eq_zero, end /-- A one-dimensional formal multilinear series representing the zero function is zero. -/ lemma has_fpower_series_at.eq_zero {p : formal_multilinear_series 𝕜 𝕜 E} {x : 𝕜} (h : has_fpower_series_at 0 p x) : p = 0 := by { ext n x, rw ←mk_pi_field_apply_one_eq_self (p n), simp [h.apply_eq_zero n 1] } /-- One-dimensional formal multilinear series representing the same function are equal. -/ theorem has_fpower_series_at.eq_formal_multilinear_series {p₁ p₂ : formal_multilinear_series 𝕜 𝕜 E} {f : 𝕜 → E} {x : 𝕜} (h₁ : has_fpower_series_at f p₁ x) (h₂ : has_fpower_series_at f p₂ x) : p₁ = p₂ := sub_eq_zero.mp (has_fpower_series_at.eq_zero (by simpa only [sub_self] using h₁.sub h₂)) /-- If a function `f : 𝕜 → E` has two power series representations at `x`, then the given radii in which convergence is guaranteed may be interchanged. This can be useful when the formal multilinear series in one representation has a particularly nice form, but the other has a larger radius. -/ theorem has_fpower_series_on_ball.exchange_radius {p₁ p₂ : formal_multilinear_series 𝕜 𝕜 E} {f : 𝕜 → E} {r₁ r₂ : ℝ≥0∞} {x : 𝕜} (h₁ : has_fpower_series_on_ball f p₁ x r₁) (h₂ : has_fpower_series_on_ball f p₂ x r₂) : has_fpower_series_on_ball f p₁ x r₂ := h₂.has_fpower_series_at.eq_formal_multilinear_series h₁.has_fpower_series_at ▸ h₂ /-- If a function `f : 𝕜 → E` has power series representation `p` on a ball of some radius and for each positive radius it has some power series representation, then `p` converges to `f` on the whole `𝕜`. -/ theorem has_fpower_series_on_ball.r_eq_top_of_exists {f : 𝕜 → E} {r : ℝ≥0∞} {x : 𝕜} {p : formal_multilinear_series 𝕜 𝕜 E} (h : has_fpower_series_on_ball f p x r) (h' : ∀ (r' : ℝ≥0) (hr : 0 < r'), ∃ p' : formal_multilinear_series 𝕜 𝕜 E, has_fpower_series_on_ball f p' x r') : has_fpower_series_on_ball f p x ∞ := { r_le := ennreal.le_of_forall_pos_nnreal_lt $ λ r hr hr', let ⟨p', hp'⟩ := h' r hr in (h.exchange_radius hp').r_le, r_pos := ennreal.coe_lt_top, has_sum := λ y hy, let ⟨r', hr'⟩ := exists_gt ∥y∥₊, ⟨p', hp'⟩ := h' r' hr'.ne_bot.bot_lt in (h.exchange_radius hp').has_sum $ mem_emetric_ball_zero_iff.mpr (ennreal.coe_lt_coe.2 hr') } end uniqueness /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series section variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} /-- A term of `formal_multilinear_series.change_origin_series`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Each term of `p.change_origin x` is itself an analytic function of `x` given by the series `p.change_origin_series`. Each term in `change_origin_series` is the sum of `change_origin_series_term`'s over all `s` of cardinality `l`. The definition is such that `p.change_origin_series_term k l s hs (λ _, x) (λ _, y) = p (k + l) (s.piecewise (λ _, x) (λ _, y))` -/ def change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : E [×l]→L[𝕜] E [×k]→L[𝕜] F := continuous_multilinear_map.curry_fin_finset 𝕜 E F hs (by erw [finset.card_compl, fintype.card_fin, hs, add_tsub_cancel_right]) (p $ k + l) lemma change_origin_series_term_apply (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : p.change_origin_series_term k l s hs (λ _, x) (λ _, y) = p (k + l) (s.piecewise (λ _, x) (λ _, y)) := continuous_multilinear_map.curry_fin_finset_apply_const _ _ _ _ _ @[simp] lemma norm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥ = ∥p (k + l)∥ := by simp only [change_origin_series_term, linear_isometry_equiv.norm_map] @[simp] lemma nnnorm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥₊ = ∥p (k + l)∥₊ := by simp only [change_origin_series_term, linear_isometry_equiv.nnnorm_map] lemma nnnorm_change_origin_series_term_apply_le (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : ∥p.change_origin_series_term k l s hs (λ _, x) (λ _, y)∥₊ ≤ ∥p (k + l)∥₊ * ∥x∥₊ ^ l * ∥y∥₊ ^ k := begin rw [← p.nnnorm_change_origin_series_term k l s hs, ← fin.prod_const, ← fin.prod_const], apply continuous_multilinear_map.le_of_op_nnnorm_le, apply continuous_multilinear_map.le_op_nnnorm end /-- The power series for `f.change_origin k`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Its `k`-th term is the sum of the series `p.change_origin_series k`. -/ def change_origin_series (k : ℕ) : formal_multilinear_series 𝕜 E (E [×k]→L[𝕜] F) := λ l, ∑ s : {s : finset (fin (k + l)) // finset.card s = l}, p.change_origin_series_term k l s s.2 lemma nnnorm_change_origin_series_le_tsum (k l : ℕ) : ∥p.change_origin_series k l∥₊ ≤ ∑' (x : {s : finset (fin (k + l)) // s.card = l}), ∥p (k + l)∥₊ := (nnnorm_sum_le _ _).trans_eq $ by simp only [tsum_fintype, nnnorm_change_origin_series_term] lemma nnnorm_change_origin_series_apply_le_tsum (k l : ℕ) (x : E) : ∥p.change_origin_series k l (λ _, x)∥₊ ≤ ∑' s : {s : finset (fin (k + l)) // s.card = l}, ∥p (k + l)∥₊ * ∥x∥₊ ^ l := begin rw [nnreal.tsum_mul_right, ← fin.prod_const], exact (p.change_origin_series k l).le_of_op_nnnorm_le _ (p.nnnorm_change_origin_series_le_tsum _ _) end /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, (p.change_origin_series k).sum x /-- An auxiliary equivalence useful in the proofs about `formal_multilinear_series.change_origin_series`: the set of triples `(k, l, s)`, where `s` is a `finset (fin (k + l))` of cardinality `l` is equivalent to the set of pairs `(n, s)`, where `s` is a `finset (fin n)`. The forward map sends `(k, l, s)` to `(k + l, s)` and the inverse map sends `(n, s)` to `(n - finset.card s, finset.card s, s)`. The actual definition is less readable because of problems with non-definitional equalities. -/ @[simps] def change_origin_index_equiv : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}) ≃ Σ n : ℕ, finset (fin n) := { to_fun := λ s, ⟨s.1 + s.2.1, s.2.2⟩, inv_fun := λ s, ⟨s.1 - s.2.card, s.2.card, ⟨s.2.map (fin.cast $ (tsub_add_cancel_of_le $ card_finset_fin_le s.2).symm).to_equiv.to_embedding, finset.card_map _⟩⟩, left_inv := begin rintro ⟨k, l, ⟨s : finset (fin $ k + l), hs : s.card = l⟩⟩, dsimp only [subtype.coe_mk], -- Lean can't automatically generalize `k' = k + l - s.card`, `l' = s.card`, so we explicitly -- formulate the generalized goal suffices : ∀ k' l', k' = k → l' = l → ∀ (hkl : k + l = k' + l') hs', (⟨k', l', ⟨finset.map (fin.cast hkl).to_equiv.to_embedding s, hs'⟩⟩ : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l})) = ⟨k, l, ⟨s, hs⟩⟩, { apply this; simp only [hs, add_tsub_cancel_right] }, rintro _ _ rfl rfl hkl hs', simp only [equiv.refl_to_embedding, fin.cast_refl, finset.map_refl, eq_self_iff_true, order_iso.refl_to_equiv, and_self, heq_iff_eq] end, right_inv := begin rintro ⟨n, s⟩, simp [tsub_add_cancel_of_le (card_finset_fin_le s), fin.cast_to_equiv] end } lemma change_origin_series_summable_aux₁ {r r' : ℝ≥0} (hr : (r + r' : ℝ≥0∞) < p.radius) : summable (λ s : Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (s.1 + s.2.1)∥₊ * r ^ s.2.1 * r' ^ s.1) := begin rw ← change_origin_index_equiv.symm.summable_iff, dsimp only [(∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst], have : ∀ n : ℕ, has_sum (λ s : finset (fin n), ∥p (n - s.card + s.card)∥₊ * r ^ s.card * r' ^ (n - s.card)) (∥p n∥₊ * (r + r') ^ n), { intro n, -- TODO: why `simp only [tsub_add_cancel_of_le (card_finset_fin_le _)]` fails? convert_to has_sum (λ s : finset (fin n), ∥p n∥₊ * (r ^ s.card * r' ^ (n - s.card))) _, { ext1 s, rw [tsub_add_cancel_of_le (card_finset_fin_le _), mul_assoc] }, rw ← fin.sum_pow_mul_eq_add_pow, exact (has_sum_fintype _).mul_left _ }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact p.summable_nnnorm_mul_pow hr end lemma change_origin_series_summable_aux₂ (hr : (r : ℝ≥0∞) < p.radius) (k : ℕ) : summable (λ s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * r ^ s.1) := begin rcases ennreal.lt_iff_exists_add_pos_lt.1 hr with ⟨r', h0, hr'⟩, simpa only [mul_inv_cancel_right₀ (pow_pos h0 _).ne'] using ((nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr')).1 k).mul_right (r' ^ k)⁻¹ end lemma change_origin_series_summable_aux₃ {r : ℝ≥0} (hr : ↑r < p.radius) (k : ℕ) : summable (λ l : ℕ, ∥p.change_origin_series k l∥₊ * r ^ l) := begin refine nnreal.summable_of_le (λ n, _) (nnreal.summable_sigma.1 $ p.change_origin_series_summable_aux₂ hr k).2, simp only [nnreal.tsum_mul_right], exact mul_le_mul' (p.nnnorm_change_origin_series_le_tsum _ _) le_rfl end lemma le_change_origin_series_radius (k : ℕ) : p.radius ≤ (p.change_origin_series k).radius := ennreal.le_of_forall_nnreal_lt $ λ r hr, le_radius_of_summable_nnnorm _ (p.change_origin_series_summable_aux₃ hr k) lemma nnnorm_change_origin_le (k : ℕ) (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : ∥p.change_origin x k∥₊ ≤ ∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1 := begin refine tsum_of_nnnorm_bounded _ (λ l, p.nnnorm_change_origin_series_apply_le_tsum k l x), have := p.change_origin_series_summable_aux₂ h k, refine has_sum.sigma this.has_sum (λ l, _), exact ((nnreal.summable_sigma.1 this).1 l).has_sum end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - ∥x∥₊ ≤ (p.change_origin x).radius := begin refine ennreal.le_of_forall_pos_nnreal_lt (λ r h0 hr, _), rw [lt_tsub_iff_right, add_comm] at hr, have hr' : (∥x∥₊ : ℝ≥0∞) < p.radius, from (le_add_right le_rfl).trans_lt hr, apply le_radius_of_summable_nnnorm, have : ∀ k : ℕ, ∥p.change_origin x k∥₊ * r ^ k ≤ (∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1) * r ^ k, from λ k, mul_le_mul_right' (p.nnnorm_change_origin_le k hr') (r ^ k), refine nnreal.summable_of_le this _, simpa only [← nnreal.tsum_mul_right] using (nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr)).2 end end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variables [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} lemma has_fpower_series_on_ball_change_origin (k : ℕ) (hr : 0 < p.radius) : has_fpower_series_on_ball (λ x, p.change_origin x k) (p.change_origin_series k) 0 p.radius := have _ := p.le_change_origin_series_radius k, ((p.change_origin_series k).has_fpower_series_on_ball (hr.trans_le this)).mono hr this /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (∥x∥₊ + ∥y∥₊ : ℝ≥0∞) < p.radius) : (p.change_origin x).sum y = (p.sum (x + y)) := begin have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, have x_mem_ball : x ∈ emetric.ball (0 : E) p.radius, from mem_emetric_ball_zero_iff.2 ((le_add_right le_rfl).trans_lt h), have y_mem_ball : y ∈ emetric.ball (0 : E) (p.change_origin x).radius, { refine mem_emetric_ball_zero_iff.2 (lt_of_lt_of_le _ p.change_origin_radius), rwa [lt_tsub_iff_right, add_comm] }, have x_add_y_mem_ball : x + y ∈ emetric.ball (0 : E) p.radius, { refine mem_emetric_ball_zero_iff.2 (lt_of_le_of_lt _ h), exact_mod_cast nnnorm_add_le x y }, set f : (Σ (k l : ℕ), {s : finset (fin (k + l)) // s.card = l}) → F := λ s, p.change_origin_series_term s.1 s.2.1 s.2.2 s.2.2.2 (λ _, x) (λ _, y), have hsf : summable f, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₁ h) _, rintro ⟨k, l, s, hs⟩, dsimp only [subtype.coe_mk], exact p.nnnorm_change_origin_series_term_apply_le _ _ _ _ _ _ }, have hf : has_sum f ((p.change_origin x).sum y), { refine has_sum.sigma_of_has_sum ((p.change_origin x).summable y_mem_ball).has_sum (λ k, _) hsf, { dsimp only [f], refine continuous_multilinear_map.has_sum_eval _ _, have := (p.has_fpower_series_on_ball_change_origin k radius_pos).has_sum x_mem_ball, rw zero_add at this, refine has_sum.sigma_of_has_sum this (λ l, _) _, { simp only [change_origin_series, continuous_multilinear_map.sum_apply], apply has_sum_fintype }, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₂ (mem_emetric_ball_zero_iff.1 x_mem_ball) k) (λ s, _), refine (continuous_multilinear_map.le_op_nnnorm _ _).trans_eq _, simp } } }, refine hf.unique (change_origin_index_equiv.symm.has_sum_iff.1 _), refine has_sum.sigma_of_has_sum (p.has_sum x_add_y_mem_ball) (λ n, _) (change_origin_index_equiv.symm.summable_iff.2 hsf), erw [(p n).map_add_univ (λ _, x) (λ _, y)], convert has_sum_fintype _, ext1 s, dsimp only [f, change_origin_series_term, (∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst, change_origin_index_equiv_symm_apply_snd_snd_coe], rw continuous_multilinear_map.curry_fin_finset_apply_const, have : ∀ m (hm : n = m), p n (s.piecewise (λ _, x) (λ _, y)) = p m ((s.map (fin.cast hm).to_equiv.to_embedding).piecewise (λ _, x) (λ _, y)), { rintro m rfl, simp }, apply this end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (∥y∥₊ : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - ∥y∥₊) := { r_le := begin apply le_trans _ p.change_origin_radius, exact tsub_le_tsub hf.r_le le_rfl end, r_pos := by simp [h], has_sum := λ z hz, begin convert (p.change_origin y).has_sum _, { rw [mem_emetric_ball_zero_iff, lt_tsub_iff_right, add_comm] at hz, rw [p.change_origin_eval (hz.trans_le hf.r_le), add_assoc, hf.sum], refine mem_emetric_ball_zero_iff.2 (lt_of_le_of_lt _ hz), exact_mod_cast nnnorm_add_le y z }, { refine emetric.ball_subset_ball (le_trans _ p.change_origin_radius) hz, exact tsub_le_tsub hf.r_le le_rfl } end } /-- If a function admits a power series expansion `p` on an open ball `B (x, r)`, then it is analytic at every point of this ball. -/ lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (∥y - x∥₊ : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end lemma has_fpower_series_on_ball.analytic_on (hf : has_fpower_series_on_ball f p x r) : analytic_on 𝕜 f (emetric.ball x r) := λ y hy, hf.analytic_at_of_mem hy variables (𝕜 f) /-- For any function `f` from a normed vector space to a Banach space, the set of points `x` such that `f` is analytic at `x` is open. -/ lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_mem_nhds, rintro x ⟨p, r, hr⟩, exact mem_of_superset (emetric.ball_mem_nhds _ hr.r_pos) (λ y hy, hr.analytic_at_of_mem hy) end end
49cf83969fe08cd4265cde908206b943c6701f32
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Structure.lean
b0a91900fe99c2d93c3230fda58e5a4f6d874c7e
[ "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
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
45,606
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.AppBuilder import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange import Lean.Elab.Binders namespace Lean.Elab.Command open Meta open TSyntax.Compat /-! Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo declName : Name name : Name -- The field name as it is going to be registered in the kernel. It does not include macroscopes. rawName : Name -- Same as `name` but including macroscopes. binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | copiedField | fromParent | subobject deriving Inhabited, DecidableEq, Repr structure StructFieldInfo where name : Name declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary "default value" functions. fvar : Expr kind : StructFieldKind value? : Option Expr := none deriving Inhabited, Repr def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, name := defaultCtorName, declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name, modifiers := ctorModifiers, declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := mkNode ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let (binders, type?) ← if binfo == BinderInfo.default then let (binders, type?) := expandOptDeclSig fieldBinder[3] let optBinderTacticDefault := fieldBinder[4] if optBinderTacticDefault.isNone then pure (binders, type?) else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then pure (binders, type?) else let binderTactic := optBinderTacticDefault[0] match type? with | none => throwErrorAt binderTactic "invalid field declaration, type must be provided when auto-param (tactic) is used" | some type => let tac := binderTactic[2] let name ← Term.declareTacticSyntax tac -- The tactic should be for binders+type. -- It is safe to reset the binders to a "null" node since there is no value to be elaborated let type ← `(forall $(binders.getArgs):bracketedBinder*, $type) let type ← `(autoParam $type $(mkIdentFrom tac name)) pure (mkNullNode, some type.raw) else let (binders, type) := expandDeclSig fieldBinder[3] pure (binders, some type) let value? ← if binfo != BinderInfo.default then pure none else let optBinderTacticDefault := fieldBinder[4] -- trace[Elab.struct] ">>> {optBinderTacticDefault}" if optBinderTacticDefault.isNone then pure none else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then pure none else -- binderDefault := leading_parser " := " >> termParser pure (some optBinderTacticDefault[0][1]) let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let rawName := ident.getId let name := rawName.eraseMacroScopes unless name.isAtomic do throwErrorAt ident "invalid field name '{name.eraseMacroScopes}', field names must be atomic" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident modifiers := fieldModifiers binderInfo := binfo declName name rawName binders type? value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo := infos.map fun info => if info.name == fieldName then { info with value? := value } else info register_builtin_option structureDiamondWarning : Bool := { defValue := false descr := "enable/disable warning messages for structure diamonds" } /-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/ private def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do let fieldNames := getStructureFieldsFlattened (← getEnv) parentStructName for fieldName in fieldNames do if containsFieldName infos fieldName then return some fieldName return none private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := go 0 infos where go (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } go (i+1) infos else k infos /-- Given `obj.foo.bar.baz`, return `obj`. -/ private partial def getNestedProjectionArg (e : Expr) : MetaM Expr := do if let Expr.const subProjName .. := e.getAppFn then if let some { numParams, .. } ← getProjectionFnInfo? subProjName then if e.getAppNumArgs == numParams + 1 then return ← getNestedProjectionArg e.appArg! return e /-- Get field type of `fieldName` in `parentType`, but replace references to other fields of that structure by existing field fvars. Auxiliary method for `copyNewFieldsFrom`. -/ private def getFieldType (infos : Array StructFieldInfo) (parentType : Expr) (fieldName : Name) : MetaM Expr := do withLocalDeclD (← mkFreshId) parentType fun parent => do let proj ← mkProjection parent fieldName let projType ← inferType proj /- Eliminate occurrences of `parent.field`. This happens when the structure contains dependent fields. If the copied parent extended another structure via a subobject, then the occurrence can also look like `parent.toGrandparent.field` (where `toGrandparent` is not a field of the current structure). -/ let visit (e : Expr) : MetaM TransformStep := do if let Expr.const subProjName .. := e.getAppFn then if let some { numParams, .. } ← getProjectionFnInfo? subProjName then let Name.str _ subFieldName .. := subProjName | throwError "invalid projection name {subProjName}" let args := e.getAppArgs if let some major := args.get? numParams then if (← getNestedProjectionArg major) == parent then if let some existingFieldInfo := findFieldInfo? infos subFieldName then return TransformStep.done <| mkAppN existingFieldInfo.fvar args[numParams+1:args.size] return TransformStep.done e let projType ← Meta.transform projType (post := visit) if projType.containsFVar parent.fvarId! then throwError "unsupported dependent field in {fieldName} : {projType}" if let some info := getFieldInfo? (← getEnv) (← getStructureName parentType) fieldName then if let some autoParamExpr := info.autoParam? then return (← mkAppM ``autoParam #[projType, autoParamExpr]) return projType private def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do if isProtected (← getEnv) fieldInfo.projFn then return Visibility.protected else if isPrivateName fieldInfo.projFn then return Visibility.private else return Visibility.regular abbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field /-- Reduce projetions of the structures in `structNames` -/ private def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr := let reduce (e : Expr) : MetaM TransformStep := do match (← reduceProjOf? e structNames.contains) with | some v => return TransformStep.done v | _ => return TransformStep.done e transform e (post := reduce) /-- Copy the default value for field `fieldName` set at structure `structName`. The arguments for the `_default` auxiliary function are provided by `fieldMap`. Recall some of the entries in `fieldMap` are constructor applications, and they needed to be reduced using `reduceProjs`. Otherwise, the produced default value may be "cyclic". That is, we reduce projections of the structures in `expandedStructNames`. Here is an example that shows why the reduction is needed. ``` structure A where a : Nat structure B where a : Nat b : Nat c : Nat structure C extends B where d : Nat c := b + d structure D extends A, C #print D.c._default ``` Without the reduction, it produces ``` def D.c._default : A → Nat → Nat → Nat → Nat := fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d) ``` -/ private partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do match getDefaultFnForField? (← getEnv) structName fieldName with | none => return none | some defaultFn => let cinfo ← getConstInfo defaultFn let us ← mkFreshLevelMVarsFor cinfo go? (← instantiateValueLevelParams cinfo us) where failed : TermElabM (Option Expr) := do logWarning s!"ignoring default value for field '{fieldName}' defined at '{structName}'" return none go? (e : Expr) : TermElabM (Option Expr) := do match e with | Expr.lam n d b c => if c.isExplicit then match fieldMap.find? n with | none => failed | some val => let valType ← inferType val if (← isDefEq valType d) then go? (b.instantiate1 val) else failed else let arg ← mkFreshExprMVar d go? (b.instantiate1 arg) | e => let r := if e.isAppOfArity ``id 2 then e.appArg! else e return some (← reduceProjs (← instantiateMVars r) expandedStructNames) private partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do copyFields infos {} parentType fun infos _ _ => k infos where copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo → FieldMap → NameSet → TermElabM α) : TermElabM α := do let parentStructName ← getStructureName parentType let fieldNames := getStructureFields (← getEnv) parentStructName let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM α := do if h : i < fieldNames.size then let fieldName := fieldNames.get ⟨i, h⟩ let fieldType ← getFieldType infos parentType fieldName match findFieldInfo? infos fieldName with | some existingFieldInfo => let existingFieldType ← inferType existingFieldInfo.fvar unless (← isDefEq fieldType existingFieldType) do throwError "parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {← mkHasTypeButIsExpectedMsg fieldType existingFieldType}" /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/ copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames | none => let some fieldInfo := getFieldInfo? (← getEnv) parentStructName fieldName | unreachable! let addNewField : TermElabM α := do let value? ← copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do let fieldDeclName := structDeclName ++ fieldName let fieldDeclName ← applyVisibility (← toVisibility fieldInfo) fieldDeclName let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?, kind := StructFieldKind.copiedField } copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames if fieldInfo.subobject?.isSome then let fieldParentStructName ← getStructureName fieldType if (← findExistingField? infos fieldParentStructName).isSome then -- See comment at `copyDefaultValue?` let expandedStructNames := expandedStructNames.insert fieldParentStructName copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do let fieldVal ← mkCompositeField fieldType nestedFieldMap copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames else let subfieldNames := getStructureFieldsFlattened (← getEnv) fieldParentStructName let fieldName := fieldInfo.fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun parentFVar => let infos := infos.push { name := fieldName, declName := structDeclName ++ fieldName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields structDeclName parentFVar fieldParentStructName subfieldNames infos fun infos => copy (i+1) infos (fieldMap.insert fieldName parentFVar) expandedStructNames else addNewField else let infos ← processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName k infos fieldMap expandedStructNames copy 0 infos {} expandedStructNames processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) := infos.mapM fun info => do match (← copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with | some value => return { info with value? := value } | none => return info mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do let env ← getEnv let Expr.const parentStructName us ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do match fieldMap.find? fieldName with | some val => result := mkApp result val | none => throwError "failed to copy fields from parent structure{indentExpr parentType}" -- TODO improve error message return result private partial def mkToParentName (parentStructName : Name) (p : Name → Bool) : Name := Id.run do let base := Name.mkSimple $ "to" ++ parentStructName.eraseMacroScopes.getString! if p base then base else let rec go (i : Nat) : Name := let curr := base.appendIndexAfter i if p curr then curr else go (i+1) go 1 private partial def withParents (view : StructView) (k : Array StructFieldInfo → Array Expr → TermElabM α) : TermElabM α := do go 0 #[] #[] where go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parentType ← Term.elabType parentStx let parentStructName ← getStructureName parentType if let some existingFieldName ← findExistingField? infos parentStructName then if structureDiamondWarning.get (← getOptions) then logWarning s!"field '{existingFieldName}' from '{parentStructName}' has already been declared" copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType) -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure` else let env ← getEnv let subfieldNames := getStructureFieldsFlattened env parentStructName let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parentType fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents else k infos copiedParents private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := Term.withAutoBoundImplicit <| Term.withAutoBoundImplicitForbiddenPred (fun n => view.name == n) <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing -- TODO: add forbidden predicate using `shortDeclName` from `view` let params ← Term.addAutoBoundImplicits params let value ← Term.withoutAutoBoundImplicit <| Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.withoutAutoBoundImplicit <| Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do go 0 {} infos where go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref do match findFieldInfo? infos view.name with | none => let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.rawName view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField } go (i+1) defaultValsOverridden infos | none, some value => let type ← inferType value withLocalDecl view.rawName view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField } go (i+1) defaultValsOverridden infos | some info => let updateDefaultValue : TermElabM α := do match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else if defaultValsOverridden.contains info.name then throwError "field '{view.name}' new default value has already been set" let defaultValsOverridden := defaultValsOverridden.insert info.name let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType pushInfoLeaf <| .ofFieldRedeclInfo { stx := view.ref } let infos := updateFieldInfoVal infos info.name value go (i+1) defaultValsOverridden infos match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.subobject => throwError "unexpected subobject field reference" -- improve error message | StructFieldKind.copiedField => updateDefaultValue | StructFieldKind.fromParent => updateDefaultValue else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p type.collectFVars fieldInfos.forM fun info => do let fvarType ← inferType info.fvar fvarType.collectFVars match info.value? with | none => pure () | some value => value.collectFVars private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Meta.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts <| k vars private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (univToInfer? : Option LMVarId) : TermElabM (Array StructFieldInfo) := go |>.run' 1 where levelMVarToParam' (type : Expr) : StateRefT Nat TermElabM Expr := do Term.levelMVarToParam' type (except := fun mvarId => univToInfer? == some mvarId) go : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← levelMVarToParam' value pure { info with value? := value } levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| levelMVarToParam' type private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do let (_, us) ← go |>.run #[] return us where go : StateRefT (Array Level) TermElabM Unit := for info in fieldInfos do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u match (← modifyGet fun s => accLevel u r rOffset |>.run |>.run s) with | some _ => pure () | none => let typeType ← inferType type let mut msg := m!"failed to compute resulting universe level of structure, field '{info.declName}' has type{indentD m!"{type} : {typeType}"}\nstructure resulting type{indentExpr (mkSort (r.addOffset rOffset))}" if r.isMVar then msg := msg ++ "\nrecall that Lean only infers the resulting universe level automatically when there is a unique solution for the universe level constraints, consider explicitly providing the structure resulting universe level" throwError msg private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type return collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar return s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i]! let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | _ => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size true pure { name := view.ctor.declName, type } @[extern "lean_mk_projections"] private opaque mkProjections (env : Environment) (structName : Name) (projs : List Name) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List Name) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do let fields ← infos.filterMapM fun info => do if info.kind == StructFieldKind.fromParent then return none else return some { fieldName := info.name projFn := info.declName binderInfo := (← getFVarLocalDecl info.fvar).binderInfo autoParam? := (← inferType info.fvar).getAutoParamTactic? subobject? := if info.kind == StructFieldKind.subobject then match (← getEnv).find? info.declName with | some (ConstantInfo.defnInfo val) => match val.type.getForallBody.getAppFn with | Expr.const parentName .. => some parentName | _ => panic! "ill-formed structure" | _ => panic! "ill-formed environment" else none } modifyEnv fun env => Lean.registerStructure env { structName, fields } private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do let env ← getEnv let structName := view.declName let sourceFieldNames := getStructureFieldsFlattened env structName let structType := mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params let Expr.const parentStructName _ ← pure parentType.getAppFn | unreachable! let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl `self binfo structType fun source => do let declType ← instantiateMVars (← mkForallFVars params (← mkForallFVars #[source] parentType)) let declType := declType.inferImplicit params.size true let rec copyFields (parentType : Expr) : MetaM Expr := do let Expr.const parentStructName us ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do if sourceFieldNames.contains fieldName then let fieldVal ← mkProjection source fieldName result := mkApp result fieldVal else -- fieldInfo must be a field of `parentStructName` let some fieldInfo := getFieldInfo? env parentStructName fieldName | unreachable! if fieldInfo.subobject?.isNone then throwError "failed to build coercion to parent structure" let resultType ← whnfD (← inferType result) unless resultType.isForall do throwError "failed to build coercion to parent structure, unexpect type{indentExpr resultType}" let fieldVal ← copyFields resultType.bindingDomain! result := mkApp result fieldVal return result let declVal ← instantiateMVars (← mkLambdaFVars params (← mkLambdaFVars #[source] (← copyFields parentType))) let declName := structName ++ mkToParentName (← getStructureName parentType) fun n => !env.contains (structName ++ n) addAndCompile <| Declaration.defnDecl { name := declName levelParams := levelParams type := declType value := declVal hints := ReducibilityHints.abbrev safety := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } if binfo.isInstImplicit then addInstance declName AttributeKind.global (eval_prio default) else setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view fun fieldInfos copiedParents => do withFields view.fields fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let univToInfer? ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos fun scopeVars => do let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos univToInfer? let type ← withRef view.ref do if univToInfer?.isSome then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projNames := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => info.declName addProjections view.declName projNames view.isClass registerStructure view.declName fieldInfos mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) withSaveInfoContext do -- save new env Term.addLocalVarInfo view.ref[1] (← mkConstWithLevelParams view.declName) if let some _ := view.ctor.ref[1].getPos? (originalOnly := true) then Term.addTermInfo' view.ctor.ref[1] (← mkConstWithLevelParams view.ctor.declName) (isBinder := true) for field in view.fields do -- may not exist if overriding inherited field if (← getEnv).contains field.declName then Term.addTermInfo' field.ref (← mkConstWithLevelParams field.declName) (isBinder := true) Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking let projInstances := instParents.toList.map fun info => info.declName projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary "default value" declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating "default value" auxiliary functions else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers Term.withAutoBoundImplicitForbiddenPred (fun n => name == n) do addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers scopeLevelNames allUserLevelNames declName isClass scopeVars params parents type ctor fields } unless isClass do mkSizeOfInstances declName mkInjectiveTheorems declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] runTermElabM fun _ => Term.withDeclName declName do Term.applyAttributesAt declName modifiers.attrs .afterCompilation builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
c8fe9094b4e509bbb6a37783505aa107c9797749
367134ba5a65885e863bdc4507601606690974c1
/src/topology/sheaves/presheaf_of_functions.lean
e18031765b2c3cfa8fcd3483a535ae9c8c7474c9
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,392
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.yoneda import topology.sheaves.presheaf import topology.category.TopCommRing import topology.algebra.continuous_functions /-! # Presheaves of functions We construct some simple examples of presheaves of functions on a topological space. * `presheaf_to_Type X f`, where `f : X → Type`, is the presheaf of dependently-typed (not-necessarily continuous) functions * `presheaf_to_Type X T`, where `T : Type`, is the presheaf of (not-necessarily-continuous) functions to a fixed target type `T` * `presheaf_to_Top X T`, where `T : Top`, is the presheaf of continuous functions into a topological space `T` * `presheaf_To_TopCommRing X R`, where `R : TopCommRing` is the presheaf valued in `CommRing` of functions functions into a topological ring `R` * as an example of the previous construction, `presheaf_to_TopCommRing X (TopCommRing.of ℂ)` is the presheaf of rings of continuous complex-valued functions on `X`. -/ universes v u open category_theory open topological_space open opposite namespace Top variables (X : Top.{v}) /-- The presheaf of dependently typed functions on `X`, with fibres given by a type family `f`. There is no requirement that the functions are continuous, here. -/ def presheaf_to_Types (T : X → Type v) : X.presheaf (Type v) := { obj := λ U, Π x : (unop U), T x, map := λ U V i g, λ (x : unop V), g (i.unop x) } @[simp] lemma presheaf_to_Types_obj {T : X → Type v} {U : (opens X)ᵒᵖ} : (presheaf_to_Types X T).obj U = Π x : (unop U), T x := rfl @[simp] lemma presheaf_to_Types_map {T : X → Type v} {U V : (opens X)ᵒᵖ} {i : U ⟶ V} {f} : (presheaf_to_Types X T).map i f = λ x, f (i.unop x) := rfl /-- The presheaf of functions on `X` with values in a type `T`. There is no requirement that the functions are continuous, here. -/ -- We don't just define this in terms of `presheaf_to_Types`, -- as it's helpful later to see (at a syntactic level) that `(presheaf_to_Type X T).obj U` -- is a non-dependent function. -- We don't use `@[simps]` to generate the projection lemmas here, -- as it turns out to be useful to have `presheaf_to_Type_map` -- written as an equality of functions (rather than being applied to some argument). def presheaf_to_Type (T : Type v) : X.presheaf (Type v) := { obj := λ U, (unop U) → T, map := λ U V i g, g ∘ i.unop } @[simp] lemma presheaf_to_Type_obj {T : Type v} {U : (opens X)ᵒᵖ} : (presheaf_to_Type X T).obj U = ((unop U) → T) := rfl @[simp] lemma presheaf_to_Type_map {T : Type v} {U V : (opens X)ᵒᵖ} {i : U ⟶ V} {f} : (presheaf_to_Type X T).map i f = f ∘ i.unop := rfl /-- The presheaf of continuous functions on `X` with values in fixed target topological space `T`. -/ def presheaf_to_Top (T : Top.{v}) : X.presheaf (Type v) := (opens.to_Top X).op ⋙ (yoneda.obj T) @[simp] lemma presheaf_to_Top_obj (T : Top.{v}) (U : (opens X)ᵒᵖ) : (presheaf_to_Top X T).obj U = ((opens.to_Top X).obj (unop U) ⟶ T) := rfl /-- The (bundled) commutative ring of continuous functions from a topological space to a topological commutative ring, with pointwise multiplication. -/ -- TODO upgrade the result to TopCommRing? def continuous_functions (X : Top.{v}ᵒᵖ) (R : TopCommRing.{v}) : CommRing.{v} := CommRing.of (unop X ⟶ (forget₂ TopCommRing Top).obj R) namespace continuous_functions /-- Pulling back functions into a topological ring along a continuous map is a ring homomorphism. -/ def pullback {X Y : Topᵒᵖ} (f : X ⟶ Y) (R : TopCommRing) : continuous_functions X R ⟶ continuous_functions Y R := { to_fun := λ g, f.unop ≫ g, map_one' := rfl, map_zero' := rfl, map_add' := by tidy, map_mul' := by tidy } /-- A homomorphism of topological rings can be postcomposed with functions from a source space `X`; this is a ring homomorphism (with respect to the pointwise ring operations on functions). -/ def map (X : Top.{u}ᵒᵖ) {R S : TopCommRing.{u}} (φ : R ⟶ S) : continuous_functions X R ⟶ continuous_functions X S := { to_fun := λ g, g ≫ ((forget₂ TopCommRing Top).map φ), map_one' := by ext; exact φ.1.map_one, map_zero' := by ext; exact φ.1.map_zero, map_add' := by intros; ext; apply φ.1.map_add, map_mul' := by intros; ext; apply φ.1.map_mul } end continuous_functions /-- An upgraded version of the Yoneda embedding, observing that the continuous maps from `X : Top` to `R : TopCommRing` form a commutative ring, functorial in both `X` and `R`. -/ def CommRing_yoneda : TopCommRing.{u} ⥤ (Top.{u}ᵒᵖ ⥤ CommRing.{u}) := { obj := λ R, { obj := λ X, continuous_functions X R, map := λ X Y f, continuous_functions.pullback f R }, map := λ R S φ, { app := λ X, continuous_functions.map X φ } } /-- The presheaf (of commutative rings), consisting of functions on an open set `U ⊆ X` with values in some topological commutative ring `T`. For example, we could construct the presheaf of continuous complex valued functions of `X` as ``` presheaf_to_TopCommRing X (TopCommRing.of ℂ) ``` (this requires `import topology.instances.complex`). -/ def presheaf_to_TopCommRing (T : TopCommRing.{v}) : X.presheaf CommRing.{v} := (opens.to_Top X).op ⋙ (CommRing_yoneda.obj T) end Top
108263d91ec0b363a5ab59007204e159d8dc5dca
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/algebraic_geometry/general_linear_group.lean
33eacae4ac15374a45cf63396c52f95f7f3c97bc
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
13,741
lean
/- In this file we define the general linear group as an affine group over a discrete field `K`-/ import .affine_variety group_theory.perm.sign ..to_mathlib category_theory.instances.groups open topological_space function sum finsupp category_theory tensor_product category_theory.limits universe u local attribute [instance, priority 1] limits.category_theory.limits.has_limit limits.category_theory.limits.has_colimit limits.category_theory.limits.has_colimits limits.category_theory.limits.has_limits limits.category_theory.limits.has_limits_of_shape limits.category_theory.limits.has_colimits_of_shape variables (K : Type u) [discrete_field K] {n : ℕ} noncomputable theory namespace algebraic_geometry namespace GL open mv_polynomial /-- The `K`-algebra `K[x₀,xᵢⱼ]` for `i,j ∈ {1, ... n}` -/ def GL_aux1 (n : ℕ) : FRAlgebra K := FRAlgebra_mv_polynomial.{u 0} K (fin n × fin n ⊕ unit) /-- Auxiliary definition for the determinant: the graph of a map out of a finite type -/ def det_aux {α β : Type*} [fintype α] [decidable_eq β] (f : α → β) : α × β →₀ ℕ := on_finset (finset.univ.product $ finset.univ.image f) (λ⟨a, b⟩, if f a = b then 1 else 0) (by { rintro ⟨a, b⟩ h, dsimp [det_aux._match_1] at h, cases ite_ne_neg h, simp }) /-- Auxiliary definition for the determinant: the graph of a map out of a finite type as an embedding -/ def det_aux2 {α β : Type*} [fintype α] [decidable_eq β] : (α → β) ↪ α × β →₀ ℕ := ⟨det_aux, omitted⟩ /-- Auxiliary definition for the determinant: the function that turns an equivalence into a monomial in a polynomial ring over one extra variable. -/ def det_aux3 {α β : Type*} [fintype α] [decidable_eq α] [decidable_eq β] : (α ≃ β) ↪ α × β ⊕ unit →₀ ℕ := equiv.equiv_embedding_fun.trans $ det_aux2.trans $ finsupp_embedding_finsupp_left sum.embedding_inl /-- We define the determinant as a multivariate polynomial follows: * We can embed permutations `fin n ≃ fin n` into `fin n × fin n →₀ ℕ` using the characteristic map of the graph of the function. * If a monomial corresponds to a permutation, then its coefficient is the sign of the permutation, otherwise it is `0`. -/ def det (n : ℕ) : GL_aux1 K n := emb_domain det_aux3 $ equiv_fun_on_fintype.inv_fun $ λ e, int.cast $ equiv.perm.sign e /-- The element `x₀ * det(xᵢⱼ) - 1` in `K[x₀,xᵢⱼ]` by which we quotient to obtain `GL(n)` -/ def GL_element (n : ℕ) : GL_aux1 K n := X (inr ⟨⟩) * det K n - 1 /-- The ideal spanned by `x₀ * det(xᵢⱼ) - 1` is radical -/ lemma radical_ideal_span_det (n : ℕ) : (ideal.span ({ GL_element K n } : set (GL_aux1 K n))).is_radical := omitted /-- The ideal spanned by `x₀ * det(xᵢⱼ) - 1` as a radical ideal -/ def GL_aux (n : ℕ) : ideal.radical_ideal (GL_aux1 K n) := ⟨(ideal.span ({ GL_element K n } : set (GL_aux1 K n))), by apply radical_ideal_span_det K n⟩ /-- The general linear group is defined as `K[x₀,xᵢⱼ]/(x₀ * det(xᵢⱼ) - 1)` -/ def GL_op (n : ℕ) : FRAlgebra K := ⟨K, (GL_aux K n).val.quotient⟩ /-- The general linear group as an affine variety -/ def GL_var (n : ℕ) : affine_variety K := op (GL_op K n) variable {K} section set_option class.instance_max_depth 80 /-- The (opposite of the) multiplication on `GL(n)`. It uses the formula for matrix multiplcation, sending `xᵢⱼ` to `Σₖ xᵢₖ ⊗ xₖⱼ`. It sends `x₀` to `x₀ ⊗ x₀` -/ def GL_mul_op : GL_op K n ⟶ FRAlgebra_tensor (GL_op K n) (GL_op K n) := algebra.quotient.lift begin refine alg_hom.comp (tensor_functor (algebra.quotient.mk _) (algebra.quotient.mk _)) _, refine aeval₂ _, rintro (⟨i,j⟩|⟨⟩), { refine (finset.univ : finset (fin n)).sum _, intro k, exact tmul K (X $ inl ⟨i, k⟩) (X $ inl ⟨k, j⟩) }, { exact tmul K (X $ inr ⟨⟩) (X $ inr ⟨⟩) } end omitted end /-- The `(i,j)`-minor is the polynomial that is obtained by taking the formula for the determinant, but skipping row `i` and column `j`. -/ def minor (i j : fin n) : GL_aux1 K n := begin cases n with n, apply fin_zero_elim i, exact rename (sum.map (prod.map (fin.succ_above i) (fin.succ_above j)) id) (det K n) end /-- The (opposite of the) inversion on `GL(n)`. The inverse sends `xᵢⱼ` to `(-1) ^ (i + j)` times the transpose of the `(i,j)`-minor. It sends `x₀` to `det(xᵢⱼ)` -/ def GL_inv_op : GL_op K n ⟶ GL_op K n := algebra.quotient.functor begin refine aeval₂ _, rintro (⟨i,j⟩|⟨⟩), { exact (-1) ^ (i.val + j.val) * minor j i }, { exact det K n } end omitted /-- The (opposite of the) unit in `GL(n)` -/ def GL_one_op : GL_op K n ⟶ FRAlgebra_id K := algebra.quotient.lift begin refine aeval₂ _, rintro (⟨i,j⟩|⟨⟩), { exact if i = j then 1 else 0 }, { exact 1 } end omitted variable (K) /-- The general linear group as an affine group -/ def GL (n : ℕ) : affine_group K := { obj := GL_var K n, mul := GL_mul_op.op, mul_assoc := omitted, one := GL_one_op.op, one_mul := omitted, mul_one := omitted, inv := GL_inv_op.op, mul_left_inv := omitted } /-- A torus is an `r`-fold product of `GL(1)` -/ def torus (r : ℕ) : affine_group K := category.pow (GL K 1) r /-- The multiplicative affine group is `torus K 1` -/ @[reducible] def Gm : affine_group K := torus K 1 variable {K} /- The map `n ↦ X ^ n`. It sends `(-n)` to `(X⁻¹)^n` for a natural number n -/ def X_pow : ℤ → (unop (Gm K).1).β | (int.of_nat n) := ideal.quotient.mk _ (monomial (single (inl ⟨0, 0⟩) n) 1) | -[1+n] := ideal.quotient.mk _ (monomial (single (inr ⟨⟩) (n+1)) 1) /-- Every group morphism `Gm ⟶ Gm` sends the variable `X` to `X^n` for some integer `n`. -/ def deg_aux (ϕ : Gm K ⟶ Gm K) : ∃!(n : ℤ), ϕ.map.unop.to_fun (ideal.quotient.mk _ $ X $ inl ⟨0, 0⟩) = X_pow n := omitted /-- The degree of a group morphism `Gm K ⟶ Gm K` is the unique number `n` such that it sends `X` to `X^n` -/ def deg (ϕ : Gm K ⟶ Gm K) : ℤ := classical.the _ (deg_aux ϕ) instance torus1.is_abelian : (Gm K).is_abelian := omitted lemma nonzero_determinant (p : (GL_var K n).type) : p.to_fun (ideal.quotient.mk _ (det K n)) ≠ (0 : K) := omitted /-- The torus is an abelian group -/ instance is_abelian_torus (r : ℕ) : (torus K r).is_abelian := omitted variable {G : affine_group K} /-- A maximal torus is a closed subgroup of `G` that is isomorphic to `torus K r` with `r` maximal. -/ class is_maximal_torus (T : set G.obj.type) extends is_closed_subgroup T : Prop := (max_torus : ∃(n : ℕ), nonempty (sub T ≅ torus K n) ∧ is_maximal { m : ℕ | ∃(s : set G.obj.type) (h : is_closed_subgroup s), by exactI nonempty (sub s ≅ torus K m) } n) def is_maximal_torus.elim {T : set G.obj.type} (h₂ : is_maximal_torus T) := is_maximal_torus.max_torus T instance is_maximal_torus.is_abelian (T : set G.obj.type) [is_maximal_torus T] : (sub T).is_abelian := omitted /- The rank of a maximal torus -/ def is_maximal_torus.rank (T : set G.obj.type) [h : is_maximal_torus T] : ℕ := classical.take_arbitrary_such_that (λ n, n) h.elim omitted /-- Every group has a maximal torus -/ lemma has_maximal_torus (G : affine_group K) : ∃(T : set G.obj.type), is_maximal_torus T := omitted /-- The rank of `G` is the number `n` such that `T ≅ torus n` where `T` is any maximal torus of `G`. -/ def rank (G : affine_group K) : ℕ := classical.take_arbitrary (λ ⟨T, hT⟩, by exactI is_maximal_torus.rank T : { T : set (G.obj.type) // is_maximal_torus T} → ℕ) (subtype.nonempty $ has_maximal_torus G) omitted /-- The character group `X^*(T)` of `T` consists of group morphisms into `Gm K` -/ @[reducible] def character_group (T : set G.obj.type) [is_closed_subgroup T] : Type* := sub T ⟶ Gm K /-- The character group froms an abelian group -/ example (T : set G.obj.type) [is_closed_subgroup T] : comm_group (character_group T) := infer_instance open category_theory.instances /-- The character group is a free group on `rank G` variables -/ lemma free_character_group (T : set G.obj.type) [is_maximal_torus T] : nonempty $ (mk_ob $ character_group T : Group) ≅ mk_ob (multiplicative $ free_abelian_group $ ulift $ fin $ rank G) := omitted /-- As a more concrete example, we give the underlying functions of the isomorphism between `Gm K ⟶ Gm K` and the free abelian group on a single generator -/ def hom_torus1 : (mk_ob $ (Gm K) ⟶ Gm K : Group) ≅ mk_ob (multiplicative $ free_abelian_group punit) := { hom := ⟨λ ϕ, free_abelian_group.of ⟨⟩ ^ deg ϕ, omitted⟩, inv := ⟨λ n, show additive $ Gm K ⟶ Gm K, from n.lift (λ x, 𝟙 _), omitted⟩, hom_inv_id' := omitted, inv_hom_id' := omitted } /-- The cocharacter group `X_*(T)` of `T` consists of group morphisms from `Gm K` -/ @[reducible] def cocharacter_group (T : set G.obj.type) [is_closed_subgroup T] : Type* := Gm K ⟶ sub T example (T : set G.obj.type) [is_maximal_torus T] : comm_group (cocharacter_group T) := infer_instance /-- The cocharacter group is a free group on `rank G` variables -/ lemma free_cocharacter_group (T : set G.obj.type) [is_maximal_torus T] : nonempty $ (mk_ob $ cocharacter_group T : Group) ≅ mk_ob (multiplicative $ free_abelian_group $ ulift $ fin $ rank G) := omitted /-- There is a pairing between the character group and the cocharacter group of `T`. -/ def pair {T : set G.obj.type} [is_closed_subgroup T] (l : character_group T) (r : cocharacter_group T) : ℤ := deg $ r ≫ l end GL -- TODO: pair is nondegenerate and bilinear variables (K) namespace Ga open polynomial GL /-- The underlying affine variety of the additive affine group is the variety whose coordinate ring is `K[x]` -/ def Ga_var : affine_variety K := op $ FRAlgebra_polynomial K variables {K} /-- The (opposite of the) multiplication on `Ga`. It sends `x` to `x ⊗ 1 + 1 ⊗ x` -/ def Ga_mul_op : FRAlgebra_polynomial K ⟶ FRAlgebra_tensor (FRAlgebra_polynomial K) (FRAlgebra_polynomial K) := aeval _ _ $ tmul K X 1 + tmul K 1 X /-- The (opposite of the) inversion on `Ga`. It sends `x` to `-x` -/ def Ga_inv_op : FRAlgebra_polynomial K ⟶ FRAlgebra_polynomial K := aeval _ _ $ -X /-- The (opposite of the) unit in `Ga` -/ def Ga_one_op : FRAlgebra_polynomial K ⟶ FRAlgebra_id K := aeval _ _ 0 variables (K) /-- The additive affine group -/ def Ga : affine_group K := { obj := Ga_var K, mul := Ga_mul_op.op, mul_assoc := omitted, one := Ga_one_op.op, one_mul := omitted, mul_one := omitted, inv := Ga_inv_op.op, mul_left_inv := omitted } local infix ` × `:60 := limits.binary_product /-- The group `Gm` acts on `Ga`. -/ def mul_add_action : group_action (Gm K) (Ga K).obj := ⟨(show FRAlgebra_polynomial K ⟶ FRAlgebra_tensor (GL_op K 1) (FRAlgebra_polynomial K), from aeval _ _ $ tmul _ (ideal.quotient.mk _ $ mv_polynomial.X $ inl $ ⟨0, 0⟩) X).op, omitted, omitted⟩ end Ga open GL Ga variables {K} variables {G : affine_group K} (B T : set G.obj.type) [is_closed_subgroup B] [is_maximal_torus T] local infix ` × `:60 := limits.binary_product local infix ` ×.map `:90 := binary_product.map structure positive_root_space := (X : set G.obj.type) (hX : is_closed_subgroup X) (hXU : X ⊆ closed_derived_subgroup B) (f : sub X ≅ Ga K) (hTX : normalizes T X) attribute [instance] positive_root_space.hX variables {B T} def is_positive_root (X : positive_root_space B T) (l : character_group T) : Prop := (conjugation_action X.hTX).map = l.map ×.map X.f.hom.map ≫ (mul_add_action K).map ≫ X.f.inv.map -- def positive_root (X : positive_root_space B T) : Type* := -- { l : character_group T // is_positive_root X l } lemma unique_positive_root (hG : almost_simple G) (hB : is_Borel_subgroup B) (hTB : T ⊆ B) (X : positive_root_space B T) : ∃!(l : character_group T), is_positive_root X l := omitted variables (B T) def Phi_plus : set (character_group T) := { l : character_group T | ∃(X : positive_root_space B T), is_positive_root X l } notation `Φ⁺` := Phi_plus lemma finite_Phi_plus (hG : almost_simple G) (hB : is_Borel_subgroup B) (hTB : T ⊆ B) : set.finite (Φ⁺ B T) := omitted variables {B T} variables (α : character_group T) local notation `M'` := closed_derived_subgroup $ centralizer $ kernel $ α lemma almost_simple_M' (hG : almost_simple G) (hB : is_Borel_subgroup B) (hTB : T ⊆ B) (hα : α ∈ Φ⁺ B T) : almost_simple $ sub M' := omitted def is_positive_coroot (αv : cocharacter_group T) : Prop := ∃(S : set (sub M').obj.type) (hS₁ : is_maximal_torus S), by exactI factors_through αv.map ((sub T).incl $ set_sub_incl S).map ∧ GL.pair α αv = 2 lemma unique_positive_coroot (hG : almost_simple G) (hB : is_Borel_subgroup B) (hTB : T ⊆ B) (hα : α ∈ Φ⁺ B T) : ∃!(αv : cocharacter_group T), is_positive_coroot α αv := omitted variables (B T) def positive_coroots : set (cocharacter_group T) := { αv : cocharacter_group T | ∃(α ∈ Φ⁺ B T), is_positive_coroot α αv } -- todo: move def cone {α} [comm_monoid α] [decidable_eq α] (s : set α) : set α := { x : α | ∃(t : finset α) (a : α → ℕ), ↑t ⊆ s ∧ t.prod (λ(y : α), y ^ a y) = x } variables {B T} section local attribute [instance, priority 0] classical.prop_decidable lemma unique_simple_roots (hG : almost_simple G) (hB : is_Borel_subgroup B) (hTB : T ⊆ B) : ∃!(Δ : set (character_group T)), Δ ⊆ Φ⁺ B T ∧ Φ⁺ B T ⊆ cone Δ := omitted end def simple_roots (hG : almost_simple G) (hB : is_Borel_subgroup B) (hTB : T ⊆ B) : set (character_group T) := classical.the _ $ unique_simple_roots hG hB hTB end algebraic_geometry
510c8b8f70398006e2d55caa0575fdd104d33303
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/zfc/ordinal.lean
b24835b989ce9c8bb9f3eb40950c235a1b474b0c
[ "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
2,641
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.zfc.basic /-! # Von Neumann ordinals This file works towards the development of von Neumann ordinals, i.e. transitive sets, well-ordered under `∈`. We currently only have an initial development of transitive sets. Further development can be found on the branch `von_neumann_v2`. ## Definitions - `Set.is_transitive` means that every element of a set is a subset. ## Todo - Define von Neumann ordinals. - Define the basic arithmetic operations on ordinals from a purely set-theoretic perspective. - Prove the equivalences between these definitions and those provided in `set_theory/ordinal/arithmetic.lean`. -/ universe u variables {x y z : Set.{u}} namespace Set /-- A transitive set is one where every element is a subset. -/ def is_transitive (x : Set) : Prop := ∀ y ∈ x, y ⊆ x @[simp] theorem empty_is_transitive : is_transitive ∅ := λ y hy, (mem_empty y hy).elim theorem is_transitive.subset_of_mem (h : x.is_transitive) : y ∈ x → y ⊆ x := h y theorem is_transitive_iff_mem_trans : z.is_transitive ↔ ∀ {x y : Set}, x ∈ y → y ∈ z → x ∈ z := ⟨λ h x y hx hy, h.subset_of_mem hy hx, λ H x hx y hy, H hy hx⟩ alias is_transitive_iff_mem_trans ↔ is_transitive.mem_trans _ protected theorem is_transitive.inter (hx : x.is_transitive) (hy : y.is_transitive) : (x ∩ y).is_transitive := λ z hz w hw, by { rw mem_inter at hz ⊢, exact ⟨hx.mem_trans hw hz.1, hy.mem_trans hw hz.2⟩ } protected theorem is_transitive.sUnion (h : x.is_transitive) : (⋃₀ x).is_transitive := λ y hy z hz, begin rcases mem_sUnion.1 hy with ⟨w, hw, hw'⟩, exact mem_sUnion_of_mem hz (h.mem_trans hw' hw) end theorem is_transitive.sUnion' (H : ∀ y ∈ x, is_transitive y) : (⋃₀ x).is_transitive := λ y hy z hz, begin rcases mem_sUnion.1 hy with ⟨w, hw, hw'⟩, exact mem_sUnion_of_mem ((H w hw).mem_trans hz hw') hw end theorem is_transitive_iff_sUnion_subset : x.is_transitive ↔ ⋃₀ x ⊆ x := ⟨λ h y hy, by { rcases mem_sUnion.1 hy with ⟨z, hz, hz'⟩, exact h.mem_trans hz' hz }, λ H y hy z hz, H $ mem_sUnion_of_mem hz hy⟩ alias is_transitive_iff_sUnion_subset ↔ is_transitive.sUnion_subset _ theorem is_transitive_iff_subset_powerset : x.is_transitive ↔ x ⊆ powerset x := ⟨λ h y hy, mem_powerset.2 $ h.subset_of_mem hy, λ H y hy z hz, mem_powerset.1 (H hy) hz⟩ alias is_transitive_iff_subset_powerset ↔ is_transitive.subset_powerset _ end Set
a2c1816cc7bd26881d2ffe427ec1569e5f79000d
fe25de614feb5587799621c41487aaee0d083b08
/tests/lean/run/new_compiler.lean
75db267656527bed69f1d7187f1a764f1787143f
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,744
lean
universe u v w r s set_option trace.compiler.stage1 true -- set_option pp.explicit true set_option pp.binderTypes false -- set_option pp.proofs true def foo (n : Nat) : Nat := let x := Nat.zero; let x1 := Nat.succ x; let x2 := Nat.succ x1; let x3 := Nat.succ x2; let x4 := Nat.succ x3; let x5 := Nat.succ x4; let x6 := Nat.succ x5; let x7 := Nat.succ x ; let x8 := Nat.succ x7; let y1 := x; let y2 := y1; y2 + n def cseTst (n : Nat) : Nat := let y := Nat.succ ((fun x => x) n); let z := Nat.succ n; y + z def tst1 (n : Nat) : Nat := let p := (Nat.succ n, n); let q := (p, p); match q with | ((z, w), y) => z def tst2 (n : Nat) : Nat := let p := (fun x => Nat.succ x, Nat.zero) ; let f := fun (p : (Nat → Nat) × Nat) => p.1; f p n partial def add' : Nat → Nat → Nat | 0, b => Nat.succ b | a+1, b => Nat.succ (Nat.succ (add' a b)) def aux (i : Nat) (h : i > 0) := i axiom bad (α : Sort u) : α unsafe def foo2 : Nat := @False.rec (fun _ => Nat) (bad _) set_option pp.notation false def foo3 (n : Nat) : Nat := (fun (a : Nat) => a + a + a) (n*n) def boo (a : Nat) (l : List Nat) : List Nat := let f := @List.cons Nat; f a (f a l) def bla (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat := @And.rec _ _ (fun _ => Nat) (fun h₁ h₂ => aux i h₁ + aux i h₁) h def bla' (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat := @And.casesOn _ _ (fun _ => Nat) h (fun h₁ h₂ => aux i h₁ + aux i h₁) inductive vec (α : Type u) : Nat → Type u | nil : vec α 0 | cons : ∀ {n}, α → vec α n → vec α (Nat.succ n) /- def vec.map {α β σ : Type u} (f : α → β → σ) : ∀ {n : Nat}, vec α n → vec β n → vec σ n | _, nil, nil => nil | _, cons a as, cons b bs => cons (f a b) (map f as bs) -/
8982243b1f87b76627f0f4da803196ebeb34d2b8
367134ba5a65885e863bdc4507601606690974c1
/src/topology/sheaves/sheaf_of_functions.lean
e7900dc0d43cdfacd47e1bdd562e84bceb79400f
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,409
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import topology.sheaves.presheaf_of_functions import topology.sheaves.sheaf import category_theory.limits.shapes.types import topology.local_homeomorph /-! # Sheaf conditions for presheaves of (continuous) functions. We show that * `Top.sheaf_condition.to_Type`: not-necessarily-continuous functions into a type form a sheaf * `Top.sheaf_condition.to_Types`: in fact, these may be dependent functions into a type family For * `Top.sheaf_condition.to_Top`: continuous functions into a topological space form a sheaf please see `topology/sheaves/local_predicate.lean`, where we set up a general framework for constructing sub(pre)sheaves of the sheaf of dependent functions. ## Future work Obviously there's more to do: * sections of a fiber bundle * various classes of smooth and structure preserving functions * functions into spaces with algebraic structure, which the sections inherit -/ open category_theory open category_theory.limits open topological_space open topological_space.opens universe u noncomputable theory variables (X : Top.{u}) open Top namespace Top.presheaf /-- We show that the presheaf of functions to a type `T` (no continuity assumptions, just plain functions) form a sheaf. In fact, the proof is identical when we do this for dependent functions to a type family `T`, so we do the more general case. -/ def to_Types (T : X → Type u) : sheaf_condition (presheaf_to_Types X T) := λ ι U, -- U is a family of open sets, indexed by `ι`. -- In the informal comments below, I'll just write `U` to represent the union. begin refine fork.is_limit.mk _ _ _ _, { -- Our first goal is to define a function "lifted" to all of `U`, given -- `s`, some cone over the sheaf condition diagram -- (which we can think of as some type `s.X` which we know nothing about, -- except how to restrict terms to each of the `U i`, obtaining a function there, -- and that these restrictions are compatible), and -- `f`, a term of `s.X`. -- We do this one point at a time, so we also pick some `x` and the evidence `mem : x ∈ supr U`. rintros s f ⟨x, mem⟩, change x ∈ supr U at mem, -- FIXME there is a stray `has_coe_t_aux.coe` here -- Since `x ∈ supr U`, there must be some `i` so `x ∈ U i`: simp [opens.mem_supr] at mem, choose i hi using mem, -- We define out function to be the restriction of `f` to that `U i`, evaluated at `x`. exact ((s.ι ≫ pi.π _ i) f) ⟨x, hi⟩, }, { -- Now we need to verify that this lifted function restricts correctly to each set `U i`. -- Of course, the difficulty is that at any given point `x ∈ U i`, -- we may have used the axiom of choice to pick a differnt `j` with `x ∈ U j` -- when defining the function. -- This we'll need to use the fact that the restrictions are compatible. -- Again, we begin with some `s`, a cone over the sheaf condition diagram. intros s, -- The goal at this point is fairly inscrutable, -- but we know we're trying two functions are equal, so we call `ext` and see what we get: ext i f ⟨x, mem⟩, dsimp at mem, -- We now have `i : ι`, a term `f : s.X`, and a point `x` with `mem : x ∈ U i`. -- We clean up the goal a little, simp only [exists_prop, set.mem_range, set.mem_image, exists_exists_eq_and, category.assoc], simp only [limit.lift_π, types_comp_apply, fan.mk_π_app, presheaf_to_Type], dsimp, -- although you still need to be ambitious to read it. -- The mathematical content, of course, is that the lifted function we constructed from `f`, -- when restricted to `U i` and evaluated at `x`, -- has the same value as `f` restricted to to `U i` and evaluated at `x`. -- We have a slightly annoying issue at this point, -- that we're not really sure which `j : ι` was used to define the lifted function -- and this point `x`, because we used choice. -- As a trick, we create a new metavariable `j` to represent this choice, -- and later in the proof it will be solved by unification. let j : ι := _, -- Now, we assert that the two restrictions of `f` to `U i` and `U j` coincide on `U i ⊓ U j`, -- and in particular coincide there after evaluating at `x`. have s₀ := s.condition =≫ pi.π _ (j, i), simp only [sheaf_condition_equalizer_products.left_res, sheaf_condition_equalizer_products.right_res] at s₀, have s₁ := congr_fun s₀ f, have s₂ := congr_fun s₁ ⟨x, _⟩, clear s₀ s₁, -- Notice at this point we've spun after an additional goal: -- that `x ∈ U j ⊓ U i` to begin with! Let's get that out of the way. swap, { -- We knew `x ∈ U i` right from the start: refine ⟨_, mem⟩, -- Notice that when we introduced `j`, we just introduced it as some metavariable. -- However at this point it's received a concrete value, -- because Lean's unification has worked out that this `j` must have been the index -- that we picked using choice back when constructing the lift. -- From this, we can extract the evidence that `x ∈ U j`: convert @classical.some_spec _ (λ i, x ∈ (U i : set X)) _, }, -- Now, we can just assert that `s₂` is the droid you are looking for, -- and do a little patching up afterwards. convert s₂, { simp only [sheaf_condition_equalizer_products.res, presheaf_to_Types_map, types.pi_lift_π_apply, types_comp_apply], dsimp [inf_le_left_apply], simp, refl, }, { simp, refl, }, }, { -- On the home stretch now, -- we just need to check that the lift we picked was the only possible one. -- So we suppose we had some other way `m` of choosing lifts, intros s m w, -- and observe that we need to check that it agrees with our choice -- for each `f : s .X` and each `x ∈ supr U`. ext f ⟨x, mem⟩, -- Now `w` is the evidence that other choice of lift agrees either on the `U i`s, -- or on the `U i ⊓ U j`s. -- We'll need the later, specialize w walking_parallel_pair.zero, -- because we're not sure which arbitrary `j : ι` we used to define our lift. let j : ι := _, -- Now it's just a matter of plugging in all the values; -- `j` gets solved for during unification. convert congr_fun (congr_fun (w =≫ pi.π _ j) f) ⟨x, _⟩, simp [sheaf_condition_equalizer_products.res], refl, } end. -- We verify that the non-dependent version is an immediate consequence: /-- The presheaf of not-necessarily-continuous functions to a target type `T` satsifies the sheaf condition. -/ def to_Type (T : Type u) : sheaf_condition (presheaf_to_Type X T) := to_Types X (λ _, T) end Top.presheaf namespace Top /-- The sheaf of not-necessarily-continuous functions on `X` with values in type family `T : X → Type u`. -/ def sheaf_to_Types (T : X → Type u) : sheaf (Type u) X := { presheaf := presheaf_to_Types X T, sheaf_condition := presheaf.to_Types _ _, } /-- The sheaf of not-necessarily-continuous functions on `X` with values in a type `T`. -/ def sheaf_to_Type (T : Type u) : sheaf (Type u) X := { presheaf := presheaf_to_Type X T, sheaf_condition := presheaf.to_Type _ _, } end Top
9eba1ba230cc3aef8e0f14083ac2511488e107c4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/def8.lean
a2692880cce9c4669b5adb11eace30fe1e1ba52c
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
673
lean
inductive imf {A B : Type} (f : A → B) : B → Type | mk : ∀ (a : A), imf (f a) definition g {A B : Type} {f : A → B} : ∀ {b : B}, imf f b → A | .(f a) (imf.mk .f a) := a example {A B : Type} (f : A → B) (a : A) : g (imf.mk f a) = a := rfl definition v₁ : imf nat.succ 1 := (imf.mk nat.succ 0) definition v₂ : imf (λ x, 1 + x) 1 := (imf.mk (λ x, 1 + x) 0) example : g v₁ = 0 := rfl example : g v₂ = 0 := rfl lemma ex1 (A : Type) : ∀ (a b : A) (H : a = b), b = a | a .a rfl := rfl lemma ex2 (A : Type) : ∀ a b : A, a = b → b = a | a .a (eq.refl .a) := rfl lemma ex3 (A : Type) : ∀ a b : A, a = b → b = a | a ._ (eq.refl ._) := rfl
bcd891197bedcabc3864a600a13207ab8b800e75
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/metric_space/baire.lean
fcfd396b994f3753f55e2fda05a9c74bcc5f42f9
[ "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
17,015
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 analysis.specific_limits import order.filter.countable_Inter /-! # Baire theorem In a complete metric space, a countable intersection of dense open subsets is dense. The good concept underlying the theorem is that of a Gδ set, i.e., a countable intersection of open sets. Then Baire theorem can also be formulated as the fact that a countable intersection of dense Gδ sets is a dense Gδ set. We prove Baire theorem, giving several different formulations that can be handy. We also prove the important consequence that, if the space is covered by a countable union of closed sets, then the union of their interiors is dense. The names of the theorems do not contain the string "Baire", but are instead built from the form of the statement. "Baire" is however in the docstring of all the theorems, to facilitate grep searches. We also define the filter `residual α` generated by dense `Gδ` sets and prove that this filter has the countable intersection property. -/ noncomputable theory open_locale classical topological_space filter open filter encodable set variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} section is_Gδ variable [topological_space α] /-- A Gδ set is a countable intersection of open sets. -/ def is_Gδ (s : set α) : Prop := ∃T : set (set α), (∀t ∈ T, is_open t) ∧ countable T ∧ s = (⋂₀ T) /-- An open set is a Gδ set. -/ lemma is_open.is_Gδ {s : set α} (h : is_open s) : is_Gδ s := ⟨{s}, by simp [h], countable_singleton _, (set.sInter_singleton _).symm⟩ lemma is_Gδ_univ : is_Gδ (univ : set α) := is_open_univ.is_Gδ lemma is_Gδ_bInter_of_open {I : set ι} (hI : countable I) {f : ι → set α} (hf : ∀i ∈ I, is_open (f i)) : is_Gδ (⋂i∈I, f i) := ⟨f '' I, by rwa ball_image_iff, hI.image _, by rw sInter_image⟩ lemma is_Gδ_Inter_of_open [encodable ι] {f : ι → set α} (hf : ∀i, is_open (f i)) : is_Gδ (⋂i, f i) := ⟨range f, by rwa forall_range_iff, countable_range _, by rw sInter_range⟩ /-- A countable intersection of Gδ sets is a Gδ set. -/ lemma is_Gδ_sInter {S : set (set α)} (h : ∀s∈S, is_Gδ s) (hS : countable S) : is_Gδ (⋂₀ S) := begin choose T hT using h, refine ⟨_, _, _, (sInter_bUnion (λ s hs, (hT s hs).2.2)).symm⟩, { simp only [mem_Union], rintros t ⟨s, hs, tTs⟩, exact (hT s hs).1 t tTs }, { exact hS.bUnion (λs hs, (hT s hs).2.1) }, end lemma is_Gδ_Inter [encodable ι] {s : ι → set α} (hs : ∀ i, is_Gδ (s i)) : is_Gδ (⋂ i, s i) := is_Gδ_sInter (forall_range_iff.2 hs) $ countable_range s lemma is_Gδ_bInter {s : set ι} (hs : countable s) {t : Π i ∈ s, set α} (ht : ∀ i ∈ s, is_Gδ (t i ‹_›)) : is_Gδ (⋂ i ∈ s, t i ‹_›) := begin rw [bInter_eq_Inter], haveI := hs.to_encodable, exact is_Gδ_Inter (λ x, ht x x.2) end lemma is_Gδ.inter {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∩ t) := by { rw inter_eq_Inter, exact is_Gδ_Inter (bool.forall_bool.2 ⟨ht, hs⟩) } /-- The union of two Gδ sets is a Gδ set. -/ lemma is_Gδ.union {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) : is_Gδ (s ∪ t) := begin rcases hs with ⟨S, Sopen, Scount, rfl⟩, rcases ht with ⟨T, Topen, Tcount, rfl⟩, rw [sInter_union_sInter], apply is_Gδ_bInter_of_open (countable_prod Scount Tcount), rintros ⟨a, b⟩ hab, exact is_open_union (Sopen a hab.1) (Topen b hab.2) end end is_Gδ /-- A set `s` is called *residual* if it includes a dense `Gδ` set. If `α` is a Baire space (e.g., a complete metric space), then residual sets form a filter, see `mem_residual`. For technical reasons we define the filter `residual` in any topological space but in a non-Baire space it is not useful because it may contain some non-residual sets. -/ def residual (α : Type*) [topological_space α] : filter α := ⨅ t (ht : is_Gδ t) (ht' : closure t = univ), 𝓟 t section Baire_theorem open emetric ennreal variables [emetric_space α] [complete_space α] /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here when the source space is ℕ (and subsumed below by `dense_Inter_of_open` working with any encodable source space). -/ theorem dense_Inter_of_open_nat {f : ℕ → set α} (ho : ∀n, is_open (f n)) (hd : ∀n, closure (f n) = univ) : closure (⋂n, f n) = univ := begin let B : ℕ → ennreal := λn, 1/2^n, have Bpos : ∀n, 0 < B n, { intro n, simp only [B, div_def, one_mul, ennreal.inv_pos], exact pow_ne_top two_ne_top }, /- Translate the density assumption into two functions `center` and `radius` associating to any n, x, δ, δpos a center and a positive radius such that `closed_ball center radius` is included both in `f n` and in `closed_ball x δ`. We can also require `radius ≤ (1/2)^(n+1)`, to ensure we get a Cauchy sequence later. -/ have : ∀n x δ, δ > 0 → ∃y r, r > 0 ∧ r ≤ B (n+1) ∧ closed_ball y r ⊆ (closed_ball x δ) ∩ f n, { assume n x δ δpos, have : x ∈ closure (f n) := by simpa only [(hd n).symm] using mem_univ x, rcases emetric.mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, xy⟩, rw edist_comm at xy, obtain ⟨r, rpos, hr⟩ : ∃ r > 0, closed_ball y r ⊆ f n := nhds_basis_closed_eball.mem_iff.1 (is_open_iff_mem_nhds.1 (ho n) y ys), refine ⟨y, min (min (δ/2) r) (B (n+1)), _, _, λz hz, ⟨_, _⟩⟩, show 0 < min (min (δ / 2) r) (B (n+1)), from lt_min (lt_min (ennreal.half_pos δpos) rpos) (Bpos (n+1)), show min (min (δ / 2) r) (B (n+1)) ≤ B (n+1), from min_le_right _ _, show z ∈ closed_ball x δ, from calc edist z x ≤ edist z y + edist y x : edist_triangle _ _ _ ... ≤ (min (min (δ / 2) r) (B (n+1))) + (δ/2) : add_le_add hz (le_of_lt xy) ... ≤ δ/2 + δ/2 : add_le_add (le_trans (min_le_left _ _) (min_le_left _ _)) (le_refl _) ... = δ : ennreal.add_halves δ, show z ∈ f n, from hr (calc edist z y ≤ min (min (δ / 2) r) (B (n+1)) : hz ... ≤ r : le_trans (min_le_left _ _) (min_le_right _ _)) }, choose! center radius H using this, refine subset.antisymm (subset_univ _) (λx hx, _), refine (mem_closure_iff_nhds_basis nhds_basis_closed_eball).2 (λ ε εpos, _), /- `ε` is positive. We have to find a point in the ball of radius `ε` around `x` belonging to all `f n`. For this, we construct inductively a sequence `F n = (c n, r n)` such that the closed ball `closed_ball (c n) (r n)` is included in the previous ball and in `f n`, and such that `r n` is small enough to ensure that `c n` is a Cauchy sequence. Then `c n` converges to a limit which belongs to all the `f n`. -/ let F : ℕ → (α × ennreal) := λn, nat.rec_on n (prod.mk x (min ε (B 0))) (λn p, prod.mk (center n p.1 p.2) (radius n p.1 p.2)), let c : ℕ → α := λn, (F n).1, let r : ℕ → ennreal := λn, (F n).2, have rpos : ∀n, r n > 0, { assume n, induction n with n hn, exact lt_min εpos (Bpos 0), exact (H n (c n) (r n) hn).1 }, have rB : ∀n, r n ≤ B n, { assume n, induction n with n hn, exact min_le_right _ _, exact (H n (c n) (r n) (rpos n)).2.1 }, have incl : ∀n, closed_ball (c (n+1)) (r (n+1)) ⊆ (closed_ball (c n) (r n)) ∩ (f n) := λn, (H n (c n) (r n) (rpos n)).2.2, have cdist : ∀n, edist (c n) (c (n+1)) ≤ B n, { assume n, rw edist_comm, have A : c (n+1) ∈ closed_ball (c (n+1)) (r (n+1)) := mem_closed_ball_self, have I := calc closed_ball (c (n+1)) (r (n+1)) ⊆ closed_ball (c n) (r n) : subset.trans (incl n) (inter_subset_left _ _) ... ⊆ closed_ball (c n) (B n) : closed_ball_subset_closed_ball (rB n), exact I A }, have : cauchy_seq c := cauchy_seq_of_edist_le_geometric_two _ one_ne_top cdist, -- as the sequence `c n` is Cauchy in a complete space, it converges to a limit `y`. rcases cauchy_seq_tendsto_of_complete this with ⟨y, ylim⟩, -- this point `y` will be the desired point. We will check that it belongs to all -- `f n` and to `ball x ε`. use y, simp only [exists_prop, set.mem_Inter], have I : ∀n, ∀m ≥ n, closed_ball (c m) (r m) ⊆ closed_ball (c n) (r n), { assume n, refine nat.le_induction _ (λm hnm h, _), { exact subset.refl _ }, { exact subset.trans (incl m) (subset.trans (inter_subset_left _ _) h) }}, have yball : ∀n, y ∈ closed_ball (c n) (r n), { assume n, refine is_closed_ball.mem_of_tendsto ylim _, refine (filter.eventually_ge_at_top n).mono (λ m hm, _), exact I n m hm mem_closed_ball_self }, split, show ∀n, y ∈ f n, { assume n, have : closed_ball (c (n+1)) (r (n+1)) ⊆ f n := subset.trans (incl n) (inter_subset_right _ _), exact this (yball (n+1)) }, show edist y x ≤ ε, from le_trans (yball 0) (min_le_left _ _), end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_open {S : set (set α)} (ho : ∀s∈S, is_open s) (hS : countable S) (hd : ∀s∈S, closure s = univ) : closure (⋂₀S) = univ := begin cases S.eq_empty_or_nonempty with h h, { simp [h] }, { rcases hS.exists_surjective h with ⟨f, hf⟩, have F : ∀n, f n ∈ S := λn, by rw hf; exact mem_range_self _, rw [hf, sInter_range], exact dense_Inter_of_open_nat (λn, ho _ (F n)) (λn, hd _ (F n)) } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_open {S : set β} {f : β → set α} (ho : ∀s∈S, is_open (f s)) (hS : countable S) (hd : ∀s∈S, closure (f s) = univ) : closure (⋂s∈S, f s) = univ := begin rw ← sInter_image, apply dense_sInter_of_open, { rwa ball_image_iff }, { exact hS.image _ }, { rwa ball_image_iff } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_open [encodable β] {f : β → set α} (ho : ∀s, is_open (f s)) (hd : ∀s, closure (f s) = univ) : closure (⋂s, f s) = univ := begin rw ← sInter_range, apply dense_sInter_of_open, { rwa forall_range_iff }, { exact countable_range _ }, { rwa forall_range_iff } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_Gδ {S : set (set α)} (ho : ∀s∈S, is_Gδ s) (hS : countable S) (hd : ∀s∈S, closure s = univ) : closure (⋂₀S) = univ := begin -- the result follows from the result for a countable intersection of dense open sets, -- by rewriting each set as a countable intersection of open sets, which are of course dense. choose T hT using ho, have : ⋂₀ S = ⋂₀ (⋃s∈S, T s ‹_›) := (sInter_bUnion (λs hs, (hT s hs).2.2)).symm, rw this, refine dense_sInter_of_open _ (hS.bUnion (λs hs, (hT s hs).2.1)) _; simp only [set.mem_Union, exists_prop]; rintro t ⟨s, hs, tTs⟩, show is_open t, { exact (hT s hs).1 t tTs }, show closure t = univ, { apply eq_univ_of_univ_subset, rw [← hd s hs, (hT s hs).2.2], exact closure_mono (sInter_subset_of_mem tTs) } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_Gδ [encodable β] {f : β → set α} (ho : ∀s, is_Gδ (f s)) (hd : ∀s, closure (f s) = univ) : closure (⋂s, f s) = univ := begin rw ← sInter_range, exact dense_sInter_of_Gδ (forall_range_iff.2 ‹_›) (countable_range _) (forall_range_iff.2 ‹_›) end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_Gδ {S : set β} {f : Π x ∈ S, set α} (ho : ∀s∈S, is_Gδ (f s ‹_›)) (hS : countable S) (hd : ∀s∈S, closure (f s ‹_›) = univ) : closure (⋂s∈S, f s ‹_›) = univ := begin rw bInter_eq_Inter, haveI := hS.to_encodable, exact dense_Inter_of_Gδ (λ s, ho s s.2) (λ s, hd s s.2) end /-- Baire theorem: the intersection of two dense Gδ sets is dense. -/ theorem dense_inter_of_Gδ {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) (hsc : closure s = univ) (htc : closure t = univ) : closure (s ∩ t) = univ := begin rw [inter_eq_Inter], apply dense_Inter_of_Gδ; simp [bool.forall_bool, *] end /-- A property holds on a residual (comeagre) set if and only if it holds on some dense `Gδ` set. -/ lemma eventually_residual {p : α → Prop} : (∀ᶠ x in residual α, p x) ↔ ∃ (t : set α), is_Gδ t ∧ closure t = univ ∧ ∀ x ∈ t, p x := calc (∀ᶠ x in residual α, p x) ↔ ∀ᶠ x in ⨅ (t : set α) (ht : is_Gδ t ∧ closure t = univ), 𝓟 t, p x : by simp only [residual, infi_and] ... ↔ ∃ (t : set α) (ht : is_Gδ t ∧ closure t = univ), ∀ᶠ x in 𝓟 t, p x : mem_binfi (λ t₁ h₁ t₂ h₂, ⟨t₁ ∩ t₂, ⟨h₁.1.inter h₂.1, dense_inter_of_Gδ h₁.1 h₂.1 h₁.2 h₂.2⟩, by simp⟩) ⟨univ, is_Gδ_univ, closure_univ⟩ ... ↔ _ : by simp [and_assoc] /-- A set is residual (comeagre) if and only if it includes a dense `Gδ` set. -/ lemma mem_residual {s : set α} : s ∈ residual α ↔ ∃ t ⊆ s, is_Gδ t ∧ closure t = univ := (@eventually_residual α _ _ (λ x, x ∈ s)).trans $ exists_congr $ λ t, by rw [exists_prop, and_comm (t ⊆ s), subset_def, and_assoc] instance : countable_Inter_filter (residual α) := ⟨begin intros S hSc hS, simp only [mem_residual] at *, choose T hTs hT using hS, refine ⟨⋂ s ∈ S, T s ‹_›, _, _, _⟩, { rw [sInter_eq_bInter], exact Inter_subset_Inter (λ s, Inter_subset_Inter $ hTs s) }, { exact is_Gδ_bInter hSc (λ s hs, (hT s hs).1) }, { exact dense_bInter_of_Gδ (λ s hs, (hT s hs).1) hSc (λ s hs, (hT s hs).2) } end⟩ /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bUnion_interior_of_closed {S : set β} {f : β → set α} (hc : ∀s∈S, is_closed (f s)) (hS : countable S) (hU : (⋃s∈S, f s) = univ) : closure (⋃s∈S, interior (f s)) = univ := begin let g := λs, (frontier (f s))ᶜ, have clos_g : closure (⋂s∈S, g s) = univ, { refine dense_bInter_of_open (λs hs, _) hS (λs hs, _), show is_open (g s), from is_open_compl_iff.2 is_closed_frontier, show closure (g s) = univ, { apply subset.antisymm (subset_univ _), simp [interior_frontier (hc s hs)] }}, have : (⋂s∈S, g s) ⊆ (⋃s∈S, interior (f s)), { assume x hx, have : x ∈ ⋃s∈S, f s, { have := mem_univ x, rwa ← hU at this }, rcases mem_bUnion_iff.1 this with ⟨s, hs, xs⟩, have : x ∈ g s := mem_bInter_iff.1 hx s hs, have : x ∈ interior (f s), { have : x ∈ f s \ (frontier (f s)) := mem_inter xs this, simpa [frontier, xs, (hc s hs).closure_eq] using this }, exact mem_bUnion_iff.2 ⟨s, ⟨hs, this⟩⟩ }, have := closure_mono this, rw clos_g at this, exact subset.antisymm (subset_univ _) this end /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with `⋃₀`. -/ theorem dense_sUnion_interior_of_closed {S : set (set α)} (hc : ∀s∈S, is_closed s) (hS : countable S) (hU : (⋃₀ S) = univ) : closure (⋃s∈S, interior s) = univ := by rw sUnion_eq_bUnion at hU; exact dense_bUnion_interior_of_closed hc hS hU /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Union_interior_of_closed [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : closure (⋃s, interior (f s)) = univ := begin rw ← bUnion_univ, apply dense_bUnion_interior_of_closed, { simp [hc] }, { apply countable_encodable }, { rwa ← bUnion_univ at hU } end /-- One of the most useful consequences of Baire theorem: if a countable union of closed sets covers the space, then one of the sets has nonempty interior. -/ theorem nonempty_interior_of_Union_of_closed [nonempty α] [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : ∃s, (interior $ f s).nonempty := begin by_contradiction h, simp only [not_exists, not_nonempty_iff_eq_empty] at h, have := calc ∅ = closure (⋃s, interior (f s)) : by simp [h] ... = univ : dense_Union_interior_of_closed hc hU, exact univ_nonempty.ne_empty this.symm end end Baire_theorem
3092e2e706f1cb5f379d0580521bcdb7e564f667
3f1a1d97c03bb24b55a1b9969bb4b3c619491d5a
/library/init/meta/tactic.lean
65d2e286cd7d3514f762edeca83b15638cd0f944
[ "Apache-2.0" ]
permissive
praveenmunagapati/lean
00c3b4496cef8e758396005013b9776bb82c4f56
fc760f57d20e0a486d14bc8a08d89147b60f530c
refs/heads/master
1,630,692,342,183
1,515,626,222,000
1,515,626,222,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,259
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state /-- Create a tactic state with an empty local context and a dummy goal. -/ meta constant mk_empty : environment → options → tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, iterate_at_most n t) <|> skip /-- (iterate_exactly n t) : execute t n times -/ meta def iterate_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, iterate_exactly n t meta def iterate : tactic unit → tactic unit := iterate_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨has_map.map to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /-- zeta reduction -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name (n : name) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : 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 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
e90ea77722c1da55df7d6ab3e25c99659edccb1f
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/for_mathlib/stuff.lean
25a83789e92e7c1b7b968bd8396073f2a596709d
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
614
lean
--import algebra.pointwise tactic /- The below is not actually needed for this project /-- Makes an add_comm_monoid in Lean's sense from a more minimal set of axioms, deducing zero_add from add_comm and add_zero -/ def add_comm_monoid.mk' {M : Type*} [has_add M] [has_zero M] (add_assoc : ∀ a b c : M, a + b + c = a + (b + c)) (add_zero : ∀ a : M, a + 0 = a) (add_comm : ∀ a b : M, a + b = b + a) : add_comm_monoid M := { add := (+), add_assoc := add_assoc, zero := (0), add_zero := add_zero, add_comm := add_comm, zero_add := λ a, add_comm a 0 ▸ add_zero a, } -- #check add_comm_monoid.mk -/
ca75f32961f23a309e64f0c7994ff86a0fb35bef
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/ring_theory/algebra_tower.lean
d99f7239f42216063ad803646f9188cc4a10ee77
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,684
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.restrict_scalars import algebra.algebra.tower import algebra.invertible import linear_algebra.basis import ring_theory.adjoin.basic import ring_theory.polynomial.tower /-! # Towers of algebras We set up the basic theory of algebra towers. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. In `field_theory/tower.lean` we use this to prove the tower law for finite extensions, that if `R` and `S` are both fields, then `[A:R] = [A:S] [S:A]`. In this file we prepare the main lemma: if `{bi | i ∈ I}` is an `R`-basis of `S` and `{cj | j ∈ J}` is a `S`-basis of `A`, then `{bi cj | i ∈ I, j ∈ J}` is an `R`-basis of `A`. This statement does not require the base rings to be a field, so we also generalize the lemma to rings in this file. -/ open_locale pointwise universes u v w u₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) namespace is_scalar_tower section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R S A B) /-- Suppose that `R -> S -> A` is a tower of algebras. If an element `r : R` is invertible in `S`, then it is invertible in `A`. -/ def invertible.algebra_tower (r : R) [invertible (algebra_map R S r)] : invertible (algebra_map R A r) := invertible.copy (invertible.map (algebra_map S A : S →* A) (algebra_map R S r)) (algebra_map R A r) (by rw [ring_hom.coe_monoid_hom, is_scalar_tower.algebra_map_apply R S A]) /-- A natural number that is invertible when coerced to `R` is also invertible when coerced to any `R`-algebra. -/ def invertible_algebra_coe_nat (n : ℕ) [inv : invertible (n : R)] : invertible (n : A) := by { haveI : invertible (algebra_map ℕ R n) := inv, exact invertible.algebra_tower ℕ R A n } end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] end comm_semiring end is_scalar_tower namespace algebra theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] (s : set S) : adjoin R (algebra_map S (restrict_scalars R S A) '' s) = (adjoin R s).map ((algebra.of_id S (restrict_scalars R S A)).restrict_scalars R) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w) [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (s : set S) : adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_scalar_tower.to_alg_hom R S A) := le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩) (subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩) lemma adjoin_res (C D E : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [algebra C D] [algebra C E] [algebra D E] [is_scalar_tower C D E] (S : set E) : (algebra.adjoin D S).res C = ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)).under (algebra.adjoin ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) S) := begin suffices : set.range (algebra_map D E) = set.range (algebra_map ((⊤ : subalgebra C D).map (is_scalar_tower.to_alg_hom C D E)) E), { ext x, change x ∈ subsemiring.closure (_ ∪ S) ↔ x ∈ subsemiring.closure (_ ∪ S), rw this }, ext x, split, { rintros ⟨y, hy⟩, exact ⟨⟨algebra_map D E y, ⟨y, ⟨algebra.mem_top, rfl⟩⟩⟩, hy⟩ }, { rintros ⟨⟨y, ⟨z, ⟨h0, h1⟩⟩⟩, h2⟩, exact ⟨z, eq.trans h1 h2⟩ }, end lemma adjoin_res_eq_adjoin_res (C D E F : Type*) [comm_semiring C] [comm_semiring D] [comm_semiring E] [comm_semiring F] [algebra C D] [algebra C E] [algebra C F] [algebra D F] [algebra E F] [is_scalar_tower C D F] [is_scalar_tower C E F] {S : set D} {T : set E} (hS : algebra.adjoin C S = ⊤) (hT : algebra.adjoin C T = ⊤) : (algebra.adjoin E (algebra_map D F '' S)).res C = (algebra.adjoin D (algebra_map E F '' T)).res C := by { rw [adjoin_res, adjoin_res, ←hS, ←hT, ←algebra.adjoin_image, ←algebra.adjoin_image, ←alg_hom.coe_to_ring_hom, ←alg_hom.coe_to_ring_hom, is_scalar_tower.coe_to_alg_hom, is_scalar_tower.coe_to_alg_hom, ←adjoin_union_eq_under, ←adjoin_union_eq_under, set.union_comm] } end algebra section open_locale classical lemma algebra.fg_trans' {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] (hRS : (⊤ : subalgebra R S).fg) (hSA : (⊤ : subalgebra S A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := hRS, ⟨t, ht⟩ := hSA in ⟨s.image (algebra_map S A) ∪ t, by rw [finset.coe_union, finset.coe_image, algebra.adjoin_union_eq_under, algebra.adjoin_algebra_map, hs, algebra.map_top, is_scalar_tower.range_under_adjoin, ht, subalgebra.res_top]⟩ end section ring open finsupp open_locale big_operators classical universes v₁ w₁ variables {R S A} variables [comm_ring R] [ring S] [add_comm_group A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] theorem linear_independent_smul {ι : Type v₁} {b : ι → S} {ι' : Type w₁} {c : ι' → A} (hb : linear_independent R b) (hc : linear_independent S c) : linear_independent R (λ p : ι × ι', b p.1 • c p.2) := begin rw linear_independent_iff' at hb hc, rw linear_independent_iff'', rintros s g hg hsg ⟨i, k⟩, by_cases hik : (i, k) ∈ s, { have h1 : ∑ i in (s.image prod.fst).product (s.image prod.snd), g i • b i.1 • c i.2 = 0, { rw ← hsg, exact (finset.sum_subset finset.subset_product $ λ p _ hp, show g p • b p.1 • c p.2 = 0, by rw [hg p hp, zero_smul]).symm }, rw [finset.sum_product, finset.sum_comm] at h1, simp_rw [← smul_assoc, ← finset.sum_smul] at h1, exact hb _ _ (hc _ _ h1 k (finset.mem_image_of_mem _ hik)) i (finset.mem_image_of_mem _ hik) }, exact hg _ hik end /-- `basis.smul (b : basis ι R S) (c : basis ι S A)` is the `R`-basis on `A` where the `(i, j)`th basis vector is `b i • c j`. -/ noncomputable def basis.smul {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) : basis (ι × ι') R A := basis.of_repr ((c.repr.restrict_scalars R).trans $ (finsupp.lcongr (equiv.refl _) b.repr).trans $ (finsupp_prod_lequiv R).symm.trans $ (finsupp.lcongr (equiv.prod_comm ι' ι) (linear_equiv.refl _ _))) @[simp] theorem basis.smul_repr {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (x ij): (b.smul c).repr x ij = b.repr (c.repr x ij.2) ij.1 := by simp [basis.smul] theorem basis.smul_repr_mk {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (x i j): (b.smul c).repr x (i, j) = b.repr (c.repr x j) i := b.smul_repr c x (i, j) @[simp] theorem basis.smul_apply {ι : Type v₁} {ι' : Type w₁} (b : basis ι R S) (c : basis ι' S A) (ij) : (b.smul c) ij = b ij.1 • c ij.2 := begin obtain ⟨i, j⟩ := ij, rw basis.apply_eq_iff, ext ⟨i', j'⟩, rw [basis.smul_repr, linear_equiv.map_smul, basis.repr_self, finsupp.smul_apply, finsupp.single_apply], dsimp only, split_ifs with hi, { simp [hi, finsupp.single_apply] }, { simp [hi] }, end end ring section artin_tate variables (C : Type*) variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra A B] [algebra B C] [algebra A C] [is_scalar_tower A B C] open finset submodule open_locale classical lemma exists_subalgebra_of_fg (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) : ∃ B₀ : subalgebra A B, B₀.fg ∧ (⊤ : submodule B₀ C).fg := begin cases hAC with x hx, cases hBC with y hy, have := hy, simp_rw [eq_top_iff', mem_span_finset] at this, choose f hf, let s : finset B := (finset.product (x ∪ (y * y)) y).image (function.uncurry f), have hsx : ∀ (xi ∈ x) (yj ∈ y), f xi yj ∈ s := λ xi hxi yj hyj, show function.uncurry f (xi, yj) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_left _ hxi, hyj⟩, have hsy : ∀ (yi yj yk ∈ y), f (yi * yj) yk ∈ s := λ yi yj yk hyi hyj hyk, show function.uncurry f (yi * yj, yk) ∈ s, from mem_image_of_mem _ $ mem_product.2 ⟨mem_union_right _ $ finset.mul_mem_mul hyi hyj, hyk⟩, have hxy : ∀ xi ∈ x, xi ∈ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) := λ xi hxi, hf xi ▸ sum_mem _ (λ yj hyj, smul_mem (span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C)) ⟨f xi yj, algebra.subset_adjoin $ hsx xi hxi yj hyj⟩ (subset_span $ mem_insert_of_mem hyj)), have hyy : span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) * span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C) ≤ span (algebra.adjoin A (↑s : set B)) (↑(insert 1 y : finset C) : set C), { rw [span_mul_span, span_le, coe_insert], rintros _ ⟨yi, yj, rfl | hyi, rfl | hyj, rfl⟩, { rw mul_one, exact subset_span (set.mem_insert _ _) }, { rw one_mul, exact subset_span (set.mem_insert_of_mem _ hyj) }, { rw mul_one, exact subset_span (set.mem_insert_of_mem _ hyi) }, { rw ← hf (yi * yj), exact set_like.mem_coe.2 (sum_mem _ $ λ yk hyk, smul_mem (span (algebra.adjoin A (↑s : set B)) (insert 1 ↑y : set C)) ⟨f (yi * yj) yk, algebra.subset_adjoin $ hsy yi yj yk hyi hyj hyk⟩ (subset_span $ set.mem_insert_of_mem _ hyk : yk ∈ _)) } }, refine ⟨algebra.adjoin A (↑s : set B), subalgebra.fg_adjoin_finset _, insert 1 y, _⟩, refine restrict_scalars_injective A _ _ _, rw [restrict_scalars_top, eq_top_iff, ← algebra.top_to_submodule, ← hx, algebra.adjoin_eq_span, span_le], refine λ r hr, submonoid.closure_induction hr (λ c hc, hxy c hc) (subset_span $ mem_insert_self _ _) (λ p q hp hq, hyy $ submodule.mul_mem_mul hp hq) end /-- Artin--Tate lemma: if A ⊆ B ⊆ C is a chain of subrings of commutative rings, and A is noetherian, and C is algebra-finite over A, and C is module-finite over B, then B is algebra-finite over A. References: Atiyah--Macdonald Proposition 7.8; Stacks 00IS; Altman--Kleiman 16.17. -/ theorem fg_of_fg_of_fg [is_noetherian_ring A] (hAC : (⊤ : subalgebra A C).fg) (hBC : (⊤ : submodule B C).fg) (hBCi : function.injective (algebra_map B C)) : (⊤ : subalgebra A B).fg := let ⟨B₀, hAB₀, hB₀C⟩ := exists_subalgebra_of_fg A B C hAC hBC in algebra.fg_trans' (B₀.fg_top.2 hAB₀) $ subalgebra.fg_of_submodule_fg $ have is_noetherian_ring B₀, from is_noetherian_ring_of_fg hAB₀, have is_noetherian B₀ C, by exactI is_noetherian_of_fg_of_noetherian' hB₀C, by exactI fg_of_injective (is_scalar_tower.to_alg_hom B₀ B C).to_linear_map (linear_map.ker_eq_bot.2 hBCi) end artin_tate section alg_hom_tower variables {A} {C D : Type*} [comm_semiring A] [comm_semiring C] [comm_semiring D] [algebra A C] [algebra A D] variables (f : C →ₐ[A] D) (B) [comm_semiring B] [algebra A B] [algebra B C] [is_scalar_tower A B C] /-- Restrict the domain of an `alg_hom`. -/ def alg_hom.restrict_domain : B →ₐ[A] D := f.comp (is_scalar_tower.to_alg_hom A B C) /-- Extend the scalars of an `alg_hom`. -/ def alg_hom.extend_scalars : @alg_hom B C D _ _ _ _ (f.restrict_domain B).to_ring_hom.to_algebra := { commutes' := λ _, rfl .. f } variables {B} /-- `alg_hom`s from the top of a tower are equivalent to a pair of `alg_hom`s. -/ def alg_hom_equiv_sigma : (C →ₐ[A] D) ≃ Σ (f : B →ₐ[A] D), @alg_hom B C D _ _ _ _ f.to_ring_hom.to_algebra := { to_fun := λ f, ⟨f.restrict_domain B, f.extend_scalars B⟩, inv_fun := λ fg, let alg := fg.1.to_ring_hom.to_algebra in by exactI fg.2.restrict_scalars A, left_inv := λ f, by { dsimp only, ext, refl }, right_inv := begin rintros ⟨⟨f, _, _, _, _, _⟩, g, _, _, _, _, hg⟩, have : f = λ x, g (algebra_map B C x) := by { ext, exact (hg x).symm }, subst this, refl, end } end alg_hom_tower
aa2598d2d900051a28358720091fb0745d744cd0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/elab7.lean
1f537ada875f700ce23afd3f41d7b0214f152774
[ "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
167
lean
set_option pp.all true set_option pp.purify_metavars false #check λ x : nat, x + 1 #check λ x y : nat, x + y #check λ x y, x + y + 1 #check λ x, (x + 1) :: []
3cee82e827b1ec43c6a68cf8a15d62a42266de90
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/MutualDef.lean
d11e06cbc245bd642d26a167433de83f2bf56af5
[ "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
26,500
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.Closure import Lean.Meta.Check import Lean.Elab.Command import Lean.Elab.DefView import Lean.Elab.PreDefinition namespace Lean namespace Elab /- DefView after elaborating the header. -/ structure DefViewElabHeader := (ref : Syntax) (modifiers : Modifiers) (kind : DefKind) (shortDeclName : Name) (declName : Name) (levelNames : List Name) (numParams : Nat) (type : Expr) -- including the parameters (valueStx : Syntax) instance DefViewElabHeader.inhabited : Inhabited DefViewElabHeader := ⟨⟨arbitrary _, {}, DefKind.«def», arbitrary _, arbitrary _, [], 0, arbitrary _, arbitrary _⟩⟩ namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless (m₁.isUnsafe == m₂.isUnsafe) $ throwError "cannot mix unsafe and safe definitions"; unless (m₁.isNoncomputable == m₂.isNoncomputable) $ throwError "cannot mix computable and non-computable definitions"; unless (m₁.isPartial == m₂.isPartial) $ throwError "cannot mix partial and non-partial definitions"; pure () private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless (k₁.isExample == k₂.isExample) $ throwError "cannot mix examples and definitions"; -- Reason: we should discard examples unless (k₁.isTheorem == k₂.isTheorem) $ throwError "cannot mix theorems and definitions"; -- Reason: we will eventually elaborate theorems in `Task`s. pure () private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do when (newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe) $ throwError "'unsafe' theorems are not allowed"; when (newHeader.kind.isTheorem && newHeader.modifiers.isPartial) $ throwError "'partial' theorems are not allowed, 'partial' is a code generation directive"; when (newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable) $ throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems"; when (newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe) $ throwError "'noncomputable unsafe' is not allowed"; when (newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial) $ throwError "'noncomputable partial' is not allowed"; when (newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe) $ throwError "'unsafe' subsumes 'partial'"; if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩; catch (do unless (newHeader.levelNames == firstHeader.levelNames) $ throwError "universe parameters mismatch"; checkModifiers newHeader.modifiers firstHeader.modifiers; checkKinds newHeader.kind firstHeader.kind) (fun ex => match ex with | Exception.error ref msg => throw (Exception.error ref ("invalid mutually recursive definitions, " ++ msg)) | _ => throw ex) else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" private def elabFunType (ref : Syntax) (xs : Array Expr) (view : DefView) : TermElabM Expr := do match view.type? with | some typeStx => do type ← elabType typeStx; synthesizeSyntheticMVarsNoPostponing; type ← instantiateMVars type; registerFailedToInferDefTypeInfo type typeStx; mkForallFVars xs type | none => do let hole := mkHole ref; type ← elabType hole; registerFailedToInferDefTypeInfo type ref; mkForallFVars xs type private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := views.foldlM (fun (headers : Array DefViewElabHeader) (view : DefView) => withRef view.ref do currNamespace ← getCurrNamespace; currLevelNames ← getLevelNames; ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId currNamespace currLevelNames view.declId view.modifiers; applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration; withLevelNames levelNames $ elabBinders view.binders.getArgs fun xs => do let refForElabFunType := view.value; type ← elabFunType refForElabFunType xs view; let newHeader : DefViewElabHeader := { ref := view.ref, modifiers := view.modifiers, kind := view.kind, shortDeclName := shortDeclName, declName := declName, levelNames := levelNames, numParams := xs.size, type := type, valueStx := view.value }; check headers newHeader; pure $ headers.push newHeader) #[] private partial def withFunLocalDeclsAux {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : Nat → Array Expr → TermElabM α | i, fvars => if h : i < headers.size then do let header := headers.get ⟨i, h⟩; withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => withFunLocalDeclsAux (i+1) (fvars.push fvar) else k fvars private def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := withFunLocalDeclsAux headers k 0 #[] /- Recall that ``` def matchAlts (optionalFirstBar := true) : Parser := withPosition $ fun pos => (if optionalFirstBar then optional "| " else "| ") >> sepBy1 matchAlt (checkColGe pos.column "alternatives must be indented" >> "|") def declValSimple := parser! " := " >> termParser def declValEqns := parser! Term.matchAlts false def declVal := declValSimple <|> declValEqns ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := if declVal.isOfKind `Lean.Parser.Command.declValSimple then pure $ declVal.getArg 1 else if declVal.isOfKind `Lean.Parser.Command.declValEqns then expandMatchAltsIntoMatch declVal (declVal.getArg 0) else Macro.throwError declVal "unexpected definition value" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do valStx ← liftMacroM $ declValToTerm header.valueStx; forallBoundedTelescope header.type header.numParams fun xs type => do val ← elabTermEnsuringType valStx type; mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State TermElabM Unit := do headers.forM fun header => collectUsedFVars header.type; values.forM collectUsedFVars; toLift.forM fun letRecToLift => do { collectUsedFVars letRecToLift.type; collectUsedFVars letRecToLift.val } private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do (_, used) ← (collectUsed headers values toLift).run {}; removeUnused vars used private def withUsedWhen {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (cond : Bool) (k : Array Expr → TermElabM α) : TermElabM α := if cond then do (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift; withLCtx lctx localInsts $ k vars else k vars private def isExample (views : Array DefView) : Bool := views.any fun view => view.kind.isExample private def isTheorem (views : Array DefView) : Bool := views.any fun view => view.kind.isTheorem private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do type ← instantiateMVars header.type; pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do type ← instantiateMVars toLift.type; val ← instantiateMVars toLift.val; pure { toLift with type := type, val := val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false; match occ? with | some (Expr.fvar fvarId _) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do decl? ← findLocalDecl? fvarId; match decl? with | some decl => pure decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => pure n /- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => do match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do fnName ← getFunName fvarId letRecsToLift; throwErrorAt toLift.ref ("invalid type in 'let rec', it uses '" ++ fnName ++ "' which is being defined simultaneously") namespace MutualClosure /- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := NameMap NameSet /- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : UsedFVarsMap := let sectionVarSet := sectionVars.foldl (fun (s : NameSet) (var : Expr) => s.insert var.fvarId!) {}; let usedFVarMap := mainFVarIds.foldl (fun (usedFVarMap : UsedFVarsMap) mainFVarId => usedFVarMap.insert mainFVarId sectionVarSet) {}; letRecsToLift.foldl (fun (usedFVarMap : UsedFVarsMap) toLift => let state := Lean.collectFVars {} toLift.val; let state := Lean.collectFVars state toLift.type; let set := state.fvarSet; /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result; let set := mvarIds.foldl (fun (set : NameSet) (mvarId : MVarId) => match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with | some fvarId => set.insert fvarId | none => set) set; usedFVarMap.insert toLift.fvarId set) usedFVarMap /- The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State := (usedFVarsMap : UsedFVarsMap := {}) (modified : Bool := false) abbrev M := ReaderT (List FVarId) $ StateM State private def isModified : M Bool := do s ← get; pure s.modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do s ← get; pure s.usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : NameSet) : M NameSet := s₂.foldM (fun (s₁ : NameSet) k => if s₁.contains k then pure s₁ else do markModified; pure $ s₁.insert k) s₁ private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do usedFVarsMap ← getUsedFVarsMap; match usedFVarsMap.find? fvarId with | none => pure () | some fvarIds => do fvarIdsNew ← fvarIds.foldM (fun (fvarIdsNew : NameSet) (fvarId' : FVarId) => if fvarId == fvarId' then pure fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => pure fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds) fvarIds; modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified; letRecFVarIds ← read; letRecFVarIds.forM updateUsedVarsOf; whenM isModified $ fixpoint () def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap }; s.usedFVarsMap end FixPoint abbrev FreeVarMap := NameMap (Array FVarId) private def mkFreeVarMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift; let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId; let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap; letRecsToLift.foldl (fun (freeVarMap : FreeVarMap) toLift => let lctx := toLift.lctx; let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get!; let fvarIds := fvarIdsSet.fold (fun (fvarIds : Array FVarId) (fvarId : FVarId) => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds) #[]; freeVarMap.insert toLift.fvarId fvarIds) {} structure ClosureState := (newLocalDecls : Array LocalDecl := #[]) (localDecls : Array LocalDecl := #[]) (newLetDecls : Array LocalDecl := #[]) (exprArgs : Array Expr := #[]) private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do e ← instantiateMVars e; -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. liftM $ check e; pure e /- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (fun (toProcess : Array FVarId) fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId) toProcess private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : StateRefT ClosureState TermElabM (Array FVarId) := do type ← liftM $ preprocess type; modify fun s => { s with newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl (arbitrary _) fvarId userName type bi, exprArgs := s.exprArgs.push (mkFVar fvarId) }; pure $ pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux : Array FVarId → StateRefT ClosureState TermElabM Unit | toProcess => do lctx ← getLCtx; match pickMaxFVar? lctx toProcess with | none => pure () | some fvarId => do trace `Elab.definition.mkClosure fun _ => "toProcess: " ++ (toProcess.map mkFVar) ++ ", maxVar: " ++ mkFVar fvarId; let toProcess := toProcess.erase fvarId; localDecl ← getLocalDecl fvarId; match localDecl with | LocalDecl.cdecl _ _ userName type bi => do toProcess ← pushLocalDecl toProcess fvarId userName type bi; mkClosureForAux toProcess | LocalDecl.ldecl _ _ userName type val _ => do zetaFVarIds ← getZetaFVarIds; if !zetaFVarIds.contains fvarId then do /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ toProcess ← pushLocalDecl toProcess fvarId userName type; mkClosureForAux toProcess else do /- Dependent let-decl. -/ type ← liftM $ preprocess type; val ← liftM $ preprocess val; modify fun s => { s with newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl (arbitrary _) fvarId userName type val false, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val), localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val) }; mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls }; pure { s with newLocalDecls := s.newLocalDecls.reverse, newLetDecls := s.newLetDecls.reverse, exprArgs := s.exprArgs.reverse } structure LetRecClosure := (localDecls : Array LocalDecl) (closed : Expr) -- expression used to replace occurrences of the let-rec FVarId (toLift : LetRecToLift) private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx; withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do type ← instantiateForall toLift.type xs; lctx ← getLCtx; s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId!; let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type; let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val; let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs; assignExprMVar toLift.mvarId c; pure ⟨s.newLocalDecls, c, { toLift with val := val, type := type }⟩ private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) := letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get! /- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := NameMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (fun i (r : Replacement) => r.insert (mainFVars.get! i).fvarId! (mkAppN (Lean.mkConst (mainHeaders.get! i).declName) sectionVars)) r def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (fun (r : Replacement) c => r.insert c.toLift.fvarId c.closed) r def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | Expr.fvar fvarId _ => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (fun i (preDefs : Array PreDefinition) => do let header := mainHeaders.get! i; val ← mkLambdaFVars sectionVars (mainVals.get! i); type ← mkForallFVars sectionVars header.type; pure $ preDefs.push { kind := header.kind, declName := header.declName, lparams := [], -- we set it later modifiers := header.modifiers, type := type, value := val }) preDefs def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition := letRecClosures.foldl (fun (preDefs : Array PreDefinition) (c : LetRecClosure) => let type := Closure.mkForall c.localDecls c.toLift.type; let val := Closure.mkLambda c.localDecls c.toLift.val; preDefs.push { kind := kind, declName := c.toLift.declName, lparams := [], -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs }, type := type, value := val }) preDefs def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable, isPartial := mainHeaders.any fun h => h.modifiers.isPartial, isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let mainFVarIds := mainFVars.map Expr.fvarId!; let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds; -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. mctx ← getMCtx; let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift; resetZetaFVarIds; withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do { liftM $ check toLift.type; liftM $ check toLift.val }; letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap; -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. mainVals ← mainVals.mapM instantiateMVars; mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader; letRecClosures ← letRecClosures.mapM fun closure => do { toLift ← instantiateMVarsAtLetRecToLift closure.toLift; pure { closure with toLift := toLift } }; -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars; let r := insertReplacementForLetRecs r letRecClosures; let mainVals := mainVals.map r.apply; let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type }; let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } }; let letRecKind := getKindForLetRecs mainHeaders; let letRecMods := getModifiersForLetRecs mainHeaders; pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] def elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit := do scopeLevelNames ← getLevelNames; headers ← elabHeaders views; let allUserLevelNames := getAllUserLevelNames headers; withFunLocalDecls headers fun funFVars => do values ← elabFunValues headers; Term.synthesizeSyntheticMVarsNoPostponing; if isExample views then pure () else do values ← values.mapM instantiateMVars; headers ← headers.mapM instantiateMVarsAtHeader; letRecsToLift ← getLetRecsToLift; letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift; checkLetRecsToLiftTypes funFVars letRecsToLift; withUsedWhen vars headers values letRecsToLift (not $ isTheorem views) fun vars => do preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift; preDefs ← levelMVarToParamPreDecls preDefs; preDefs ← instantiateMVarsAtPreDecls preDefs; preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames; addPreDefinitions preDefs end Term namespace Command def elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do views ← ds.mapM fun d => do { modifiers ← elabModifiers (d.getArg 0); mkDefView modifiers (d.getArg 1) }; runTermElabM none fun vars => Term.elabMutualDef vars views end Command end Elab end Lean
a4d5d5f96ab72cf21643ec0863f508771ec37569
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/fubini.lean
3dad12f3e93853108ea02a7b78aef2cf3982a276
[ "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
11,271
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.has_limits import category_theory.products.basic import category_theory.functor.currying /-! # A Fubini theorem for categorical limits We prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`, when all the appropriate limits exist. We begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated "uncurried" functor. In the first part, given a coherent family `D` of limit cones over the functors `F.obj j`, and a cone `c` over `G`, we construct a cone over the cone points of `D`. We then show that if `c` is a limit cone, the constructed cone is also a limit cone. In the second part, we state the Fubini theorem in the setting where limits are provided by suitable `has_limit` classes. We construct `limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)` and give simp lemmas characterising it. For convenience, we also provide `limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)` in terms of the uncurried functor. ## Future work The dual statement. -/ universes v u open category_theory namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables (F : J ⥤ K ⥤ C) /-- A structure carrying a diagram of cones over the functors `F.obj j`. -/ -- We could try introducing a "dependent functor type" to handle this? structure diagram_of_cones := (obj : Π j : J, cone (F.obj j)) (map : Π {j j' : J} (f : j ⟶ j'), (cones.postcompose (F.map f)).obj (obj j) ⟶ obj j') (id : ∀ j : J, (map (𝟙 j)).hom = 𝟙 _ . obviously) (comp : ∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃), (map (f ≫ g)).hom = (map f).hom ≫ (map g).hom . obviously) variables {F} /-- Extract the functor `J ⥤ C` consisting of the cone points and the maps between them, from a `diagram_of_cones`. -/ @[simps] def diagram_of_cones.cone_points (D : diagram_of_cones F) : J ⥤ C := { obj := λ j, (D.obj j).X, map := λ j j' f, (D.map f).hom, map_id' := λ j, D.id j, map_comp' := λ j₁ j₂ j₃ f g, D.comp f g, } /-- Given a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`, we can construct a cone over the diagram consisting of the cone points from `D`. -/ @[simps] def cone_of_cone_uncurry {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) (c : cone (uncurry.obj F)) : cone (D.cone_points) := { X := c.X, π := { app := λ j, (Q j).lift { X := c.X, π := { app := λ k, c.π.app (j, k), naturality' := λ k k' f, begin dsimp, simp only [category.id_comp], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j, k') (𝟙 j, f), dsimp at this, simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end } }, naturality' := λ j j' f, (Q j').hom_ext begin dsimp, intro k, simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_π, limits.is_limit.fac_assoc, limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j', k) (f, 𝟙 k), dsimp at this, simp only [category.id_comp, category.comp_id, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end, } }. /-- `cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.` -/ def cone_of_cone_uncurry_is_limit {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) {c : cone (uncurry.obj F)} (P : is_limit c) : is_limit (cone_of_cone_uncurry Q c) := { lift := λ s, P.lift { X := s.X, π := { app := λ p, s.π.app p.1 ≫ (D.obj p.1).π.app p.2, naturality' := λ p p' f, begin dsimp, simp only [category.id_comp, category.assoc], rcases p with ⟨j, k⟩, rcases p' with ⟨j', k'⟩, rcases f with ⟨fj, fk⟩, dsimp, slice_rhs 3 4 { rw ←nat_trans.naturality, }, slice_rhs 2 3 { rw ←(D.obj j).π.naturality, }, simp only [functor.const_obj_map, category.id_comp, category.assoc], have w := (D.map fj).w k', dsimp at w, rw ←w, have n := s.π.naturality fj, dsimp at n, simp only [category.id_comp] at n, rw n, simp, end, } }, fac' := λ s j, begin apply (Q j).hom_ext, intro k, simp, end, uniq' := λ s m w, begin refine P.uniq { X := s.X, π := _, } m _, rintro ⟨j, k⟩, dsimp, rw [←w j], simp, end, } section variables (F) variables [has_limits_of_shape K C] /-- Given a functor `F : J ⥤ K ⥤ C`, with all needed limits, we can construct a diagram consisting of the limit cone over each functor `F.obj j`, and the universal cone morphisms between these. -/ @[simps] noncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F := { obj := λ j, limit.cone (F.obj j), map := λ j j' f, { hom := lim.map (F.map f), }, } -- Satisfying the inhabited linter. noncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) := ⟨diagram_of_cones.mk_of_has_limits F⟩ @[simp] lemma diagram_of_cones.mk_of_has_limits_cone_points : (diagram_of_cones.mk_of_has_limits F).cone_points = (F ⋙ lim) := rfl variables [has_limit (uncurry.obj F)] variables [has_limit (F ⋙ lim)] /-- The Fubini theorem for a functor `F : J ⥤ K ⥤ C`, showing that the limit of `uncurry.obj F` can be computed as the limit of the limits of the functors `F.obj j`. -/ noncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) ≅ limit (F ⋙ lim) := begin let c := limit.cone (uncurry.obj F), let P : is_limit c := limit.is_limit _, let G := diagram_of_cones.mk_of_has_limits F, let Q : Π j, is_limit (G.obj j) := λ j, limit.is_limit _, have Q' := cone_of_cone_uncurry_is_limit Q P, have Q'' := (limit.is_limit (F ⋙ lim)), exact is_limit.cone_point_unique_up_to_iso Q' Q'', end @[simp, reassoc] lemma limit_uncurry_iso_limit_comp_lim_hom_π_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := begin dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso], simp, end @[simp, reassoc] lemma limit_uncurry_iso_limit_comp_lim_inv_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom], simp, end end section variables (F) [has_limits_of_shape J C] [has_limits_of_shape K C] -- With only moderate effort these could be derived if needed: variables [has_limits_of_shape (J × K) C] [has_limits_of_shape (K × J) C] /-- The limit of `F.flip ⋙ lim` is isomorphic to the limit of `F ⋙ lim`. -/ noncomputable def limit_flip_comp_lim_iso_limit_comp_lim : limit (F.flip ⋙ lim) ≅ limit (F ⋙ lim) := (limit_uncurry_iso_limit_comp_lim _).symm ≪≫ has_limit.iso_of_nat_iso (uncurry_obj_flip _) ≪≫ (has_limit.iso_of_equivalence (prod.braiding _ _) (nat_iso.of_components (λ _, by refl) (by tidy))) ≪≫ limit_uncurry_iso_limit_comp_lim _ @[simp, reassoc] lemma limit_flip_comp_lim_iso_limit_comp_lim_hom_π_π (j) (k) : (limit_flip_comp_lim_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ k ≫ limit.π _ j := by { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, } -- See note [dsimp, simp] @[simp, reassoc] lemma limit_flip_comp_lim_iso_limit_comp_lim_inv_π_π (k) (j) : (limit_flip_comp_lim_iso_limit_comp_lim F).inv ≫ limit.π _ k ≫ limit.π _ j = limit.π _ j ≫ limit.π _ k := by { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, dsimp, simp, } end section variables (G : J × K ⥤ C) section variables [has_limits_of_shape K C] variables [has_limit G] variables [has_limit ((curry.obj G) ⋙ lim)] /-- The Fubini theorem for a functor `G : J × K ⥤ C`, showing that the limit of `G` can be computed as the limit of the limits of the functors `G.obj (j, _)`. -/ noncomputable def limit_iso_limit_curry_comp_lim : limit G ≅ limit ((curry.obj G) ⋙ lim) := begin have i : G ≅ uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G, haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) := has_limit_of_iso i, transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)), apply has_limit.iso_of_nat_iso i, exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G), end @[simp, reassoc] lemma limit_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := by simp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso] @[simp, reassoc] lemma limit_iso_limit_curry_comp_lim_inv_π {j} {k} : (limit_iso_limit_curry_comp_lim G).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_iso_limit_curry_comp_lim G).hom], simp, end end section variables [has_limits C] -- Certainly one could weaken the hypotheses here. open category_theory.prod /-- A variant of the Fubini theorem for a functor `G : J × K ⥤ C`, showing that $\lim_k \lim_j G(j,k) ≅ \lim_j \lim_k G(j,k)$. -/ noncomputable def limit_curry_swap_comp_lim_iso_limit_curry_comp_lim : limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit ((curry.obj G) ⋙ lim) := calc limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit (swap K J ⋙ G) : (limit_iso_limit_curry_comp_lim _).symm ... ≅ limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _) ... ≅ limit ((curry.obj G) ⋙ lim) : limit_iso_limit_curry_comp_lim _ @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ k ≫ limit.π _ j := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv ≫ limit.π _ k ≫ limit.π _ j = limit.π _ j ≫ limit.π _ k := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end end end end category_theory.limits
8a1f20e42b2c6a91c066413308a3e50698621156
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/logic/basic.lean
a715ba3480bfb7037931a2f9efae18e4cb7c4a8e
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,593
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. -/ 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 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 [subsingleton α] (x y : α) : x = y ↔ true := by cc 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⟩ /-- 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] def fact (p : Prop) := p lemma fact.elim {p : Prop} (h : fact p) : p := 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` -/ 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 em (p : Prop) : p ∨ ¬ p := classical.em _ theorem or_not {p : Prop} : p ∨ ¬ p := em _ 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" -- 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) := ⟨function.swap, function.swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap /-! ### 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 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 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_rfl {α : Sort*} {a : α} : eq.mp (eq.refl α) a = a := rfl @[simp] lemma eq_mpr_rfl {α : Sort*} {a : α} : eq.mpr (eq.refl α) a = 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_eq_mp : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : (eq.mp e a) = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.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 @[simp] lemma {u} eq_mpr_heq {α β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x := by subst h; refl 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 := ⟨function.swap, function.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 @[simp] theorem forall_true_iff : (α → true) ↔ true := iff_true_intro (λ _, trivial) -- 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 @[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 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] 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₂⟩⟩ @[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 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.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) 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 @[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⟩⟩ 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⟩ 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 * /-! ### 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 : ¬ 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 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
6b125822066cfe7a685d82e77ebe88255a334b8d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/aux_decl_zeta.lean
b456cff8b5d0c68409ca81f64cbb5a2a0057da29
[ "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
450
lean
inductive vec (A : Sort*) : nat → Sort* | nil : vec 0 | cons : Π {n}, A → vec n → vec (n+1) definition f : bool → Prop | x := let m := 10, n := m in match x with | tt := true | ff := ∀ (x : vec nat 10) (w : vec nat n), x = w end set_option eqn_compiler.zeta true definition g : bool → Prop | x := let m := 10, n := m in match x with | tt := true | ff := ∀ (x : vec nat 10) (w : vec nat n), x = w end
63ab8669af8a8c36c4d62cf233b1e492ab881996
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/currying.lean
87f8f54a82b2fcb628f5d48e626eb4e39b199d9f
[ "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
3,339
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.products.bifunctor import category_theory.equivalence import category_theory.eq_to_hom namespace category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) := { obj := λ F, { obj := λ X, (F.obj X.1).obj X.2, map := λ X Y f, (F.map f.1).app X.2 ≫ (F.obj Y.1).map f.2, map_comp' := λ X Y Z f g, begin simp only [prod_comp_fst, prod_comp_snd, functor.map_comp, nat_trans.comp_app, category.assoc], slice_lhs 2 3 { rw ← nat_trans.naturality }, rw category.assoc, end }, map := λ F G T, { app := λ X, (T.app X.1).app X.2, naturality' := λ X Y f, begin simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc, functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app], slice_lhs 2 3 { rw nat_trans.naturality }, slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app], }, rw category.assoc, end } }. def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) := { obj := λ X, { obj := λ Y, F.obj (X, Y), map := λ Y Y' g, F.map (𝟙 X, g) }, map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } } def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) := { obj := λ F, curry_obj F, map := λ F G T, { app := λ X, { app := λ Y, T.app (X, Y), naturality' := λ Y Y' g, begin dsimp [curry_obj], rw nat_trans.naturality, end }, naturality' := λ X X' f, begin ext, dsimp [curry_obj], rw nat_trans.naturality, end } }. @[simp] lemma uncurry.obj_obj {F : C ⥤ (D ⥤ E)} {X : C × D} : (uncurry.obj F).obj X = (F.obj X.1).obj X.2 := rfl @[simp] lemma uncurry.obj_map {F : C ⥤ (D ⥤ E)} {X Y : C × D} {f : X ⟶ Y} : (uncurry.obj F).map f = ((F.map f.1).app X.2) ≫ ((F.obj Y.1).map f.2) := rfl @[simp] lemma uncurry.map_app {F G : C ⥤ (D ⥤ E)} {α : F ⟶ G} {X : C × D} : (uncurry.map α).app X = (α.app X.1).app X.2 := rfl @[simp] lemma curry.obj_obj_obj {F : (C × D) ⥤ E} {X : C} {Y : D} : ((curry.obj F).obj X).obj Y = F.obj (X, Y) := rfl @[simp] lemma curry.obj_obj_map {F : (C × D) ⥤ E} {X : C} {Y Y' : D} {g : Y ⟶ Y'} : ((curry.obj F).obj X).map g = F.map (𝟙 X, g) := rfl @[simp] lemma curry.obj_map_app {F : (C × D) ⥤ E} {X X' : C} {f : X ⟶ X'} {Y} : ((curry.obj F).map f).app Y = F.map (f, 𝟙 Y) := rfl @[simp] lemma curry.map_app_app {F G : (C × D) ⥤ E} {α : F ⟶ G} {X} {Y} : ((curry.map α).app X).app Y = α.app (X, Y) := rfl def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) := equivalence.mk uncurry curry (nat_iso.of_components (λ F, nat_iso.of_components (λ X, nat_iso.of_components (λ Y, as_iso (𝟙 _)) (by tidy)) (by tidy)) (by tidy)) (nat_iso.of_components (λ F, nat_iso.of_components (λ X, eq_to_iso (by {dsimp, simp})) (by tidy)) (by tidy)) end category_theory
605c2b8d7831b3a42db0c7888113e424589d5a52
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/polynomial/degree.lean
f0466dbaad590c3c1647b2f0185330f352620785
[ "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
5,486
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import tactic.interval_cases /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset namespace polynomial universes u v w variables {R : Type u} {S : Type v} { ι : Type w} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section degree lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... = _ : congr_arg degree comp_eq_sum_left ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n •ℕ (degree q) : add_le_add degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n •ℕ (nat_degree q) : add_le_add_left (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) _ ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [semiring S] (f : R →+* S) : degree (map f p) ≤ degree p := if h : map f p = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma degree_map_eq_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma nat_degree_map_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f hf) lemma leading_coeff_map_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_of_leading_coeff_ne_zero f hf], end lemma degree_pos_of_root {p : polynomial R} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end variables [semiring S] lemma nat_degree_pos_of_eval₂_root {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < nat_degree p := lt_of_not_ge $ λ hlt, begin rw [eq_C_of_nat_degree_le_zero hlt, eval₂_C] at hz, refine hp (finsupp.ext (λ n, _)), cases n, { exact inj _ hz }, { exact coeff_eq_zero_of_nat_degree_lt (lt_of_le_of_lt hlt (nat.succ_pos _)) } end lemma degree_pos_of_eval₂_root {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < degree p := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_eval₂_root hp f hz inj) section injective open function variables {f : R →+* S} (hf : injective f) include hf lemma degree_map_eq_of_injective (p : polynomial R) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma degree_map' (p : polynomial R) : degree (p.map f) = degree p := p.degree_map_eq_of_injective hf lemma nat_degree_map' (p : polynomial R) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) lemma leading_coeff_map' (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map' hf p], end end injective section variable {f : polynomial R} lemma monomial_nat_degree_leading_coeff_eq_self (h : f.support.card ≤ 1) : monomial f.nat_degree f.leading_coeff = f := begin interval_cases f.support.card with H, { have : f = 0 := finsupp.card_support_eq_zero.1 H, simp [this] }, { obtain ⟨n, x, hx, rfl : f = monomial n x⟩ := finsupp.card_support_eq_one'.1 H, simp [hx] } end lemma C_mul_X_pow_eq_self (h : f.support.card ≤ 1) : C f.leading_coeff * X^f.nat_degree = f := by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h] end end degree end semiring end polynomial
949cc28d5ccacadd0e769b273dd17f5c05ed8752
0e175f34f8dca5ea099671777e8d7446d7d74227
/tests/lean/rename.lean
909cc25318e4ba57c0ebac10db8ce497edaecc0c
[ "Apache-2.0" ]
permissive
utensil-contrib/lean
b31266738071c654d96dac8b35d9ccffc8172fda
a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8
refs/heads/master
1,670,045,564,075
1,597,397,599,000
1,597,397,599,000
287,528,503
0
0
Apache-2.0
1,597,408,338,000
1,597,408,337,000
null
UTF-8
Lean
false
false
877
lean
example {α β} (a : α) (b : β) : unit := begin rename a a', -- rename-compatible syntax guard_hyp a' := α, rename a' → a, -- more suggestive syntax guard_hyp a := α, rename [a a', b b'], -- parallel renaming guard_hyp a' := α, guard_hyp b' := β, rename [a' → a, b' → b], -- ditto with alternative syntax guard_hyp a := α, guard_hyp b := β, rename [a → b, b → a], -- renaming really is parallel guard_hyp a := β, guard_hyp b := α, rename b a, -- shadowing is allowed (but guard_hyp doesn't like it) rename d e, -- cannot rename nonexistent hypothesis exact () end example {α} [decidable α] (a : α) : unit := begin rename a a', -- renaming works after frozen local instances rename α α', -- renaming doesn't work before frozen local instances end
13b6ef33731544032c55d019f0ec2a82ce31d471
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/types/default.hlean
d4947f6d32eeb5f7c0b1771f55a607bfd220cdd5
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
277
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: types.default Authors: Floris van Doorn The core of the HoTT library -/ import .sigma .prod .pi .equiv .fiber .eq .trunc .arrow .pointed
17167fd4749c1cf86ec4c81a6702c576b78d388c
9dc8cecdf3c4634764a18254e94d43da07142918
/counterexamples/pseudoelement.lean
1f093546d6b19b56e0a2a55b83c844f0a792c89e
[ "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
5,376
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 category_theory.abelian.pseudoelements /-! # Pseudoelements and pullbacks Borceux claims in Proposition 1.9.5 that the pseudoelement constructed in `category_theory.abelian.pseudoelement.pseudo_pullback` is unique. We show here that this claim is false. This means in particular that we cannot have an extensionality principle for pullbacks in terms of pseudoelements. ## Implementation details The construction, suggested in https://mathoverflow.net/a/419951/7845, is the following. We work in the category of `Module ℤ` and we consider the special case of `ℚ ⊞ ℚ` (that is the pullback over the terminal object). We consider the pseudoelements associated to `x : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, 2 * t)` and `y : ℚ ⟶ ℚ ⊞ ℚ` given by `t ↦ (t, t)`. ## Main results * `category_theory.abelian.pseudoelement.exist_ne_and_fst_eq_fst_and_snd_eq_snd` : there are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and `biprod.snd x = biprod.snd y`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ open category_theory.abelian category_theory category_theory.limits Module linear_map noncomputable theory namespace category_theory.abelian.pseudoelement /-- `x` is given by `t ↦ (t, 2 * t)`. -/ def x : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) := begin constructor, exact biprod.lift (of_hom id) (of_hom (2 * id)), end /-- `y` is given by `t ↦ (t, t)`. -/ def y : over ((of ℤ ℚ) ⊞ (of ℤ ℚ)) := begin constructor, exact biprod.lift (of_hom id) (of_hom id), end /-- `biprod.fst ≫ x` is pseudoequal to `biprod.fst y`. -/ lemma fst_x_pseudo_eq_fst_y : pseudo_equal _ (app biprod.fst x) (app biprod.fst y) := begin refine ⟨of ℤ ℚ, (of_hom id), (of_hom id), category_struct.id.epi (of ℤ ℚ), _, _⟩, { exact (Module.epi_iff_surjective _).2 (λ a, ⟨(a : ℚ), by simp⟩) }, { dsimp [x, y], simp } end /-- `biprod.snd ≫ x` is pseudoequal to `biprod.snd y`. -/ lemma snd_x_pseudo_eq_snd_y : pseudo_equal _ (app biprod.snd x) (app biprod.snd y) := begin refine ⟨of ℤ ℚ, (of_hom id), 2 • (of_hom id), category_struct.id.epi (of ℤ ℚ), _, _⟩, { refine (Module.epi_iff_surjective _).2 (λ a, ⟨(a/2 : ℚ), _⟩), simp only [two_smul, add_apply, of_hom_apply, id_coe, id.def], exact add_halves' (show ℚ, from a) }, { dsimp [x, y], exact concrete_category.hom_ext _ _ (λ a, by simpa) } end /-- `x` is not pseudoequal to `y`. -/ lemma x_not_pseudo_eq : ¬(pseudo_equal _ x y) := begin intro h, replace h := Module.eq_range_of_pseudoequal h, dsimp [x, y] at h, let φ := (biprod.lift (of_hom (id : ℚ →ₗ[ℤ] ℚ)) (of_hom (2 * id))), have mem_range := mem_range_self φ (1 : ℚ), rw h at mem_range, obtain ⟨a, ha⟩ := mem_range, rw [← Module.id_apply (φ (1 : ℚ)), ← biprod.total, ← linear_map.comp_apply, ← comp_def, preadditive.comp_add] at ha, let π₁ := (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _), have ha₁ := congr_arg π₁ ha, simp only [← linear_map.comp_apply, ← comp_def] at ha₁, simp only [biprod.lift_fst, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc, biprod.inl_fst, category.comp_id, biprod.inr_fst, limits.comp_zero, add_zero] at ha₁, let π₂ := (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _), have ha₂ := congr_arg π₂ ha, simp only [← linear_map.comp_apply, ← comp_def] at ha₂, have : (2 : ℚ →ₗ[ℤ] ℚ) 1 = 1 + 1 := rfl, simp only [ha₁, this, biprod.lift_snd, of_hom_apply, id_coe, id.def, preadditive.add_comp, category.assoc, biprod.inl_snd, limits.comp_zero, biprod.inr_snd, category.comp_id, zero_add, mul_apply, self_eq_add_left] at ha₂, exact @one_ne_zero ℚ _ _ ha₂, end local attribute [instance] pseudoelement.setoid open_locale pseudoelement /-- `biprod.fst ⟦x⟧ = biprod.fst ⟦y⟧`. -/ lemma fst_mk_x_eq_fst_mk_y : (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ := by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using fst_x_pseudo_eq_fst_y /-- `biprod.snd ⟦x⟧ = biprod.snd ⟦y⟧`. -/ lemma snd_mk_x_eq_snd_mk_y : (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦x⟧ = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) ⟦y⟧ := by simpa only [abelian.pseudoelement.pseudo_apply_mk, quotient.eq] using snd_x_pseudo_eq_snd_y /-- `⟦x⟧ ≠ ⟦y⟧`. -/ lemma mk_x_ne_mk_y : ⟦x⟧ ≠ ⟦y⟧ := λ h, x_not_pseudo_eq $ quotient.eq.1 h /-- There are two pseudoelements `x y : ℚ ⊞ ℚ` such that `x ≠ y`, `biprod.fst x = biprod.fst y` and `biprod.snd x = biprod.snd y`. -/ lemma exist_ne_and_fst_eq_fst_and_snd_eq_snd : ∃ x y : (of ℤ ℚ) ⊞ (of ℤ ℚ), x ≠ y ∧ (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.fst : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y ∧ (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) x = (biprod.snd : (of ℤ ℚ) ⊞ (of ℤ ℚ) ⟶ _) y:= ⟨⟦x⟧, ⟦y⟧, mk_x_ne_mk_y, fst_mk_x_eq_fst_mk_y, snd_mk_x_eq_snd_mk_y⟩ end category_theory.abelian.pseudoelement
92cc0eff74680103d0aa1fb9794d1267fb714e65
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/deprecated/ring.lean
315e6ff949eaf585d2a2ac11b4109b0e621b0b90
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,110
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import deprecated.group /-! # Unbundled semiring and ring homomorphisms (deprecated) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file is deprecated, and is no longer imported by anything in mathlib other than other deprecated files, and test files. You should not need to import it. This file defines predicates for unbundled semiring and ring homomorphisms. Instead of using this file, please use `ring_hom`, defined in `algebra.hom.ring`, with notation `→+*`, for morphisms between semirings or rings. For example use `φ : A →+* B` to represent a ring homomorphism. ## Main Definitions `is_semiring_hom` (deprecated), `is_ring_hom` (deprecated) ## Tags is_semiring_hom, is_ring_hom -/ universes u v w variable {α : Type u} /-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ structure is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop := (map_zero [] : f 0 = 0) (map_one [] : f 1 = 1) (map_add [] : ∀ {x y}, f (x + y) = f x + f y) (map_mul [] : ∀ {x y}, f (x * y) = f x * f y) namespace is_semiring_hom variables {β : Type v} [semiring α] [semiring β] variables {f : α → β} (hf : is_semiring_hom f) {x y : α} /-- The identity map is a semiring homomorphism. -/ lemma id : is_semiring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two semiring homomorphisms is a semiring homomorphism. -/ lemma comp (hf : is_semiring_hom f) {γ} [semiring γ] {g : β → γ} (hg : is_semiring_hom g) : is_semiring_hom (g ∘ f) := { map_zero := by simpa [map_zero hf] using map_zero hg, map_one := by simpa [map_one hf] using map_one hg, map_add := λ x y, by simp [map_add hf, map_add hg], map_mul := λ x y, by simp [map_mul hf, map_mul hg] } /-- A semiring homomorphism is an additive monoid homomorphism. -/ lemma to_is_add_monoid_hom (hf : is_semiring_hom f) : is_add_monoid_hom f := { ..‹is_semiring_hom f› } /-- A semiring homomorphism is a monoid homomorphism. -/ lemma to_is_monoid_hom (hf : is_semiring_hom f) : is_monoid_hom f := { ..‹is_semiring_hom f› } end is_semiring_hom /-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ structure is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop := (map_one [] : f 1 = 1) (map_mul [] : ∀ {x y}, f (x * y) = f x * f y) (map_add [] : ∀ {x y}, f (x + y) = f x + f y) namespace is_ring_hom variables {β : Type v} [ring α] [ring β] /-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/ lemma of_semiring {f : α → β} (H : is_semiring_hom f) : is_ring_hom f := {..H} variables {f : α → β} (hf : is_ring_hom f) {x y : α} /-- Ring homomorphisms map zero to zero. -/ lemma map_zero (hf : is_ring_hom f) : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [hf.map_add]; simp ... = 0 : by simp /-- Ring homomorphisms preserve additive inverses. -/ lemma map_neg (hf : is_ring_hom f) : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [hf.map_add]; simp ... = -f x : by simp [hf.map_zero] /-- Ring homomorphisms preserve subtraction. -/ lemma map_sub (hf : is_ring_hom f) : f (x - y) = f x - f y := by simp [sub_eq_add_neg, hf.map_add, hf.map_neg] /-- The identity map is a ring homomorphism. -/ lemma id : is_ring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two ring homomorphisms is a ring homomorphism. -/ -- see Note [no instance on morphisms] lemma comp (hf : is_ring_hom f) {γ} [ring γ] {g : β → γ} (hg : is_ring_hom g) : is_ring_hom (g ∘ f) := { map_add := λ x y, by simp [map_add hf]; rw map_add hg; refl, map_mul := λ x y, by simp [map_mul hf]; rw map_mul hg; refl, map_one := by simp [map_one hf]; exact map_one hg } /-- A ring homomorphism is also a semiring homomorphism. -/ lemma to_is_semiring_hom (hf : is_ring_hom f) : is_semiring_hom f := { map_zero := map_zero hf, ..‹is_ring_hom f› } lemma to_is_add_group_hom (hf : is_ring_hom f) : is_add_group_hom f := { map_add := λ _ _, hf.map_add } end is_ring_hom variables {β : Type v} {γ : Type w} [rα : semiring α] [rβ : semiring β] namespace ring_hom section include rα rβ /-- Interpret `f : α → β` with `is_semiring_hom f` as a ring homomorphism. -/ def of {f : α → β} (hf : is_semiring_hom f) : α →+* β := { to_fun := f, .. monoid_hom.of hf.to_is_monoid_hom, .. add_monoid_hom.of hf.to_is_add_monoid_hom } @[simp] lemma coe_of {f : α → β} (hf : is_semiring_hom f) : ⇑(of hf) = f := rfl lemma to_is_semiring_hom (f : α →+* β) : is_semiring_hom f := { map_zero := f.map_zero, map_one := f.map_one, map_add := f.map_add, map_mul := f.map_mul } end lemma to_is_ring_hom {α γ} [ring α] [ring γ] (g : α →+* γ) : is_ring_hom g := is_ring_hom.of_semiring g.to_is_semiring_hom end ring_hom
0a6ed30e07a1bd6e0f79aa719e0f36dbfc154978
4c06d0726f5a71477566b5375c127fa204c6c583
/proofs-before.lean
902d04665b031539e2313e0c307551b327b5bed1
[]
no_license
skaslev/proofs-talk
d2e990c889ee0b3fe015fa391011078a63dba0d5
b8019ae7506def5f8d657c35c8c4ee685a015796
refs/heads/master
1,585,996,863,406
1,541,627,234,000
1,541,627,234,000
155,862,265
1
0
null
null
null
null
UTF-8
Lean
false
false
3,152
lean
attribute [simp] function.comp section intro variables {a b c d e : Type} def modus_ponens : a → (a → b) → b := sorry def modus_tollens : (b → empty) → (a → b) → (a → empty) := sorry def ex_falso_quodlibet : empty → a := sorry def eagle : (a → d → c) → a → (b → e → d) → b → e → c := sorry def batman : (((a → empty) → empty) → empty) → (a → empty) := sorry end intro -------------------------------------------------------------------------------- def wtf : (Π {α}, (α → α) → α) → empty := sorry -------------------------------------------------------------------------------- def foo : (λ x, 2 * x) = (λ x, x + x) := sorry -------------------------------------------------------------------------------- structure {u v} iso (α : Type u) (β : Type v) := (f : α → β) (g : β → α) (gf : Π x, g (f x) = x) (fg : Π x, f (g x) = x) namespace iso def inv {α β} (i : iso α β) : iso β α := sorry def comp {α β γ} (i : iso α β) (j : iso β γ) : iso α γ := sorry end iso -------------------------------------------------------------------------------- def fiber {α β} (f : α → β) (y : β) := Σ' x : α, f x = y def iscontr (α : Type) := Σ' x : α, Π y : α, x = y structure eqv (α β : Type) := (f : α → β) (h : Π y : β, iscontr (fiber f y)) -------------------------------------------------------------------------------- def ran (g h : Type → Type) (α : Type) := Π β, (α → g β) → h β def lan (g h : Type → Type) (α : Type) := Σ β, (g β → α) × h β -------------------------------------------------------------------------------- section balanced def iter {α} (g : α → α) : ℕ → α → α | 0 := id | (n + 1) := iter n ∘ g def diter {β : Type → Type 1} {γ : Type → Type} (g : Π {α}, β (γ α) → β α) : Π (n : ℕ) {α}, β (iter γ n α) → β α | 0 α := id | (n + 1) α := g ∘ diter n -- Perfectly Balanced Tree inductive F (g : Type → Type) : Type → Type 1 | F₀ : Π {α}, α → F α | F₁ : Π {α}, F (g α) → F α -- `F G` is a general balanced tree (arbitrary branching factor at each node) inductive G (α : Type) : Type | G₀ : α → G | G₁ : α → G → G -- `F G₂₃` is balanced 2-3-tree inductive G₂₃ (α : Type) : Type | G₂ : α → α → G₂₃ | G₃ : α → α → α → G₂₃ def S (g : Type → Type) (α : Type) := Σ n : ℕ, iter g n α def from_s {g α} (x : S g α) : F g α := diter (@F.F₁ g) x.1 (F.F₀ g x.2) def to_s {g α} (x : F g α) : S g α := F.rec (λ α a, ⟨0, a⟩) (λ α a ih, ⟨ih.1 + 1, ih.2⟩) x def to_s_from_s {g α} (x : S g α) : to_s (from_s x) = x := begin simp [to_s, from_s], induction x with n x, induction n with m ih generalizing α, { dsimp [diter], refl }, { dsimp [diter], rw ih } end def from_s_to_s {g α} (x : F g α) : from_s (to_s x) = x := begin simp [to_s, from_s], induction x with β x β x ih, { dsimp [diter], refl }, { dsimp [diter], rw ih } end def sf_iso {g α} : iso (S g α) (F g α) := ⟨from_s, to_s, to_s_from_s, from_s_to_s⟩ end balanced
25452eaff94f01e96bf2325719ab48ee71585b77
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/list/comb.lean
45bef1e927fc6c534ed1022be018ef5599d510de
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,247
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Haitao Zhang, Floris van Doorn List combinators. -/ import data.list.basic data.equiv open nat prod decidable function helper_tactics algebra namespace list variables {A B C : Type} section replicate -- 'replicate i n' returns the list contain i copies of n. definition replicate : ℕ → A → list A | 0 a := [] | (succ n) a := a :: replicate n a theorem length_replicate : ∀ (i : ℕ) (a : A), length (replicate i a) = i | 0 a := rfl | (succ i) a := calc length (replicate (succ i) a) = length (replicate i a) + 1 : rfl ... = i + 1 : length_replicate end replicate /- map -/ definition map (f : A → B) : list A → list B | [] := [] | (a :: l) := f a :: map l theorem map_nil (f : A → B) : map f [] = [] theorem map_cons (f : A → B) (a : A) (l : list A) : map f (a :: l) = f a :: map f l lemma map_concat (f : A → B) (a : A) : Πl, map f (concat a l) = concat (f a) (map f l) | nil := rfl | (b::l) := begin rewrite [concat_cons, +map_cons, concat_cons, map_concat] end lemma map_append (f : A → B) : ∀ l₁ l₂, map f (l₁++l₂) = (map f l₁)++(map f l₂) | nil := take l, rfl | (a::l) := take l', begin rewrite [append_cons, *map_cons, append_cons, map_append] end lemma map_reverse (f : A → B) : Πl, map f (reverse l) = reverse (map f l) | nil := rfl | (b::l) := begin rewrite [reverse_cons, +map_cons, reverse_cons, map_concat, map_reverse] end lemma map_singleton (f : A → B) (a : A) : map f [a] = [f a] := rfl theorem map_id [simp] : ∀ l : list A, map id l = l | [] := rfl | (x::xs) := begin rewrite [map_cons, map_id] end theorem map_id' {f : A → A} (H : ∀x, f x = x) : ∀ l : list A, map f l = l | [] := rfl | (x::xs) := begin rewrite [map_cons, H, map_id'] end theorem map_map [simp] (g : B → C) (f : A → B) : ∀ l, map g (map f l) = map (g ∘ f) l | [] := rfl | (a :: l) := show (g ∘ f) a :: map g (map f l) = map (g ∘ f) (a :: l), by rewrite (map_map l) theorem length_map [simp] (f : A → B) : ∀ l : list A, length (map f l) = length l | [] := by esimp | (a :: l) := show length (map f l) + 1 = length l + 1, by rewrite (length_map l) theorem mem_map {A B : Type} (f : A → B) : ∀ {a l}, a ∈ l → f a ∈ map f l | a [] i := absurd i !not_mem_nil | a (x::xs) i := or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite [this, map_cons]; apply mem_cons) (suppose a ∈ xs, or.inr (mem_map this)) theorem exists_of_mem_map {A B : Type} {f : A → B} {b : B} : ∀{l}, b ∈ map f l → ∃a, a ∈ l ∧ f a = b | [] H := false.elim H | (c::l) H := or.elim (iff.mp !mem_cons_iff H) (suppose b = f c, exists.intro c (and.intro !mem_cons (eq.symm this))) (suppose b ∈ map f l, obtain a (Hl : a ∈ l) (Hr : f a = b), from exists_of_mem_map this, exists.intro a (and.intro (mem_cons_of_mem _ Hl) Hr)) theorem eq_of_map_const {A B : Type} {b₁ b₂ : B} : ∀ {l : list A}, b₁ ∈ map (const A b₂) l → b₁ = b₂ | [] h := absurd h !not_mem_nil | (a::l) h := or.elim (eq_or_mem_of_mem_cons h) (suppose b₁ = b₂, this) (suppose b₁ ∈ map (const A b₂) l, eq_of_map_const this) definition map₂ (f : A → B → C) : list A → list B → list C | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys theorem map₂_nil1 (f : A → B → C) : ∀ (l : list B), map₂ f [] l = [] | [] := rfl | (a::y) := rfl theorem map₂_nil2 (f : A → B → C) : ∀ (l : list A), map₂ f l [] = [] | [] := rfl | (a::y) := rfl theorem length_map₂ : ∀(f : A → B → C) x y, length (map₂ f x y) = min (length x) (length y) | f [] [] := rfl | f (xh::xr) [] := rfl | f [] (yh::yr) := rfl | f (xh::xr) (yh::yr) := calc length (map₂ f (xh::xr) (yh::yr)) = length (map₂ f xr yr) + 1 : rfl ... = min (length xr) (length yr) + 1 : length_map₂ ... = min (length (xh::xr)) (length (yh::yr)) : min_succ_succ /- filter -/ definition filter (p : A → Prop) [h : decidable_pred p] : list A → list A | [] := [] | (a::l) := if p a then a :: filter l else filter l theorem filter_nil [simp] (p : A → Prop) [h : decidable_pred p] : filter p [] = [] theorem filter_cons_of_pos [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa theorem filter_cons_of_neg [simp] {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa theorem of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain !not_mem_nil | (b::l) ain := by_cases (assume pb : p b, have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by rewrite [-this at pb]; exact pb) (suppose a ∈ filter p l, of_mem_filter this)) (suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (of_mem_filter ain)) theorem mem_of_mem_filter {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ filter p l → a ∈ l | [] ain := absurd ain !not_mem_nil | (b::l) ain := by_cases (λ pb : p b, have a ∈ b :: filter p l, by rewrite [filter_cons_of_pos _ pb at ain]; exact ain, or.elim (eq_or_mem_of_mem_cons this) (suppose a = b, by rewrite this; exact !mem_cons) (suppose a ∈ filter p l, mem_cons_of_mem _ (mem_of_mem_filter this))) (suppose ¬ p b, by rewrite [filter_cons_of_neg _ this at ain]; exact (mem_cons_of_mem _ (mem_of_mem_filter ain))) theorem mem_filter_of_mem {p : A → Prop} [h : decidable_pred p] {a : A} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain !not_mem_nil | (b::l) ain pa := by_cases (λ pb : p b, or.elim (eq_or_mem_of_mem_cons ain) (λ aeqb : a = b, by rewrite [filter_cons_of_pos _ pb, aeqb]; exact !mem_cons) (λ ainl : a ∈ l, by rewrite [filter_cons_of_pos _ pb]; exact (mem_cons_of_mem _ (mem_filter_of_mem ainl pa)))) (λ npb : ¬ p b, or.elim (eq_or_mem_of_mem_cons ain) (λ aeqb : a = b, absurd (eq.rec_on aeqb pa) npb) (λ ainl : a ∈ l, by rewrite [filter_cons_of_neg _ npb]; exact (mem_filter_of_mem ainl pa))) theorem filter_sub [simp] {p : A → Prop} [h : decidable_pred p] (l : list A) : filter p l ⊆ l := λ a ain, mem_of_mem_filter ain theorem filter_append {p : A → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list A), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by_cases (suppose p a, by rewrite [append_cons, *filter_cons_of_pos _ this, filter_append]) (suppose ¬ p a, by rewrite [append_cons, *filter_cons_of_neg _ this, filter_append]) /- foldl & foldr -/ definition foldl (f : A → B → A) : A → list B → A | a [] := a | a (b :: l) := foldl (f a b) l theorem foldl_nil [simp] (f : A → B → A) (a : A) : foldl f a [] = a theorem foldl_cons [simp] (f : A → B → A) (a : A) (b : B) (l : list B) : foldl f a (b::l) = foldl f (f a b) l definition foldr (f : A → B → B) : B → list A → B | b [] := b | b (a :: l) := f a (foldr b l) theorem foldr_nil [simp] (f : A → B → B) (b : B) : foldr f b [] = b theorem foldr_cons [simp] (f : A → B → B) (b : B) (a : A) (l : list A) : foldr f b (a::l) = f a (foldr f b l) section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative parameters {α : Type} {f : α → α → α} hypothesis (Hcomm : ∀ a b, f a b = f b a) hypothesis (Hassoc : ∀ a b c, f (f a b) c = f a (f b c)) include Hcomm Hassoc theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := Hcomm a b | a b (c::l) := begin change foldl f (f (f a b) c) l = f b (foldl f (f a c) l), rewrite -foldl_eq_of_comm_of_assoc, change foldl f (f (f a b) c) l = foldl f (f (f a c) b) l, have H₁ : f (f a b) c = f (f a c) b, by rewrite [Hassoc, Hassoc, Hcomm b c], rewrite H₁ end theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := begin rewrite foldl_eq_of_comm_of_assoc, esimp, change f b (foldl f a l) = f b (foldr f a l), rewrite foldl_eq_foldr end end foldl_eq_foldr theorem foldl_append [simp] (f : B → A → B) : ∀ (b : B) (l₁ l₂ : list A), foldl f b (l₁++l₂) = foldl f (foldl f b l₁) l₂ | b [] l₂ := rfl | b (a::l₁) l₂ := by rewrite [append_cons, *foldl_cons, foldl_append] theorem foldr_append [simp] (f : A → B → B) : ∀ (b : B) (l₁ l₂ : list A), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by rewrite [append_cons, *foldr_cons, foldr_append] /- all & any -/ definition all (l : list A) (p : A → Prop) : Prop := foldr (λ a r, p a ∧ r) true l definition any (l : list A) (p : A → Prop) : Prop := foldr (λ a r, p a ∨ r) false l theorem all_nil_eq [simp] (p : A → Prop) : all [] p = true theorem all_nil (p : A → Prop) : all [] p := trivial theorem all_cons_eq (p : A → Prop) (a : A) (l : list A) : all (a::l) p = (p a ∧ all l p) theorem all_cons {p : A → Prop} {a : A} {l : list A} (H1 : p a) (H2 : all l p) : all (a::l) p := and.intro H1 H2 theorem all_of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → all l p := assume h, by rewrite [all_cons_eq at h]; exact (and.elim_right h) theorem of_all_cons {p : A → Prop} {a : A} {l : list A} : all (a::l) p → p a := assume h, by rewrite [all_cons_eq at h]; exact (and.elim_left h) theorem all_cons_of_all {p : A → Prop} {a : A} {l : list A} : p a → all l p → all (a::l) p := assume pa alllp, and.intro pa alllp theorem all_implies {p q : A → Prop} : ∀ {l}, all l p → (∀ x, p x → q x) → all l q | [] h₁ h₂ := trivial | (a::l) h₁ h₂ := have all l q, from all_implies (all_of_all_cons h₁) h₂, have q a, from h₂ a (of_all_cons h₁), all_cons_of_all this `all l q` theorem of_mem_of_all {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → all l p → p a | [] h₁ h₂ := absurd h₁ !not_mem_nil | (b::l) h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (suppose a = b, by rewrite [all_cons_eq at h₂, -this at h₂]; exact (and.elim_left h₂)) (suppose a ∈ l, have all l p, by rewrite [all_cons_eq at h₂]; exact (and.elim_right h₂), of_mem_of_all `a ∈ l` this) theorem all_of_forall {p : A → Prop} : ∀ {l}, (∀a, a ∈ l → p a) → all l p | [] H := !all_nil | (a::l) H := all_cons (H a !mem_cons) (all_of_forall (λ a' H', H a' (mem_cons_of_mem _ H'))) theorem any_nil [simp] (p : A → Prop) : any [] p = false theorem any_cons [simp] (p : A → Prop) (a : A) (l : list A) : any (a::l) p = (p a ∨ any l p) theorem any_of_mem {p : A → Prop} {a : A} : ∀ {l}, a ∈ l → p a → any l p | [] i h := absurd i !not_mem_nil | (b::l) i h := or.elim (eq_or_mem_of_mem_cons i) (suppose a = b, by rewrite [-this]; exact (or.inl h)) (suppose a ∈ l, have any l p, from any_of_mem this h, or.inr this) theorem exists_of_any {p : A → Prop} : ∀{l : list A}, any l p → ∃a, a ∈ l ∧ p a | [] H := false.elim H | (b::l) H := or.elim H (assume H1 : p b, exists.intro b (and.intro !mem_cons H1)) (assume H1 : any l p, obtain a (H2l : a ∈ l) (H2r : p a), from exists_of_any H1, exists.intro a (and.intro (mem_cons_of_mem b H2l) H2r)) definition decidable_all (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (all l p) | [] := decidable_true | (a :: l) := match H a with | inl Hp₁ := match decidable_all l with | inl Hp₂ := inl (and.intro Hp₁ Hp₂) | inr Hn₂ := inr (not_and_of_not_right (p a) Hn₂) end | inr Hn := inr (not_and_of_not_left (all l p) Hn) end definition decidable_any (p : A → Prop) [H : decidable_pred p] : ∀ l, decidable (any l p) | [] := decidable_false | (a :: l) := match H a with | inl Hp := inl (or.inl Hp) | inr Hn₁ := match decidable_any l with | inl Hp₂ := inl (or.inr Hp₂) | inr Hn₂ := inr (not_or Hn₁ Hn₂) end end /- zip & unzip -/ definition zip (l₁ : list A) (l₂ : list B) : list (A × B) := map₂ (λ a b, (a, b)) l₁ l₂ definition unzip : list (A × B) → list A × list B | [] := ([], []) | ((a, b) :: l) := match unzip l with | (la, lb) := (a :: la, b :: lb) end theorem unzip_nil [simp] : unzip (@nil (A × B)) = ([], []) theorem unzip_cons [simp] (a : A) (b : B) (l : list (A × B)) : unzip ((a, b) :: l) = match unzip l with (la, lb) := (a :: la, b :: lb) end := rfl theorem zip_unzip : ∀ (l : list (A × B)), zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l | [] := rfl | ((a, b) :: l) := begin rewrite unzip_cons, have r : zip (pr₁ (unzip l)) (pr₂ (unzip l)) = l, from zip_unzip l, revert r, eapply prod.cases_on (unzip l), intro la lb r, rewrite -r end section mapAccumR variable {S : Type} -- This runs a function over a list returning the intermediate results and a -- a final result. definition mapAccumR : (A → S → S × B) → list A → S → (S × list B) | f [] c := (c, []) | f (y::yr) c := let r := mapAccumR f yr c in let z := f y (pr₁ r) in (pr₁ z, pr₂ z :: pr₂ r) theorem length_mapAccumR : ∀ (f : A → S → S × B) (x : list A) (s : S), length (pr₂ (mapAccumR f x s)) = length x | f (a::x) s := calc length (pr₂ (mapAccumR f (a::x) s)) = length x + 1 : { length_mapAccumR f x s } ... = length (a::x) : rfl | f [] s := calc length (pr₂ (mapAccumR f [] s)) = 0 : rfl end mapAccumR section mapAccumR₂ variable {S : Type} -- This runs a function over two lists returning the intermediate results and a -- a final result. definition mapAccumR₂ : (A → B → S → S × C) → list A → list B → S → S × list C | f [] _ c := (c,[]) | f _ [] c := (c,[]) | f (x::xr) (y::yr) c := let r := mapAccumR₂ f xr yr c in let q := f x y (pr₁ r) in (pr₁ q, pr₂ q :: (pr₂ r)) theorem length_mapAccumR₂ : ∀ (f : A → B → S → S × C) (x : list A) (y : list B) (c : S), length (pr₂ (mapAccumR₂ f x y c)) = min (length x) (length y) | f (a::x) (b::y) c := calc length (pr₂ (mapAccumR₂ f (a::x) (b::y) c)) = length (pr₂ (mapAccumR₂ f x y c)) + 1 : rfl ... = min (length x) (length y) + 1 : length_mapAccumR₂ f x y c ... = min (length (a::x)) (length (b::y)) : min_succ_succ | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end mapAccumR₂ /- flat -/ definition flat (l : list (list A)) : list A := foldl append nil l /- product -/ section product definition product : list A → list B → list (A × B) | [] l₂ := [] | (a::l₁) l₂ := map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem nil_product (l : list B) : product (@nil A) l = [] theorem product_cons (a : A) (l₁ : list A) (l₂ : list B) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ theorem product_nil : ∀ (l : list A), product l (@nil B) = [] | [] := rfl | (a::l) := by rewrite [product_cons, map_nil, product_nil] theorem eq_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → a₁ = a := assume ain, assert pr1 (a₁, b₁) ∈ map pr1 (map (λ b, (a, b)) l), from mem_map pr1 ain, assert a₁ ∈ map (λb, a) l, by revert this; rewrite [map_map, ↑pr1]; intro this; assumption, eq_of_map_const this theorem mem_of_mem_map_pair₁ {a₁ a : A} {b₁ : B} {l : list B} : (a₁, b₁) ∈ map (λ b, (a, b)) l → b₁ ∈ l := assume ain, assert pr2 (a₁, b₁) ∈ map pr2 (map (λ b, (a, b)) l), from mem_map pr2 ain, assert b₁ ∈ map (λx, x) l, by rewrite [map_map at this, ↑pr2 at this]; exact this, by rewrite [map_id at this]; exact this theorem mem_product {a : A} {b : B} : ∀ {l₁ l₂}, a ∈ l₁ → b ∈ l₂ → (a, b) ∈ product l₁ l₂ | [] l₂ h₁ h₂ := absurd h₁ !not_mem_nil | (x::l₁) l₂ h₁ h₂ := or.elim (eq_or_mem_of_mem_cons h₁) (assume aeqx : a = x, assert (a, b) ∈ map (λ b, (a, b)) l₂, from mem_map _ h₂, begin rewrite [-aeqx, product_cons], exact mem_append_left _ this end) (assume ainl₁ : a ∈ l₁, assert (a, b) ∈ product l₁ l₂, from mem_product ainl₁ h₂, begin rewrite [product_cons], exact mem_append_right _ this end) theorem mem_of_mem_product_left {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → a ∈ l₁ | [] l₂ h := absurd h !not_mem_nil | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, assert a = x, from eq_of_mem_map_pair₁ this, by rewrite this; exact !mem_cons) (suppose (a, b) ∈ product l₁ l₂, have a ∈ l₁, from mem_of_mem_product_left this, mem_cons_of_mem _ this) theorem mem_of_mem_product_right {a : A} {b : B} : ∀ {l₁ l₂}, (a, b) ∈ product l₁ l₂ → b ∈ l₂ | [] l₂ h := absurd h !not_mem_nil | (x::l₁) l₂ h := or.elim (mem_or_mem_of_mem_append h) (suppose (a, b) ∈ map (λ b, (x, b)) l₂, mem_of_mem_map_pair₁ this) (suppose (a, b) ∈ product l₁ l₂, mem_of_mem_product_right this) theorem length_product : ∀ (l₁ : list A) (l₂ : list B), length (product l₁ l₂) = length l₁ * length l₂ | [] l₂ := by rewrite [length_nil, zero_mul] | (x::l₁) l₂ := assert length (product l₁ l₂) = length l₁ * length l₂, from length_product l₁ l₂, by rewrite [product_cons, length_append, length_cons, length_map, this, right_distrib, one_mul, add.comm] end product -- new for list/comb dependent map theory definition dinj₁ (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), a1 ≠ a2 → (f a1 h1) ≠ (f a2 h2) definition dinj (p : A → Prop) (f : Π a, p a → B) := ∀ ⦃a1 a2⦄ (h1 : p a1) (h2 : p a2), (f a1 h1) = (f a2 h2) → a1 = a2 definition dmap (p : A → Prop) [h : decidable_pred p] (f : Π a, p a → B) : list A → list B | [] := [] | (a::l) := if P : (p a) then cons (f a P) (dmap l) else (dmap l) -- properties of dmap section dmap variable {p : A → Prop} variable [h : decidable_pred p] include h variable {f : Π a, p a → B} lemma dmap_nil : dmap p f [] = [] := rfl lemma dmap_cons_of_pos {a : A} (P : p a) : ∀ l, dmap p f (a::l) = (f a P) :: dmap p f l := λ l, dif_pos P lemma dmap_cons_of_neg {a : A} (P : ¬ p a) : ∀ l, dmap p f (a::l) = dmap p f l := λ l, dif_neg P lemma mem_dmap : ∀ {l : list A} {a} (Pa : p a), a ∈ l → (f a Pa) ∈ dmap p f l | [] := take a Pa Pinnil, by contradiction | (a::l) := take b Pb Pbin, or.elim (eq_or_mem_of_mem_cons Pbin) (assume Pbeqa, begin rewrite [eq.symm Pbeqa, dmap_cons_of_pos Pb], exact !mem_cons end) (assume Pbinl, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa], apply mem_cons_of_mem, exact mem_dmap Pb Pbinl end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], exact mem_dmap Pb Pbinl end)) lemma exists_of_mem_dmap : ∀ {l : list A} {b : B}, b ∈ dmap p f l → ∃ a P, a ∈ l ∧ b = f a P | [] := take b, by rewrite dmap_nil; contradiction | (a::l) := take b, decidable.rec_on (h a) (assume Pa, begin rewrite [dmap_cons_of_pos Pa, mem_cons_iff], intro Pb, cases Pb with Peq Pin, exact exists.intro a (exists.intro Pa (and.intro !mem_cons Peq)), assert Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end) (assume nPa, begin rewrite [dmap_cons_of_neg nPa], intro Pin, assert Pex : ∃ (a : A) (P : p a), a ∈ l ∧ b = f a P, exact exists_of_mem_dmap Pin, cases Pex with a' Pex', cases Pex' with Pa' P', exact exists.intro a' (exists.intro Pa' (and.intro (mem_cons_of_mem a (and.left P')) (and.right P'))) end) lemma map_dmap_of_inv_of_pos {g : B → A} (Pinv : ∀ a (Pa : p a), g (f a Pa) = a) : ∀ {l : list A}, (∀ ⦃a⦄, a ∈ l → p a) → map g (dmap p f l) = l | [] := assume Pl, by rewrite [dmap_nil, map_nil] | (a::l) := assume Pal, assert Pa : p a, from Pal a !mem_cons, assert Pl : ∀ a, a ∈ l → p a, from take x Pxin, Pal x (mem_cons_of_mem a Pxin), by rewrite [dmap_cons_of_pos Pa, map_cons, Pinv, map_dmap_of_inv_of_pos Pl] lemma mem_of_dinj_of_mem_dmap (Pdi : dinj p f) : ∀ {l : list A} {a} (Pa : p a), (f a Pa) ∈ dmap p f l → a ∈ l | [] := take a Pa Pinnil, by contradiction | (b::l) := take a Pa Pmap, decidable.rec_on (h b) (λ Pb, begin rewrite (dmap_cons_of_pos Pb) at Pmap, rewrite mem_cons_iff at Pmap, rewrite mem_cons_iff, apply (or_of_or_of_imp_of_imp Pmap), apply Pdi, apply mem_of_dinj_of_mem_dmap Pa end) (λ nPb, begin rewrite (dmap_cons_of_neg nPb) at Pmap, apply mem_cons_of_mem, exact mem_of_dinj_of_mem_dmap Pa Pmap end) lemma not_mem_dmap_of_dinj_of_not_mem (Pdi : dinj p f) {l : list A} {a} (Pa : p a) : a ∉ l → (f a Pa) ∉ dmap p f l := not.mto (mem_of_dinj_of_mem_dmap Pdi Pa) end dmap section open equiv definition list_equiv_of_equiv {A B : Type} : A ≃ B → list A ≃ list B | (mk f g l r) := mk (map f) (map g) begin intros, rewrite [map_map, id_of_left_inverse l, map_id], try reflexivity end begin intros, rewrite [map_map, id_of_righ_inverse r, map_id], try reflexivity end private definition to_nat : list nat → nat | [] := 0 | (x::xs) := succ (mkpair (to_nat xs) x) open prod.ops private definition of_nat.F : Π (n : nat), (Π m, m < n → list nat) → list nat | 0 f := [] | (succ n) f := (unpair n).2 :: f (unpair n).1 (unpair_lt n) private definition of_nat : nat → list nat := well_founded.fix of_nat.F private lemma of_nat_zero : of_nat 0 = [] := well_founded.fix_eq of_nat.F 0 private lemma of_nat_succ (n : nat) : of_nat (succ n) = (unpair n).2 :: of_nat (unpair n).1 := well_founded.fix_eq of_nat.F (succ n) private lemma to_nat_of_nat (n : nat) : to_nat (of_nat n) = n := nat.case_strong_induction_on n _ (λ n ih, begin rewrite of_nat_succ, unfold to_nat, have to_nat (of_nat (unpair n).1) = (unpair n).1, from ih _ (le_of_lt_succ (unpair_lt n)), rewrite this, rewrite mkpair_unpair end) private lemma of_nat_to_nat : ∀ (l : list nat), of_nat (to_nat l) = l | [] := rfl | (x::xs) := begin unfold to_nat, rewrite of_nat_succ, rewrite *unpair_mkpair, esimp, congruence, apply of_nat_to_nat end definition list_nat_equiv_nat : list nat ≃ nat := mk to_nat of_nat of_nat_to_nat to_nat_of_nat definition list_equiv_self_of_equiv_nat {A : Type} : A ≃ nat → list A ≃ A := suppose A ≃ nat, calc list A ≃ list nat : list_equiv_of_equiv this ... ≃ nat : list_nat_equiv_nat ... ≃ A : this end end list attribute list.decidable_any [instance] attribute list.decidable_all [instance]
d01e60649743b9eda4f70342f67445b05e2ec9b4
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/groupoid.lean
4438eb1036a19fb81f1cc79afc11e8c8cf5fa33f
[ "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
2,085
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison, David Wärn -/ import category_theory.epi_mono namespace category_theory universes v v₂ u u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation /-- A `groupoid` is a category such that all morphisms are isomorphisms. -/ class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) := (inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X)) (inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously) (comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously) restate_axiom groupoid.inv_comp' restate_axiom groupoid.comp_inv' attribute [simp] groupoid.inv_comp groupoid.comp_inv abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C section variables {C : Type u} [groupoid.{v} C] {X Y : C} @[priority 100] -- see Note [lower instance priority] instance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f := { inv := groupoid.inv f } variables (X Y) /-- In a groupoid, isomorphisms are equivalent to morphisms. -/ def groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) := { to_fun := iso.hom, inv_fun := λ f, as_iso f, left_inv := λ i, iso.ext rfl, right_inv := λ f, rfl } end section variables {C : Type u} [category.{v} C] /-- A category where every morphism `is_iso` is a groupoid. -/ def groupoid.of_is_iso (all_is_iso : ∀ {X Y : C} (f : X ⟶ Y), is_iso f) : groupoid.{v} C := { inv := λ X Y f, (all_is_iso f).inv } /-- A category where every morphism has a `trunc` retraction is computably a groupoid. -/ def groupoid.of_trunc_split_mono (all_split_mono : ∀ {X Y : C} (f : X ⟶ Y), trunc (split_mono f)) : groupoid.{v} C := begin apply groupoid.of_is_iso, intros X Y f, trunc_cases all_split_mono f, trunc_cases all_split_mono (retraction f), apply is_iso.of_mono_retraction, end end end category_theory
80baeaab2f4891034c33e00ff2b9b4788774837b
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Meta/Tactic/Simp/Types.lean
e2b4bb4678e3daea4a560adf3feef0d370ed821f
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
2,142
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.Tactic.Simp.SimpLemmas import Lean.Meta.Tactic.Simp.CongrLemmas namespace Lean.Meta namespace Simp structure Result where expr : Expr proof? : Option Expr := none -- If none, proof is assumed to be `refl` deriving Inhabited abbrev Cache := ExprMap Result structure Context where config : Config simpLemmas : SimpLemmas congrLemmas : CongrLemmas parent? : Option Expr := none structure State where cache : Cache := {} numSteps : Nat := 0 abbrev SimpM := ReaderT Context $ StateRefT State MetaM inductive Step where | visit : Result → Step | done : Result → Step deriving Inhabited def Step.result : Step → Result | Step.visit r => r | Step.done r => r structure Methods where pre : Expr → SimpM Step := fun e => return Step.visit { expr := e } post : Expr → SimpM Step := fun e => return Step.done { expr := e } discharge? : Expr → SimpM (Option Expr) := fun e => return none deriving Inhabited /- Internal monad -/ abbrev M := ReaderT Methods SimpM def pre (e : Expr) : M Step := do (← read).pre e def post (e : Expr) : M Step := do (← read).post e def discharge? (e : Expr) : M (Option Expr) := do (← read).discharge? e def getConfig : M Config := return (← readThe Context).config @[inline] def withParent (parent : Expr) (f : M α) : M α := withTheReader Context (fun ctx => { ctx with parent? := parent }) f def getSimpLemmas : M SimpLemmas := return (← readThe Context).simpLemmas def getCongrLemmas : M CongrLemmas := return (← readThe Context).congrLemmas @[inline] def withSimpLemmas (s : SimpLemmas) (x : M α) : M α := do let cacheSaved := (← get).cache modify fun s => { s with cache := {} } try withTheReader Context (fun ctx => { ctx with simpLemmas := s }) x finally modify fun s => { s with cache := cacheSaved } end Simp export Simp (SimpM) end Lean.Meta
3620a07ff15cbb4aa143c7544e4ab185aba1b8bb
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Meta/Basic.lean
8f13208492a5e78fed5ede6669a34dca5fb00511
[ "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
73,171
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.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.ReplaceExpr import Lean.Util.MonadBacktrack import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode /-! This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck /-- Configuration flags for the `MetaM` monad. Many of them are used to control the `isDefEq` function that checks whether two terms are definitionally equal or not. Recall that when `isDefEq` is trying to check whether `?m@C a₁ ... aₙ` and `t` are definitionally equal (`?m@C a₁ ... aₙ =?= t`), where `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. We solve it using the assignment `?m := fun a₁ ... aₙ => t` if 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` -/ structure Config where /-- If `foApprox` is set to true, and some `aᵢ` is not a free variable, then we use first-order unification ``` ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k ``` reduces to ``` ?m a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k ``` -/ foApprox : Bool := false /-- When `ctxApprox` is set to true, we relax condition 4, by creating an auxiliary metavariable `?n'` with a smaller context than `?m'`. -/ ctxApprox : Bool := false /-- When `quasiPatternApprox` is set to true, we ignore condition 2. -/ quasiPatternApprox : Bool := false /-- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /-- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. 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`. -/ isDefEqStuckEx : Bool := false /-- Controls which definitions and theorems can be unfolded by `isDefEq` and `whnf`. -/ transparency : TransparencyMode := TransparencyMode.default /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false /-- Enable/disable the unification hints feature. -/ unificationHints : Bool := true /-- Enables proof irrelevance at `isDefEq` -/ proofIrrelevance : Bool := true /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics. However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because this last unification step is not really part of the term elaboration. -/ assignSyntheticOpaque : Bool := false /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with `depth == metavariable` context depth can be assigned. We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few cases. Recall that universe levels are often ignored by users, they may not even be aware they exist. We set `ignoreLevelMVarDepth := false` during `simp`. See comment at `withSimpConfig` and issue #1829. -/ ignoreLevelMVarDepth : Bool := true /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/ offsetCnstrs : Bool := true /-- Eta for structures configuration mode. -/ etaStruct : EtaStructMode := .all /-- Function parameter information cache. -/ structure ParamInfo where /-- The binder annotation for the parameter. -/ binderInfo : BinderInfo := BinderInfo.default /-- `hasFwdDeps` is true if there is another parameter whose type depends on this one. -/ hasFwdDeps : Bool := false /-- `backDeps` contains the backwards dependencies. That is, the (0-indexed) position of previous parameters that this one depends on. -/ backDeps : Array Nat := #[] /-- `isProp` is true if the parameter is always a proposition. -/ isProp : Bool := false /-- `isDecInst` is true if the parameter's type is of the form `Decidable ...`. This information affects the generation of congruence theorems. -/ isDecInst : Bool := false /-- `higherOrderOutParam` is true if this parameter is a higher-order output parameter of local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter `dom` because it is output parameter of `[self : GetElem cont idx elem dom]` -/ higherOrderOutParam : Bool := false /-- `dependsOnHigherOrderOutParam` is true if the type of this parameter depends on the higher-order output parameter of a previous local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter with type `dom xs i` since `dom` is an output parameter of the instance `[self : GetElem cont idx elem dom]` -/ dependsOnHigherOrderOutParam : Bool := false deriving Inhabited def ParamInfo.isImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.implicit def ParamInfo.isInstImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.instImplicit def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.strictImplicit def ParamInfo.isExplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.default /-- Function information cache. See `ParamInfo`. -/ structure FunInfo where /-- Parameter information cache. -/ paramInfo : Array ParamInfo := #[] /-- `resultDeps` contains the function result type backwards dependencies. That is, the (0-indexed) position of parameters that the result type depends on. -/ resultDeps : Array Nat := #[] /-- Key for the function information cache. -/ structure InfoCacheKey where /-- The transparency mode used to compute the `FunInfo`. -/ transparency : TransparencyMode /-- The function being cached information about. It is quite often an `Expr.const`. -/ expr : Expr /-- `nargs? = some n` if the cached information was computed assuming the function has arity `n`. If `nargs? = none`, then the cache information consumed the arrow type as much as possible unsing the current transparency setting. X-/ nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr /-- A mapping `(s, t) ↦ isDefEq s t`. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache). We should also investigate the impact on memory consumption. -/ abbrev DefEqCache := PersistentHashMap (Expr × Expr) Bool /-- Cache datastructures for type inference, type class resolution, whnf, and definitional equality. -/ structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` defEq : DefEqCache := {} deriving Inhabited /-- "Context" for a postponed universe constraint. `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created. -/ structure DefEqContext where lhs : Expr rhs : Expr lctx : LocalContext localInstances : LocalInstances /-- Auxiliary structure for representing postponed universe constraints. Remark: the fields `ref` and `rootDefEq?` are used for error message generation only. Remark: we may consider improving the error message generation in the future. -/ structure PostponedEntry where /-- We save the `ref` at entry creation time. This is used for reporting errors back to the user. -/ ref : Syntax lhs : Level rhs : Level /-- Context for the surrounding `isDefEq` call when entry was created. -/ ctx? : Option DefEqContext deriving Inhabited /-- `MetaM` monad state. -/ structure State where mctx : MetavarContext := {} cache : Cache := {} /-- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : FVarIdSet := {} /-- Array of postponed universe level constraints -/ postponed : PersistentArray PostponedEntry := {} deriving Inhabited /-- Backtrackable state for the `MetaM` monad. -/ structure SavedState where core : Core.State meta : State deriving Inhabited /-- Contextual information for the `MetaM` monad. -/ structure Context where config : Config := {} /-- Local context -/ lctx : LocalContext := {} /-- Local instances in `lctx`. -/ localInstances : LocalInstances := #[] /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/ defEqCtx? : Option DefEqContext := none /-- Track the number of nested `synthPending` invocations. Nested invocations can happen when the type class resolution invokes `synthPending`. Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`. We will add a configuration option if necessary. -/ synthPendingDepth : Nat := 0 /-- A predicate to control whether a constant can be unfolded or not at `whnf`. Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/ canUnfold? : Option (Config → ConstantInfo → CoreM Bool) := none abbrev MetaM := ReaderT Context $ StateRefT State CoreM -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. @[always_inline] instance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind } instance : Inhabited (MetaM α) where default := fun _ _ => default instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadEnv MetaM where getEnv := return (← getThe Core.State).env modifyEnv f := do modifyThe Core.State fun s => { s with env := f s.env, cache := {} }; modify fun s => { s with cache := {} } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull protected def saveState : MetaM SavedState := return { core := (← getThe Core.State), meta := (← get) } /-- Restore backtrackable parts of the state. -/ def SavedState.restore (b : SavedState) : MetaM Unit := do Core.restore b.core modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed } instance : MonadBacktrack SavedState MetaM where saveState := Meta.saveState restoreState s := s.restore @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug export Core (instantiateTypeLevelParams instantiateValueLevelParams) @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4, c5⟩ => ⟨f ic, c1, c2, c3, c4, c5⟩ @[inline] def modifyDefEqCache (f : DefEqCache → DefEqCache) : MetaM Unit := modifyCache fun ⟨c1, c2, c3, c4, c5, defeq⟩ => ⟨c1, c2, c3, c4, c5, f defeq⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM FVarIdSet := return (← get).zetaFVarIds /-- Return the array of postponed universe level constraints. -/ def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed /-- Set the array of postponed universe level constraints. -/ def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } /-- Modify the array of postponed universe level constraints. -/ @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } /-- `useEtaStruct inductName` return `true` if we eta for structures is enabled for for the inductive datatype `inductName`. Recall we have three different settings: `.none` (never use it), `.all` (always use it), `.notClasses` (enabled only for structure-like inductive types that are not classes). The parameter `inductName` affects the result only if the current setting is `.notClasses`. -/ def useEtaStruct (inductName : Name) : MetaM Bool := do match (← getConfig).etaStruct with | .none => return false | .all => return true | .notClasses => return !isClass (← getEnv) inductName /-! WARNING: The following 4 constants are a hack for simulating forward declarations. They are defined later using the `export` attribute. This is hackish because we have to hard-code the true arity of these definitions here, and make sure the C names match. We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/ /-- Reduces an expression to its Weak Head Normal Form. This is when the topmost expression has been fully reduced, but may contain subexpressions which have not been reduced. -/ @[extern 6 "lean_whnf"] opaque whnf : Expr → MetaM Expr /-- Returns the inferred type of the given expression, or fails if it is not type-correct. -/ @[extern 6 "lean_infer_type"] opaque inferType : Expr → MetaM Expr @[extern 7 "lean_is_expr_def_eq"] opaque isExprDefEqAux : Expr → Expr → MetaM Bool @[extern 7 "lean_is_level_def_eq"] opaque isLevelDefEqAux : Level → Level → MetaM Bool @[extern 6 "lean_synth_pending"] protected opaque synthPending : MVarId → MetaM Bool def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshLMVarId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /-- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshLevelMVars (num : Nat) : MetaM (List Level) := num.foldM (init := []) fun _ us => return (← mkFreshLevelMVar)::us def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) := mkFreshLevelMVars info.numLevelParams /-- Create a constant with the given name and new universe metavariables. Example: ``mkConstWithFreshMVarLevels `Monad`` returns `@Monad.{?u, ?v}` -/ def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do let info ← getConstInfo declName return mkConst declName (← mkFreshLevelMVarsFor info) /-- Return current transparency setting/mode. -/ def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible /-- Return `some mvarDecl` where `mvarDecl` is `mvarId` declaration in the current metavariable context. Return `none` if `mvarId` has no declaration in the current metavariable context. -/ def _root_.Lean.MVarId.findDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := return (← getMCtx).findDecl? mvarId @[deprecated MVarId.findDecl?] def findMVarDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := mvarId.findDecl? /-- Return `mvarId` declaration in the current metavariable context. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getDecl (mvarId : MVarId) : MetaM MetavarDecl := do match (← mvarId.findDecl?) with | some d => pure d | none => throwError "unknown metavariable '?{mvarId.name}'" @[deprecated MVarId.getDecl] def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do mvarId.getDecl /-- Return `mvarId` kind. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getKind (mvarId : MVarId) : MetaM MetavarKind := return (← mvarId.getDecl).kind @[deprecated MVarId.getKind] def getMVarDeclKind (mvarId : MVarId) : MetaM MetavarKind := mvarId.getKind /-- Reture `true` if `e` is a synthetic (or synthetic opaque) metavariable -/ def isSyntheticMVar (e : Expr) : MetaM Bool := do if e.isMVar then return (← e.mvarId!.getKind) matches .synthetic | .syntheticOpaque else return false /-- Set `mvarId` kind in the current metavariable context. -/ def _root_.Lean.MVarId.setKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind @[deprecated MVarId.setKind] def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := mvarId.setKind kind /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def _root_.Lean.MVarId.setType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type @[deprecated MVarId.setType] def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do mvarId.setType type /-- Return true if the given metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.MVarId.isReadOnly (mvarId : MVarId) : MetaM Bool := do return (← mvarId.getDecl).depth != (← getMCtx).depth @[deprecated MVarId.isReadOnly] def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnly /-- Return true if `mvarId.isReadOnly` return true or if `mvarId` is a synthetic opaque metavariable. Recall `isDefEq` will not assign a value to `mvarId` if `mvarId.isReadOnlyOrSyntheticOpaque`. -/ def _root_.Lean.MVarId.isReadOnlyOrSyntheticOpaque (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← mvarId.getDecl match mvarDecl.kind with | MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque | _ => return mvarDecl.depth != (← getMCtx).depth @[deprecated MVarId.isReadOnlyOrSyntheticOpaque] def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnlyOrSyntheticOpaque /-- Return the level of the given universe level metavariable. -/ def _root_.Lean.LMVarId.getLevel (mvarId : LMVarId) : MetaM Nat := do match (← getMCtx).findLevelDepth? mvarId with | some depth => return depth | _ => throwError "unknown universe metavariable '?{mvarId.name}'" @[deprecated LMVarId.getLevel] def getLevelMVarDepth (mvarId : LMVarId) : MetaM Nat := mvarId.getLevel /-- Return true if the given universe metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.LMVarId.isReadOnly (mvarId : LMVarId) : MetaM Bool := do if (← getConfig).ignoreLevelMVarDepth then return false else return (← mvarId.getLevel) != (← getMCtx).depth @[deprecated LMVarId.isReadOnly] def isReadOnlyLevelMVar (mvarId : LMVarId) : MetaM Bool := do mvarId.isReadOnly /-- Set the user-facing name for the given metavariable. -/ def _root_.Lean.MVarId.setUserName (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarUserName mvarId newUserName @[deprecated MVarId.setUserName] def setMVarUserName (mvarId : MVarId) (userNameNew : Name) : MetaM Unit := mvarId.setUserName userNameNew /-- Throw an exception saying `fvarId` is not declared in the current local context. -/ def _root_.Lean.FVarId.throwUnknown (fvarId : FVarId) : CoreM α := throwError "unknown free variable '{mkFVar fvarId}'" @[deprecated FVarId.throwUnknown] def throwUnknownFVar (fvarId : FVarId) : MetaM α := fvarId.throwUnknown /-- Return `some decl` if `fvarId` is declared in the current local context. -/ def _root_.Lean.FVarId.findDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId @[deprecated FVarId.findDecl?] def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := fvarId.findDecl? /-- Return the local declaration for the given free variable. Throw an exception if local declaration is not in the current local context. -/ def _root_.Lean.FVarId.getDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => return d | none => fvarId.throwUnknown @[deprecated FVarId.getDecl] def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do fvarId.getDecl /-- Return the type of the given free variable. -/ def _root_.Lean.FVarId.getType (fvarId : FVarId) : MetaM Expr := return (← fvarId.getDecl).type /-- Return the binder information for the given free variable. -/ def _root_.Lean.FVarId.getBinderInfo (fvarId : FVarId) : MetaM BinderInfo := return (← fvarId.getDecl).binderInfo /-- Return `some value` if the given free variable is a let-declaration, and `none` otherwise. -/ def _root_.Lean.FVarId.getValue? (fvarId : FVarId) : MetaM (Option Expr) := return (← fvarId.getDecl).value? /-- Return the user-facing name for the given free variable. -/ def _root_.Lean.FVarId.getUserName (fvarId : FVarId) : MetaM Name := return (← fvarId.getDecl).userName /-- Return `true` is the free variable is a let-variable. -/ def _root_.Lean.FVarId.isLetVar (fvarId : FVarId) : MetaM Bool := return (← fvarId.getDecl).isLet /-- Get the local declaration associated to the given `Expr` in the current local context. Fails if the given expression is not a fvar or if no such declaration exists. -/ def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := fvar.fvarId!.getDecl /-- Given a user-facing name for a free variable, return its declaration in the current local context. Throw an exception if free variable is not declared. -/ def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError "unknown local declaration '{userName}'" /-- Given a user-facing name for a free variable, return the free variable or throw if not declared. -/ def getFVarFromUserName (userName : Name) : MetaM Expr := do let d ← getLocalDeclFromUserName userName return Expr.fvar d.fvarId /-- Lift a `MkBindingM` monadic action `x` to `MetaM`. -/ @[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do match x { lctx := (← getLCtx), mainModule := (← getEnv).mainModule } { mctx := (← getMCtx), ngen := (← getNGen), nextMacroScope := (← getThe Core.State).nextMacroScope } with | .ok e sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } pure e | .error (.revertFailure ..) sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } throwError "failed to create binder due to failure when reverting variable dependencies" /-- Similar to `abstracM` but consider only the first `min n xs.size` entries in `xs` It is also similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. -/ def _root_.Lean.Expr.abstractRangeM (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := liftMkBindingM <| MetavarContext.abstractRange e n xs @[deprecated Expr.abstractRangeM] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := e.abstractRangeM n xs /-- Replace free (or meta) variables `xs` with loose bound variables. Similar to `Expr.abstract`, but handles metavariables correctly. -/ def _root_.Lean.Expr.abstractM (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractRangeM xs.size xs @[deprecated Expr.abstractM] def abstract (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractM xs /-- Collect forward dependencies for the free variables in `toRevert`. Recall that when reverting free variables `xs`, we must also revert their forward dependencies. -/ def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MetaM (Array Expr) := do liftMkBindingM <| MetavarContext.collectForwardDeps toRevert preserveOrder /-- Takes an array `xs` of free variables or metavariables and a term `e` that may contain those variables, and abstracts and binds them as universal quantifiers. - if `usedOnly = true` then only variables that the expression body depends on will appear. - if `usedLetOnly = true` same as `usedOnly` except for let-bound variables. (That is, local constants which have been assigned a value.) -/ def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly binderInfoForMVars /-- Takes an array `xs` of free variables and metavariables and a body term `e` and creates `fun ..xs => e`, suitably abstracting `e` and the types in `xs`. -/ def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly binderInfoForMVars def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := mkLambdaFVars xs e (usedLetOnly := usedLetOnly) (binderInfoForMVars := binderInfoForMVars) /-- `fun _ : Unit => a` -/ def mkFunUnit (a : Expr) : MetaM Expr := return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder /-- `withConfig f x` executes `x` using the updated configuration object obtained by applying `f`. -/ @[inline] def withConfig (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withoutProofIrrelevance (x : n α) : n α := withConfig (fun cfg => { cfg with proofIrrelevance := false }) x @[inline] def withTransparency (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) /-- `withDefault x` excutes `x` using the default transparency setting. -/ @[inline] def withDefault (x : n α) : n α := withTransparency TransparencyMode.default x /-- `withReducible x` excutes `x` using the reducible transparency setting. In this setting only definitions tagged as `[reducible]` are unfolded. -/ @[inline] def withReducible (x : n α) : n α := withTransparency TransparencyMode.reducible x /-- `withReducibleAndInstances x` excutes `x` using the `.instances` transparency setting. In this setting only definitions tagged as `[reducible]` or type class instances are unfolded. -/ @[inline] def withReducibleAndInstances (x : n α) : n α := withTransparency TransparencyMode.instances x /-- Execute `x` ensuring the transparency setting is at least `mode`. Recall that `.all > .default > .instances > .reducible`. -/ @[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/ @[inline] def withAssignableSyntheticOpaque (x : n α) : n α := withConfig (fun config => { config with assignSyntheticOpaque := true }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do let savedCache := (← get).cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /-- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do if isClass (← getEnv) constName then return .some constName else match (← getConstTemp? constName) with | some (.defnInfo ..) => return .undef -- We may be able to unfold the definition | _ => return .none private partial def isClassQuick? : Expr → MetaM (LOption Name) | .bvar .. => return .none | .lit .. => return .none | .fvar .. => return .none | .sort .. => return .none | .lam .. => return .none | .letE .. => return .undef | .proj .. => return .undef | .forallE _ _ b _ => isClassQuick? b | .mdata _ e => isClassQuick? e | .const n _ => isClassQuickConst? n | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => return .none | .app f _ => match f.getAppFn with | .const n .. => isClassQuickConst? n | .lam .. => return .undef | _ => return .none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let savedSythInstance := (← get).cache.synthInstance modifyCache fun c => { c with synthInstance := {} } return savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar if localDecl.isImplementationDetail then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | .none => withNewLocalInstancesImp fvars (i+1) k | .undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | .some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | .forallE n d b bi => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? (type : Expr) : MetaM (Option Name) := withReducible do -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun _ type => do let env ← getEnv match type.getAppFn with | .const c _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | .const c _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | .none => return none | .some c => return (some c) | .undef => isClassExpensive? type end /-- `isClass? type` return `some ClsName` if `type` is an instance of the class `ClsName`. Example: ``` #eval do let x ← mkAppM ``Inhabited #[mkConst ``Nat] IO.println (← isClass? x) -- (some Inhabited) ``` -/ def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => return none private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do process consumeLet (← getLCtx) #[] 0 e where process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, .lam n d b bi => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, .letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e /-- Similar to `lambdaTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e true k) k /-- Given `e` of the form `fun ..xs => A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def lambdaTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e false k) k /-- Return the parameter names for the given global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do xs.mapM fun x => do let localDecl ← x.fvarId!.getDecl return localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do if maxMVars?.isEqSome mvars.size then let type := type.instantiateRevRange j mvars.size mvars; return (mvars, bis, type) else match type with | .forallE n d b bi => let d := d.instantiateRevRange j mvars.size mvars let k := if bi.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else return (mvars, bis, type) else return (mvars, bis, type) /-- Given `e` of the form `forall ..xs, A`, this combinator will create a new metavariable for each `x` in `xs` and instantiate `A` with these. Returns a product containing - the new metavariables - the binder info for the `xs` - the instantiated `A` -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallMetaTelescope`, but if `e = forall ..xs, A` it will reduce `A` to construct further mvars. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/ def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind) /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars return (mvars, bis, type) if maxMVars?.isEqSome mvars.size then finalize () else match type with | .lam _ d b bi => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => finalize () private def withNewFVar (n : Name) (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do if let some c ← isClass? fvarType then withNewLocalInstance c fvar <| k fvar else k fvar private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) (kind : LocalDeclKind) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi kind let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar n fvar type k /-- Create a free variable `x` with name, binderInfo and type, add it to the context and run in `k`. Then revert the context. -/ def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) (kind : LocalDeclKind := .default) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k kind) k def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k /-- Append an array of free variables `xs` to the local context and execute `k xs`. declInfos takes the form of an array consisting of: - the name of the variable - the binder info of the variable - a type constructor for the variable, where the array consists of all of the free variables defined prior to this one. This is needed because the type of the variable may depend on prior variables. -/ partial def withLocalDecls [Inhabited α] (declInfos : Array (Name × BinderInfo × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := loop #[] where loop [Inhabited α] (acc : Array Expr) : n α := do if acc.size < declInfos.size then let (name, bi, typeCtor) := declInfos[acc.size]! withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x) else k acc def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := withLocalDecls (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) => lctx.setBinderInfo fvarId bi withReader (fun ctx => { ctx with lctx := lctx }) k def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α := mapMetaM (fun k => withNewBinderInfosImp bs k) k /-- Execute `k` using a local context where any `x` in `xs` that is tagged as instance implicit is treated as a regular implicit. -/ def withInstImplicitAsImplict (xs : Array Expr) (k : MetaM α) : MetaM α := do let newBinderInfos ← xs.filterMapM fun x => do let bi ← x.fvarId!.getBinderInfo if bi == .instImplicit then return some (x.fvarId!, .implicit) else return none withNewBinderInfos newBinderInfos k private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) (kind : LocalDeclKind) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val (nonDep := false) kind let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar n fvar type k /-- Add the local declaration `<name> : <type> := <val>` to the local context and execute `k x`, where `x` is a new free variable corresponding to the `let`-declaration. After executing `k x`, the local context is restored. -/ def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) (kind : LocalDeclKind := .default) : n α := map1MetaM (fun k => withLetDeclImp name type val k kind) k def withLocalInstancesImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let mut localInsts := (← read).localInstances let size := localInsts.size for decl in decls do unless decl.isImplementationDetail do if let some className ← isClass? decl.type then localInsts := localInsts.push { className, fvar := decl.toExpr } if localInsts.size == size then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := localInsts }) k /-- Register any local instance in `decls` -/ def withLocalInstances (decls : List LocalDecl) : n α → n α := mapMetaM <| withLocalInstancesImp decls private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do withLocalInstancesImp decls k /-- `withExistingLocalDecls decls k`, adds the given local declarations to the local context, and then executes `k`. This method assumes declarations in `decls` have valid `FVarId`s. After executing `k`, the local context is restored. Remark: this method is used, for example, to implement the `match`-compiler. Each `match`-alternative commes with a local declarations (corresponding to pattern variables), and we use `withExistingLocalDecls` to add them to the local context before we process them. -/ def withExistingLocalDecls (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do let saved ← get modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} } try x finally modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed } /-- `withNewMCtxDepth k` executes `k` with a higher metavariable context depth, where metavariables created outside the `withNewMCtxDepth` (with a lower depth) cannot be assigned. Note that this does not affect level metavariables (by default). See the docstring of `isDefEq` for more information. -/ def withNewMCtxDepth : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x /-- `withLCtx lctx localInsts k` replaces the local context and local instances, and then executes `k`. The local context and instances are restored after executing `k`. This method assumes that the local instances in `localInsts` are in the local context `lctx`. -/ def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← mvarId.getDecl withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def _root_.Lean.MVarId.withContext (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId @[deprecated MVarId.withContext] def withMVarContext (mvarId : MVarId) : n α → n α := mvarId.withContext private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' /-- `withMCtx mctx k` replaces the metavariable context and then executes `k`. The metavariable context is restored after executing `k`. This method is used to implement the type class resolution procedure. -/ def withMCtx (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq : n α → n α := mapMetaM fullApproxDefEqImp /-- Instantiate assigned universe metavariables in `u`, and then normalize it. -/ def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize /-- `whnf` with reducible transparency.-/ def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e /-- `whnf` with default transparency.-/ def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e /-- `whnf` with instances transparency.-/ def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e /-- Mark declaration `declName` with the attribute `[inline]`. This method does not check whether the given declaration is a definition. Recall that this attribute can only be set in the same module where `declName` has been declared. -/ def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | .ok env => setEnv env | .error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else return e /-- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else return e /-- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Pretty-print the given expression. -/ def ppExpr (e : Expr) : MetaM Format := do let ctxCore ← readThe Core.Context Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do let s ← saveState try x catch _ => s.restore; y () instance : OrElse (MetaM α) := ⟨Meta.orElse⟩ instance : Alternative MetaM where failure := fun {_} => throwError "failed" orElse := Meta.orElse @[inline] private def orelseMergeErrorsImp (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- Sort free variables using an order `x < y` iff `x` was defined before `y`. If a free variable is not in the local context, we use their id. -/ def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do let lctx ← getLCtx return fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index < d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁.name fvarId₂.name end Methods /-- Return `true` if `declName` is an inductive predicate. That is, `inductive` type in `Prop`. -/ def isInductivePredicate (declName : Name) : MetaM Bool := do match (← getEnv).find? declName with | some (.inductInfo { type := type, ..}) => forallTelescopeReducing type fun _ type => do match (← whnfD type) with | .sort u .. => return u == levelZero | _ => return false | _ => return false def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false def getNumPostponed : MetaM Nat := do return (← getPostponed).size def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | .const _ us => if us.any p then some (e.setPPUniverses true) else none | .sort u => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | .mvar m => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then withRef p.ref do throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else let numPostponedBegin ← getNumPostponed withTraceNode `Meta.isLevelDefEq.postponed (fun _ => return m!"processing #{numPostponedBegin} postponed is-def-eq level constraints") do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState /- It is not safe to use the `isDefEq` cache between different `isDefEq` calls. Reason: different configuration settings, and result depends on the state of the `MetavarContext` We have tried in the past to track when the result was independent of the `MetavarContext` state but it was not effective. It is more important to cache aggressively inside of a single `isDefEq` call because some of the heuristics create many similar subproblems. See issue #1102 for an example that triggers an exponential blowup if we don't use this more aggresive form of caching. -/ modifyDefEqCache fun _ => {} let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex /-- Determines whether two universe level expressions are definitionally equal to each other. -/ def isLevelDefEq (u v : Level) : MetaM Bool := checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v /-- See `isDefEq`. -/ def isExprDefEq (t s : Expr) : MetaM Bool := withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s /-- Determines whether two expressions are definitionally equal to each other. To control how metavariables are assigned and unified, metavariables and their context have a "depth". Given a metavariable `?m` and a `MetavarContext` `mctx`, `?m` is not assigned if `?m.depth != mctx.depth`. The combinator `withNewMCtxDepth x` will bump the depth while executing `x`. So, `withNewMCtxDepth (isDefEq a b)` is `isDefEq` without any mvar assignment happening whereas `isDefEq a b` will assign any metavariables of the current depth in `a` and `b` to unify them. By default, level metavariables can be assigned at any depth. That is, `withNewMCtxDepth (isDefEq a b)` will still assign level mvars in `a` and `b`. Setting the option `ignoreLevelMVarDepth := false` will disable this behavior. For matching (where only mvars in `b` should be assigned), we create the term inside the `withNewMCtxDepth`. For an example, see [Lean.Meta.Simp.tryTheoremWithExtraArgs?](https://github.com/leanprover/lean4/blob/master/src/Lean/Meta/Tactic/Simp/Rewrite.lean#L100-L106) -/ abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false /-- Similar to `isDefEq`, but returns `false` if an exception has been thrown. -/ abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s /-- Eta expand the given expression. Example: ``` etaExpand (mkConst ``Nat.add) ``` produces `fun x y => Nat.add x y` -/ def etaExpand (e : Expr) : MetaM Expr := withDefault do forallTelescopeReducing (← inferType e) fun xs _ => mkLambdaFVars xs (mkAppN e xs) end Meta builtin_initialize registerTraceClass `Meta.isLevelDefEq.postponed export Meta (MetaM) end Lean
8d2d00c695965229a05a11e7cfdc8018fb4aa68a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/suggest.lean
0b73339384f4009e4c11761dfec7a82c4d910954
[ "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
22,327
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 data.bool.basic import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- Map a name (typically a head symbol) to a "canonical" definitional synonym. Given a name `n`, we want a name `n'` such that a sufficiently applied expression with head symbol `n` is always definitionally equal to an expression with head symbol `n'`. Thus, we can search through all lemmas with a result type of `n'` to solve a goal with head symbol `n`. For example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`, and `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false` The default is that the original argument is returned, so `<` is just mapped to `<`. `normalize_synonym` is called for every lemma in the library, so it needs to be fast. -/ -- TODO this is a hack; if you suspect more cases here would help, please report them meta def normalize_synonym : name → name | `gt := `has_lt.lt | `ge := `has_le.le | `monotone := `has_le.le | `not := `false | n := n /-- Compute the head symbol of an expression, then normalise synonyms. This is only used when analysing the goal, so it is okay to do more expensive analysis here. -/ -- We may want to tweak this further? meta def allowed_head_symbols : expr → list name -- We first have a various "customisations": -- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`, -- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`. -- Note we only do this in the `ℕ` case, for performance. | `(@has_le.le ℕ _ (nat.succ _) _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ (nat.succ _)) := [`has_le.le, `has_lt.lt] | `(@has_le.le ℕ _ 1 _) := [`has_le.le, `has_lt.lt] | `(@ge ℕ _ _ 1) := [`has_le.le, `has_lt.lt] -- These allow `library_search` to search for lemmas of type `¬ a = b` when proving `a ≠ b` -- and vice-versa. | `(_ ≠ _) := [`false, `ne] | `(¬ _ = _) := [`ne, `false] -- And then the generic cases: | (expr.pi _ _ _ t) := allowed_head_symbols t | (expr.app f _) := allowed_head_symbols f | (expr.const n _) := [normalize_synonym n] | _ := [`_] . /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name_set) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if hs.contains `iff then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if hs.contains (normalize_synonym n) then some ex else none | _ := if hs.contains `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name_set) (d : declaration) : option decl_data := let n := d.to_name in if !d.is_trusted || n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name_set) : tactic (list decl_data) := do trace_if_enabled `suggest format!"Looking for lemmas with head symbols {hs}.", env ← get_env, let defs := env.decl_filter_map (process_declaration hs), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), return defs /-- We unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply in both directions into two separate elements. This ensures that both directions can be independently returned by `suggest`, and avoids a problem where the application of one direction prevents the application of the other direction. (See `exp_le_exp` in the tests.) -/ meta def unpack_iff_both : list decl_data → list decl_data | [] := [] | (⟨d, n, both, l⟩ :: L) := ⟨d, n, mp, l⟩ :: ⟨d, n, mpr, l⟩ :: unpack_iff_both L | (⟨d, n, m, l⟩ :: L) := ⟨d, n, m, l⟩ :: unpack_iff_both L /-- An extension to the option structure for `solve_by_elim`. * `compulsory_hyps` specifies a list of local hypotheses which must appear in any solution. These are useful for constraining the results from `library_search` and `suggest`. * `try_this` is a flag (default: `tt`) that controls whether a "Try this:"-line should be traced. -/ meta structure suggest_opt extends opt := (compulsory_hyps : list expr := []) (try_this : bool := tt) /-- Convert a `suggest_opt` structure to a `opt` structure suitable for `solve_by_elim`, by setting the `accept` parameter to require that all complete solutions use everything in `compulsory_hyps`. -/ meta def suggest_opt.mk_accept (o : suggest_opt) : opt := { accept := λ gs, o.accept gs >> (guard $ o.compulsory_hyps.all (λ h, gs.any (λ g, g.contains_expr_or_mvar h))), ..o } /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. Returns the number of subgoals which were closed using `solve_by_elim`. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on the independent goals, -- whether or not `close_goals` is set, -- and then run `solve_by_elim { all_goals := tt }`, -- requiring that it succeeds if `close_goals = tt`. meta def apply_and_solve (close_goals : bool) (opt : suggest_opt := { }) (e : expr) : tactic ℕ := do trace_if_enabled `suggest format!"Trying to apply lemma: {e}", apply e opt.to_apply_cfg, trace_if_enabled `suggest format!"Applied lemma: {e}", ng ← num_goals, -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. -- In Phase 2 we will do backtracking search across all goals, -- allowing us to guess solutions that involve data or unify metavariables, -- but only as long as we can finish all goals.) -- If `compulsory_hyps` is non-empty, we skip this phase and defer to phase 2. try (guard (opt.compulsory_hyps = []) >> any_goals (independent_goal >> solve_by_elim opt.to_opt)), -- Phase 2 (done >> return ng) <|> (do -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). ((guard (opt.compulsory_hyps ≠ []) <|> any_goals (success_if_fail independent_goal) >> skip) >> solve_by_elim { backtrack_all_goals := tt, ..opt.mk_accept }) <|> -- and fail unless `close_goals = ff` guard ¬ close_goals, ng' ← num_goals, return (ng - ng')) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the subgoal using `apply_and_solve`. Returns the number of subgoals successfully closed. -/ meta def apply_declaration (close_goals : bool) (opt : suggest_opt := { }) (d : decl_data) : tactic ℕ := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := undefined -- we use `unpack_iff_both` to ensure this isn't reachable end /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : list expr) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : suggest_opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, guard $ (opt.compulsory_hyps.all (λ h, h.occurs g)), ng ← num_goals, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.filter (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : suggest_opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Check if `solve_by_elim` can solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt.mk_accept, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, guard (opt.compulsory_hyps.all (λ h, h.occurs g)), return $ mllist.of_list [⟨s, m, none, 0, hyps.filter (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← unpack_iff_both <$> library_defs (name_set.of_list $ allowed_head_symbols t), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `Try this: refine ...` or `Try this: exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : suggest_opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : suggest_opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used.length ≥ d₂.hyps_used.length)) /-- Returns a list of at most `limit` strings, of the form `Try this: exact ...` or `Try this: refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : suggest_opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `Try this: exact ...`, which closes the current goal. -/ meta def library_search (opt : suggest_opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive setup_tactic_parser open solve_by_elim declare_trace silence_suggest -- Turn off `Try this: exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (use : parse $ (tk "using" *> many ident_) <|> return []) (opt : suggest_opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, use ← use.mmap get_local, L ← tactic.suggest_scripts (n.get_or_else 50) { compulsory_hyps := use, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, ..opt }, if !opt.try_this || is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. `suggest using h₁ h₂` will only show solutions that make use of the local hypotheses `h₁` and `h₂`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } -- Turn off `Try this: exact ...` trace message for `library_search` declare_trace silence_library_search /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact mul_tsub n m k ``` `library_search using h₁ h₂` will only show solutions that make use of the local hypotheses `h₁` and `h₂`. By default `library_search` only unfolds `reducible` definitions when attempting to match lemmas against the goal. Previously, it would unfold most definitions, sometimes giving surprising answers, or slow answers. The old behaviour is still available via `library_search!`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `library_search with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (semireducible : parse $ optional (tk "!")) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (use : parse $ (tk "using" *> many ident_) <|> return []) (opt : suggest_opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set ff hs attr_names, use ← use.mmap get_local, (tactic.library_search { compulsory_hyps := use, backtrack_all_goals := tt, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, md := if semireducible.is_some then tactic.transparency.semireducible else tactic.transparency.reducible, ..opt } >>= if !opt.try_this || is_trace_enabled_for `silence_library_search then (λ _, skip) else trace) <|> fail "`library_search` failed. If you aren't sure what to do next, you can also try `library_search!`, `suggest`, or `hint`. Possible reasons why `library_search` failed: * `library_search` will only apply a single lemma from the library, and then try to fill in its hypotheses from local hypotheses. * If you haven't already, try stating the theorem you want in its own lemma. * Sometimes the library has one version of a lemma but not a very similar version obtained by permuting arguments. Try replacing `a + b` with `b + a`, or `a - b < c` with `a < b + c`, to see if maybe the lemma exists but isn't stated quite the way you would like. * Make sure that you have all the side conditions for your theorem to be true. For example you won't find `a - b + b = a` for natural numbers in the library because it's false! Search for `b ≤ a → a - b + b = a` instead. * If a definition you made is in the goal, you won't find any theorems about it in the library. Try unfolding the definition using `unfold my_definition`. * If all else fails, ask on https://leanprover.zulipchat.com/, and maybe we can improve the library and/or `library_search` for next time." add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'Try this: exact ' prefix on this string? return [((script.get_rest "Try this: exact ").get_or_else script, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
a5cac38785e4e57636751cd5c279c70bb7354c5d
f57749ca63d6416f807b770f67559503fdb21001
/library/theories/group_theory/subgroup.lean
133ccb2fa1be92e12928d48cd5b9c0a6efa2b907
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,949
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import data algebra.group data open function eq.ops open set namespace algebra namespace coset -- semigroup coset definition section variable {A : Type} variable [s : semigroup A] include s definition lmul (a : A) := λ x, a * x definition rmul (a : A) := λ x, x * a definition l a (S : set A) := (lmul a) '[S] definition r a (S : set A) := (rmul a) '[S] lemma lmul_compose : ∀ (a b : A), (lmul a) ∘ (lmul b) = lmul (a*b) := take a, take b, funext (assume x, by rewrite [↑function.compose, ↑lmul, mul.assoc]) lemma rmul_compose : ∀ (a b : A), (rmul a) ∘ (rmul b) = rmul (b*a) := take a, take b, funext (assume x, by rewrite [↑function.compose, ↑rmul, mul.assoc]) lemma lcompose a b (S : set A) : l a (l b S) = l (a*b) S := calc (lmul a) '[(lmul b) '[S]] = ((lmul a) ∘ (lmul b)) '[S] : image_compose ... = lmul (a*b) '[S] : lmul_compose lemma rcompose a b (S : set A) : r a (r b S) = r (b*a) S := calc (rmul a) '[(rmul b) '[S]] = ((rmul a) ∘ (rmul b)) '[S] : image_compose ... = rmul (b*a) '[S] : rmul_compose lemma l_sub a (S H : set A) : S ⊆ H → (l a S) ⊆ (l a H) := image_subset (lmul a) definition l_same S (a b : A) := l a S = l b S definition r_same S (a b : A) := r a S = r b S lemma l_same.refl S (a : A) : l_same S a a := rfl lemma l_same.symm S (a b : A) : l_same S a b → l_same S b a := eq.symm lemma l_same.trans S (a b c : A) : l_same S a b → l_same S b c → l_same S a c := eq.trans example (S : set A) : equivalence (l_same S) := mk_equivalence (l_same S) (l_same.refl S) (l_same.symm S) (l_same.trans S) end end coset section variable {A : Type} variable [s : group A] include s definition lmul_by (a : A) := λ x, a * x definition rmul_by (a : A) := λ x, x * a definition glcoset a (H : set A) : set A := λ x, H (a⁻¹ * x) definition grcoset H (a : A) : set A := λ x, H (x * a⁻¹) end end algebra namespace group open algebra namespace ops infixr `∘>`:55 := glcoset -- stronger than = (50), weaker than * (70) infixl `<∘`:55 := grcoset infixr `∘c`:55 := conj_by end ops end group namespace algebra open group.ops section variable {A : Type} variable [s : group A] include s lemma conj_inj (g : A) : injective (conj_by g) := injective_of_has_left_inverse (exists.intro (conj_by g⁻¹) take a, !conj_inv_cancel) lemma lmul_inj (a : A) : injective (lmul_by a) := take x₁ x₂ Peq, by esimp [lmul_by] at Peq; rewrite [-(inv_mul_cancel_left a x₁), -(inv_mul_cancel_left a x₂), Peq] lemma lmul_inv_on (a : A) (H : set A) : left_inv_on (lmul_by a⁻¹) (lmul_by a) H := take x Px, show a⁻¹*(a*x) = x, by rewrite inv_mul_cancel_left lemma lmul_inj_on (a : A) (H : set A) : inj_on (lmul_by a) H := inj_on_of_left_inv_on (lmul_inv_on a H) lemma glcoset_eq_lcoset a (H : set A) : a ∘> H = coset.l a H := setext begin intro x, rewrite [↑glcoset, ↑coset.l, ↑image, ↑set_of, ↑mem, ↑coset.lmul], apply iff.intro, intro P1, apply (exists.intro (a⁻¹ * x)), apply and.intro, exact P1, exact (mul_inv_cancel_left a x), show (∃ (x_1 : A), H x_1 ∧ a * x_1 = x) → H (a⁻¹ * x), from assume P2, obtain x_1 P3, from P2, have P4 : a * x_1 = x, from and.right P3, have P5 : x_1 = a⁻¹ * x, from eq_inv_mul_of_mul_eq P4, eq.subst P5 (and.left P3) end lemma grcoset_eq_rcoset a (H : set A) : H <∘ a = coset.r a H := begin rewrite [↑grcoset, ↑coset.r, ↑image, ↑coset.rmul, ↑set_of], apply setext, rewrite ↑mem, intro x, apply iff.intro, show H (x * a⁻¹) → (∃ (x_1 : A), H x_1 ∧ x_1 * a = x), from assume PH, exists.intro (x * a⁻¹) (and.intro PH (inv_mul_cancel_right x a)), show (∃ (x_1 : A), H x_1 ∧ x_1 * a = x) → H (x * a⁻¹), from assume Pex, obtain x_1 Pand, from Pex, eq.subst (eq_mul_inv_of_mul_eq (and.right Pand)) (and.left Pand) end lemma glcoset_sub a (S H : set A) : S ⊆ H → (a ∘> S) ⊆ (a ∘> H) := assume Psub, assert P : _, from coset.l_sub a S H Psub, eq.symm (glcoset_eq_lcoset a S) ▸ eq.symm (glcoset_eq_lcoset a H) ▸ P lemma glcoset_compose (a b : A) (H : set A) : a ∘> b ∘> H = a*b ∘> H := begin rewrite [*glcoset_eq_lcoset], exact (coset.lcompose a b H) end lemma grcoset_compose (a b : A) (H : set A) : H <∘ a <∘ b = H <∘ a*b := begin rewrite [*grcoset_eq_rcoset], exact (coset.rcompose b a H) end lemma glcoset_id (H : set A) : 1 ∘> H = H := funext (assume x, calc (1 ∘> H) x = H (1⁻¹*x) : rfl ... = H (1*x) : {one_inv} ... = H x : {one_mul x}) lemma grcoset_id (H : set A) : H <∘ 1 = H := funext (assume x, calc H (x*1⁻¹) = H (x*1) : {one_inv} ... = H x : {mul_one x}) --lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := -- funext (assume x, -- calc glcoset a⁻¹ (glcoset a H) x = H x : {mul_inv_cancel_left a⁻¹ x}) lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := calc a⁻¹ ∘> a ∘> H = (a⁻¹*a) ∘> H : glcoset_compose ... = 1 ∘> H : mul.left_inv ... = H : glcoset_id lemma grcoset_inv H (a : A) : (H <∘ a) <∘ a⁻¹ = H := funext (assume x, calc grcoset (grcoset H a) a⁻¹ x = H x : {inv_mul_cancel_right x a⁻¹}) lemma glcoset_cancel a b (H : set A) : (b*a⁻¹) ∘> a ∘> H = b ∘> H := calc (b*a⁻¹) ∘> a ∘> H = b*a⁻¹*a ∘> H : glcoset_compose ... = b ∘> H : {inv_mul_cancel_right b a} lemma grcoset_cancel a b (H : set A) : H <∘ a <∘ a⁻¹*b = H <∘ b := calc H <∘ a <∘ a⁻¹*b = H <∘ a*(a⁻¹*b) : grcoset_compose ... = H <∘ b : {mul_inv_cancel_left a b} -- test how precedence breaks tie: infixr takes hold since its encountered first example a b (H : set A) : a ∘> H <∘ b = a ∘> (H <∘ b) := rfl -- should be true for semigroup as well but irrelevant lemma lcoset_rcoset_assoc a b (H : set A) : a ∘> H <∘ b = (a ∘> H) <∘ b := funext (assume x, begin esimp [glcoset, grcoset], rewrite mul.assoc end) definition mul_closed_on H := ∀ (x y : A), x ∈ H → y ∈ H → x * y ∈ H lemma closed_lcontract a (H : set A) : mul_closed_on H → a ∈ H → a ∘> H ⊆ H := begin rewrite [↑mul_closed_on, ↑glcoset, ↑subset, ↑mem], intro Pclosed, intro PHa, intro x, intro PHainvx, exact (eq.subst (mul_inv_cancel_left a x) (Pclosed a (a⁻¹*x) PHa PHainvx)) end lemma closed_rcontract a (H : set A) : mul_closed_on H → a ∈ H → H <∘ a ⊆ H := assume P1 : mul_closed_on H, assume P2 : H a, begin rewrite ↑subset, intro x, rewrite [↑grcoset, ↑mem], intro P3, exact (eq.subst (inv_mul_cancel_right x a) (P1 (x * a⁻¹) a P3 P2)) end lemma closed_lcontract_set a (H G : set A) : mul_closed_on G → H ⊆ G → a∈G → a∘>H ⊆ G := assume Pclosed, assume PHsubG, assume PainG, assert PaGsubG : a ∘> G ⊆ G, from closed_lcontract a G Pclosed PainG, assert PaHsubaG : a ∘> H ⊆ a ∘> G, from eq.symm (glcoset_eq_lcoset a H) ▸ eq.symm (glcoset_eq_lcoset a G) ▸ (coset.l_sub a H G PHsubG), subset.trans _ _ _ PaHsubaG PaGsubG definition subgroup.has_inv H := ∀ (a : A), a ∈ H → a⁻¹ ∈ H -- two ways to define the same equivalence relatiohship for subgroups definition in_lcoset [reducible] H (a b : A) := a ∈ b ∘> H definition in_rcoset [reducible] H (a b : A) := a ∈ H <∘ b definition same_lcoset [reducible] H (a b : A) := a ∘> H = b ∘> H definition same_rcoset [reducible] H (a b : A) := H <∘ a = H <∘ b definition same_left_right_coset (N : set A) := ∀ x, x ∘> N = N <∘ x structure is_subgroup [class] (H : set A) : Type := (has_one : H 1) (mul_closed : mul_closed_on H) (has_inv : subgroup.has_inv H) structure is_normal_subgroup [class] (N : set A) extends is_subgroup N := (normal : same_left_right_coset N) end section subgroup variable {A : Type} variable [s : group A] include s variable {H : set A} variable [is_subg : is_subgroup H] include is_subg lemma subg_has_one : H (1 : A) := @is_subgroup.has_one A s H is_subg lemma subg_mul_closed : mul_closed_on H := @is_subgroup.mul_closed A s H is_subg lemma subg_has_inv : subgroup.has_inv H := @is_subgroup.has_inv A s H is_subg lemma subgroup_coset_id : ∀ a, a ∈ H → (a ∘> H = H ∧ H <∘ a = H) := take a, assume PHa : H a, assert Pl : a ∘> H ⊆ H, from closed_lcontract a H subg_mul_closed PHa, assert Pr : H <∘ a ⊆ H, from closed_rcontract a H subg_mul_closed PHa, assert PHainv : H a⁻¹, from subg_has_inv a PHa, and.intro (setext (assume x, begin esimp [glcoset, mem], apply iff.intro, apply Pl, intro PHx, exact (subg_mul_closed a⁻¹ x PHainv PHx) end)) (setext (assume x, begin esimp [grcoset, mem], apply iff.intro, apply Pr, intro PHx, exact (subg_mul_closed x a⁻¹ PHx PHainv) end)) lemma subgroup_lcoset_id : ∀ a, a ∈ H → a ∘> H = H := take a, assume PHa : H a, and.left (subgroup_coset_id a PHa) lemma subgroup_rcoset_id : ∀ a, a ∈ H → H <∘ a = H := take a, assume PHa : H a, and.right (subgroup_coset_id a PHa) lemma subg_in_coset_refl (a : A) : a ∈ a ∘> H ∧ a ∈ H <∘ a := assert PH1 : H 1, from subg_has_one, assert PHinvaa : H (a⁻¹*a), from (eq.symm (mul.left_inv a)) ▸ PH1, assert PHainva : H (a*a⁻¹), from (eq.symm (mul.right_inv a)) ▸ PH1, and.intro PHinvaa PHainva lemma subg_in_lcoset_same_lcoset (a b : A) : in_lcoset H a b → same_lcoset H a b := assume Pa_in_b : H (b⁻¹*a), have Pbinva : b⁻¹*a ∘> H = H, from subgroup_lcoset_id (b⁻¹*a) Pa_in_b, have Pb_binva : b ∘> b⁻¹*a ∘> H = b ∘> H, from Pbinva ▸ rfl, have Pbbinva : b*(b⁻¹*a)∘>H = b∘>H, from glcoset_compose b (b⁻¹*a) H ▸ Pb_binva, mul_inv_cancel_left b a ▸ Pbbinva lemma subg_same_lcoset_in_lcoset (a b : A) : same_lcoset H a b → in_lcoset H a b := assume Psame : a∘>H = b∘>H, assert Pa : a ∈ a∘>H, from and.left (subg_in_coset_refl a), by exact (Psame ▸ Pa) lemma subg_lcoset_same (a b : A) : in_lcoset H a b = (a∘>H = b∘>H) := propext(iff.intro (subg_in_lcoset_same_lcoset a b) (subg_same_lcoset_in_lcoset a b)) lemma subg_rcoset_same (a b : A) : in_rcoset H a b = (H<∘a = H<∘b) := propext(iff.intro (assume Pa_in_b : H (a*b⁻¹), have Pabinv : H<∘a*b⁻¹ = H, from subgroup_rcoset_id (a*b⁻¹) Pa_in_b, have Pabinv_b : H <∘ a*b⁻¹ <∘ b = H <∘ b, from Pabinv ▸ rfl, have Pabinvb : H <∘ a*b⁻¹*b = H <∘ b, from grcoset_compose (a*b⁻¹) b H ▸ Pabinv_b, inv_mul_cancel_right a b ▸ Pabinvb) (assume Psame, assert Pa : a ∈ H<∘a, from and.right (subg_in_coset_refl a), by exact (Psame ▸ Pa))) lemma subg_same_lcoset.refl (a : A) : same_lcoset H a a := rfl lemma subg_same_rcoset.refl (a : A) : same_rcoset H a a := rfl lemma subg_same_lcoset.symm (a b : A) : same_lcoset H a b → same_lcoset H b a := eq.symm lemma subg_same_rcoset.symm (a b : A) : same_rcoset H a b → same_rcoset H b a := eq.symm lemma subg_same_lcoset.trans (a b c : A) : same_lcoset H a b → same_lcoset H b c → same_lcoset H a c := eq.trans lemma subg_same_rcoset.trans (a b c : A) : same_rcoset H a b → same_rcoset H b c → same_rcoset H a c := eq.trans variable {S : set A} lemma subg_lcoset_subset_subg (Psub : S ⊆ H) (a : A) : a ∈ H → a ∘> S ⊆ H := assume Pin, have P : a ∘> S ⊆ a ∘> H, from glcoset_sub a S H Psub, subgroup_lcoset_id a Pin ▸ P end subgroup section normal_subg open quot variable {A : Type} variable [s : group A] include s variable (N : set A) variable [is_nsubg : is_normal_subgroup N] include is_nsubg local notation a `~` b := same_lcoset N a b -- note : does not bind as strong as → lemma nsubg_normal : same_left_right_coset N := @is_normal_subgroup.normal A s N is_nsubg lemma nsubg_same_lcoset_product : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ((a1*a2) ~ (b1*b2)) := take a1, take a2, take b1, take b2, assume Psame1 : a1 ∘> N = b1 ∘> N, assume Psame2 : a2 ∘> N = b2 ∘> N, calc a1*a2 ∘> N = a1 ∘> a2 ∘> N : glcoset_compose ... = a1 ∘> b2 ∘> N : by rewrite Psame2 ... = a1 ∘> (N <∘ b2) : by rewrite (nsubg_normal N) ... = (a1 ∘> N) <∘ b2 : by rewrite lcoset_rcoset_assoc ... = (b1 ∘> N) <∘ b2 : by rewrite Psame1 ... = N <∘ b1 <∘ b2 : by rewrite (nsubg_normal N) ... = N <∘ (b1*b2) : by rewrite grcoset_compose ... = (b1*b2) ∘> N : by rewrite (nsubg_normal N) example (a b : A) : (a⁻¹ ~ b⁻¹) = (a⁻¹ ∘> N = b⁻¹ ∘> N) := rfl lemma nsubg_same_lcoset_inv : ∀ a b, (a ~ b) → (a⁻¹ ~ b⁻¹) := take a b, assume Psame : a ∘> N = b ∘> N, calc a⁻¹ ∘> N = a⁻¹*b*b⁻¹ ∘> N : by rewrite mul_inv_cancel_right ... = a⁻¹*b ∘> b⁻¹ ∘> N : by rewrite glcoset_compose ... = a⁻¹*b ∘> (N <∘ b⁻¹) : by rewrite nsubg_normal ... = (a⁻¹*b ∘> N) <∘ b⁻¹ : by rewrite lcoset_rcoset_assoc ... = (a⁻¹ ∘> b ∘> N) <∘ b⁻¹ : by rewrite glcoset_compose ... = (a⁻¹ ∘> a ∘> N) <∘ b⁻¹ : by rewrite Psame ... = N <∘ b⁻¹ : by rewrite glcoset_inv ... = b⁻¹ ∘> N : by rewrite nsubg_normal definition nsubg_setoid [instance] : setoid A := setoid.mk (same_lcoset N) (mk_equivalence (same_lcoset N) (subg_same_lcoset.refl) (subg_same_lcoset.symm) (subg_same_lcoset.trans)) definition coset_of : Type := quot (nsubg_setoid N) definition coset_inv_base (a : A) : coset_of N := ⟦a⁻¹⟧ definition coset_product (a b : A) : coset_of N := ⟦a*b⟧ lemma coset_product_well_defined : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ⟦a1*a2⟧ = ⟦b1*b2⟧ := take a1 a2 b1 b2, assume P1 P2, quot.sound (nsubg_same_lcoset_product N a1 a2 b1 b2 P1 P2) definition coset_mul (aN bN : coset_of N) : coset_of N := quot.lift_on₂ aN bN (coset_product N) (coset_product_well_defined N) lemma coset_inv_well_defined : ∀ a b, (a ~ b) → ⟦a⁻¹⟧ = ⟦b⁻¹⟧ := take a b, assume P, quot.sound (nsubg_same_lcoset_inv N a b P) definition coset_inv (aN : coset_of N) : coset_of N := quot.lift_on aN (coset_inv_base N) (coset_inv_well_defined N) definition coset_one : coset_of N := ⟦1⟧ local infixl `cx`:70 := coset_mul N example (a b c : A) : ⟦a⟧ cx ⟦b*c⟧ = ⟦a*(b*c)⟧ := rfl lemma coset_product_assoc (a b c : A) : ⟦a⟧ cx ⟦b⟧ cx ⟦c⟧ = ⟦a⟧ cx (⟦b⟧ cx ⟦c⟧) := calc ⟦a*b*c⟧ = ⟦a*(b*c)⟧ : {mul.assoc a b c} ... = ⟦a⟧ cx ⟦b*c⟧ : rfl lemma coset_product_left_id (a : A) : ⟦1⟧ cx ⟦a⟧ = ⟦a⟧ := calc ⟦1*a⟧ = ⟦a⟧ : {one_mul a} lemma coset_product_right_id (a : A) : ⟦a⟧ cx ⟦1⟧ = ⟦a⟧ := calc ⟦a*1⟧ = ⟦a⟧ : {mul_one a} lemma coset_product_left_inv (a : A) : ⟦a⁻¹⟧ cx ⟦a⟧ = ⟦1⟧ := calc ⟦a⁻¹*a⟧ = ⟦1⟧ : {mul.left_inv a} lemma coset_mul.assoc (aN bN cN : coset_of N) : aN cx bN cx cN = aN cx (bN cx cN) := quot.ind (λ a, quot.ind (λ b, quot.ind (λ c, coset_product_assoc N a b c) cN) bN) aN lemma coset_mul.one_mul (aN : coset_of N) : coset_one N cx aN = aN := quot.ind (coset_product_left_id N) aN lemma coset_mul.mul_one (aN : coset_of N) : aN cx (coset_one N) = aN := quot.ind (coset_product_right_id N) aN lemma coset_mul.left_inv (aN : coset_of N) : (coset_inv N aN) cx aN = (coset_one N) := quot.ind (coset_product_left_inv N) aN definition mk_quotient_group : group (coset_of N):= group.mk (coset_mul N) (coset_mul.assoc N) (coset_one N) (coset_mul.one_mul N) (coset_mul.mul_one N) (coset_inv N) (coset_mul.left_inv N) end normal_subg namespace group namespace quotient section open quot variable {A : Type} variable [s : group A] include s variable {N : set A} variable [is_nsubg : is_normal_subgroup N] include is_nsubg definition quotient_group [instance] : group (coset_of N) := mk_quotient_group N example (aN : coset_of N) : aN * aN⁻¹ = 1 := mul.right_inv aN definition natural (a : A) : coset_of N := ⟦a⟧ end end quotient end group end algebra
7e6411215c76f5ea901dd8f34f5e518b24a0a1d6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/is_prime_pow.lean
862dd75df97972b49a90a8001e0be51febcd2d92
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,135
lean
/- Copyright (c) 2022 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import algebra.associated import number_theory.divisors /-! # Prime powers This file deals with prime powers: numbers which are positive integer powers of a single prime. -/ variables {R : Type*} [comm_monoid_with_zero R] (n p : R) (k : ℕ) /-- `n` is a prime power if there is a prime `p` and a positive natural `k` such that `n` can be written as `p^k`. -/ def is_prime_pow : Prop := ∃ (p : R) (k : ℕ), prime p ∧ 0 < k ∧ p ^ k = n lemma is_prime_pow_def : is_prime_pow n ↔ ∃ (p : R) (k : ℕ), prime p ∧ 0 < k ∧ p ^ k = n := iff.rfl /-- An equivalent definition for prime powers: `n` is a prime power iff there is a prime `p` and a natural `k` such that `n` can be written as `p^(k+1)`. -/ lemma is_prime_pow_iff_pow_succ : is_prime_pow n ↔ ∃ (p : R) (k : ℕ), prime p ∧ p ^ (k + 1) = n := (is_prime_pow_def _).trans ⟨λ ⟨p, k, hp, hk, hn⟩, ⟨_, _, hp, by rwa [nat.sub_add_cancel hk]⟩, λ ⟨p, k, hp, hn⟩, ⟨_, _, hp, nat.succ_pos', hn⟩⟩ lemma not_is_prime_pow_zero [no_zero_divisors R] : ¬ is_prime_pow (0 : R) := begin simp only [is_prime_pow_def, not_exists, not_and', and_imp], intros x n hn hx, rw pow_eq_zero hx, simp, end lemma is_prime_pow.not_unit {n : R} (h : is_prime_pow n) : ¬is_unit n := let ⟨p, k, hp, hk, hn⟩ := h in hn ▸ (is_unit_pow_iff hk.ne').not.mpr hp.not_unit lemma is_unit.not_is_prime_pow {n : R} (h : is_unit n) : ¬is_prime_pow n := λ h', h'.not_unit h lemma not_is_prime_pow_one : ¬ is_prime_pow (1 : R) := is_unit_one.not_is_prime_pow lemma prime.is_prime_pow {p : R} (hp : prime p) : is_prime_pow p := ⟨p, 1, hp, zero_lt_one, by simp⟩ lemma is_prime_pow.pow {n : R} (hn : is_prime_pow n) {k : ℕ} (hk : k ≠ 0) : is_prime_pow (n ^ k) := let ⟨p, k', hp, hk', hn⟩ := hn in ⟨p, k * k', hp, mul_pos hk.bot_lt hk', by rw [pow_mul', hn]⟩ theorem is_prime_pow.ne_zero [no_zero_divisors R] {n : R} (h : is_prime_pow n) : n ≠ 0 := λ t, eq.rec not_is_prime_pow_zero t.symm h lemma is_prime_pow.ne_one {n : R} (h : is_prime_pow n) : n ≠ 1 := λ t, eq.rec not_is_prime_pow_one t.symm h section nat lemma is_prime_pow_nat_iff (n : ℕ) : is_prime_pow n ↔ ∃ (p k : ℕ), nat.prime p ∧ 0 < k ∧ p ^ k = n := by simp only [is_prime_pow_def, nat.prime_iff] lemma nat.prime.is_prime_pow {p : ℕ} (hp : p.prime) : is_prime_pow p := hp.prime.is_prime_pow lemma is_prime_pow_nat_iff_bounded (n : ℕ) : is_prime_pow n ↔ ∃ (p : ℕ), p ≤ n ∧ ∃ (k : ℕ), k ≤ n ∧ p.prime ∧ 0 < k ∧ p ^ k = n := begin rw is_prime_pow_nat_iff, refine iff.symm ⟨λ ⟨p, _, k, _, hp, hk, hn⟩, ⟨p, k, hp, hk, hn⟩, _⟩, rintro ⟨p, k, hp, hk, rfl⟩, refine ⟨p, _, k, (nat.lt_pow_self hp.one_lt _).le, hp, hk, rfl⟩, simpa using nat.pow_le_pow_of_le_right hp.pos hk, end instance {n : ℕ} : decidable (is_prime_pow n) := decidable_of_iff' _ (is_prime_pow_nat_iff_bounded n) lemma is_prime_pow.dvd {n m : ℕ} (hn : is_prime_pow n) (hm : m ∣ n) (hm₁ : m ≠ 1) : is_prime_pow m := begin rw is_prime_pow_nat_iff at hn ⊢, rcases hn with ⟨p, k, hp, hk, rfl⟩, obtain ⟨i, hik, rfl⟩ := (nat.dvd_prime_pow hp).1 hm, refine ⟨p, i, hp, _, rfl⟩, apply nat.pos_of_ne_zero, rintro rfl, simpa using hm₁, end lemma nat.disjoint_divisors_filter_prime_pow {a b : ℕ} (hab : a.coprime b) : disjoint (a.divisors.filter is_prime_pow) (b.divisors.filter is_prime_pow) := begin simp only [finset.disjoint_left, finset.mem_filter, and_imp, nat.mem_divisors, not_and], rintro n han ha hn hbn hb -, exact hn.ne_one (nat.eq_one_of_dvd_coprimes hab han hbn), end lemma is_prime_pow.two_le : ∀ {n : ℕ}, is_prime_pow n → 2 ≤ n | 0 h := (not_is_prime_pow_zero h).elim | 1 h := (not_is_prime_pow_one h).elim | (n+2) _ := le_add_self theorem is_prime_pow.pos {n : ℕ} (hn : is_prime_pow n) : 0 < n := pos_of_gt hn.two_le theorem is_prime_pow.one_lt {n : ℕ} (h : is_prime_pow n) : 1 < n := h.two_le end nat
5fe11522fdb3f86aa6a6f2588348ce071f2614b4
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/zmod/basic.lean
729ed89f853d4ad828660b56feea31797eafc315
[ "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
32,591
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.char_p.basic import ring_theory.ideal.operations import tactic.fin_cases /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat.modeq int /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ instance (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : (nat.mod_modeq _ _).mul_right _ ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : (nat.mod_modeq _ _).symm.mul_left _), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : (nat.mod_modeq _ _).mul_left _ ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : (nat.mod_modeq _ _).symm.add (nat.mod_modeq _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ instance (n : ℕ) : comm_ring (fin (n+1)) := { one_mul := fin.one_mul, mul_one := fin.mul_one, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_one, ..fin.add_comm_group n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 h := false.elim $ nat.not_lt_zero 0 h.1 | (n+1) _ := fin.fintype (n+1) @[simp] lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := (coe : fin (n + 1) → ℕ) lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, exact fin.is_lt a end lemma val_le {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val ≤ n := a.val_lt.le @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl @[simp] lemma val_one' : (1 : zmod 0).val = 1 := rfl @[simp] lemma val_neg' {n : zmod 0} : (-n).val = n.val := by simp [val] @[simp] lemma val_mul' {m n : zmod 0} : (m * n).val = m.val * n.val := by simp [val, int.nat_abs_mul] lemma val_nat_cast {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin casesI n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_nat_cast, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma nat_cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma nat_cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, nat_cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } variables {S : Type*} [has_zero S] [has_one S] [has_add S] [has_neg S] @[simp] lemma _root_.prod.fst_zmod_cast (a : zmod n) : (a : R × S).fst = a := by cases n; simp @[simp] lemma _root_.prod.snd_zmod_cast (a : zmod n) : (a : R × S).snd = a := by cases n; simp end /-- So-named because the coercion is `nat.cast` into `zmod`. For `nat.cast` into an arbitrary ring, see `zmod.nat_cast_val`. -/ lemma nat_cast_zmod_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, { apply fin.coe_coe_eq_self } end lemma nat_cast_right_inverse [fact (0 < n)] : function.right_inverse val (coe : ℕ → zmod n) := nat_cast_zmod_val lemma nat_cast_zmod_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := nat_cast_right_inverse.surjective /-- So-named because the outer coercion is `int.cast` into `zmod`. For `int.cast` into an arbitrary ring, see `zmod.int_cast_cast`. -/ lemma int_cast_zmod_cast (a : zmod n) : ((a : ℤ) : zmod n) = a := begin cases n, { rw [int.cast_id a, int.cast_id a], }, { rw [coe_coe, int.nat_cast_eq_coe_nat, int.cast_coe_nat, fin.coe_coe_eq_self] } end lemma int_cast_right_inverse : function.right_inverse (coe : zmod n → ℤ) (coe : ℤ → zmod n) := int_cast_zmod_cast lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := int_cast_right_inverse.surjective @[norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := nat_cast_zmod_val i @[simp] lemma cast_id' : (coe : zmod n → zmod n) = id := funext (cast_id n) variables (R) [ring R] /-- The coercions are respectively `nat.cast` and `zmod.cast`. -/ @[simp] lemma nat_cast_comp_val [fact (0 < n)] : (coe : ℕ → R) ∘ (val : zmod n → ℕ) = coe := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, refl end /-- The coercions are respectively `int.cast`, `zmod.cast`, and `zmod.cast`. -/ @[simp] lemma int_cast_comp_cast : (coe : ℤ → R) ∘ (coe : zmod n → ℤ) = coe := begin cases n, { exact congr_arg ((∘) int.cast) zmod.cast_id', }, { ext, simp } end variables {R} @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := congr_fun (nat_cast_comp_val R) i @[simp] lemma int_cast_cast (i : zmod n) : ((i : ℤ) : R) = i := congr_fun (int_cast_comp_cast R) i lemma coe_add_eq_ite {n : ℕ} (a b : zmod n) : (↑(a + b) : ℤ) = if (n : ℤ) ≤ a + b then a + b - n else a + b := begin cases n, { simp }, simp only [coe_coe, fin.coe_add_eq_ite, int.nat_cast_eq_coe_nat, ← int.coe_nat_add, ← int.coe_nat_succ, int.coe_nat_le], split_ifs with h, { exact int.coe_nat_sub h }, { refl } end section char_dvd /-! If the characteristic of `R` divides `n`, then `cast` is a homomorphism. -/ variables {n} {m : ℕ} [char_p R m] @[simp] lemma cast_one (h : m ∣ n) : ((1 : zmod n) : R) = 1 := begin casesI n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { rw [nat.dvd_one] at h, substI m, apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end lemma cast_add (h : m ∣ n) (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin casesI n, { apply int.cast_add }, simp only [coe_coe], symmetry, erw [fin.coe_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ _ m], exact h.trans (nat.dvd_sub_mod _), end lemma cast_mul (h : m ∣ n) (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin casesI n, { apply int.cast_mul }, simp only [coe_coe], symmetry, erw [fin.coe_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub (nat.mod_le _ _), @char_p.cast_eq_zero_iff R _ _ m], exact h.trans (nat.dvd_sub_mod _), end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. See also `zmod.lift` (in `data.zmod.quotient`) for a generalized version working in `add_group`s. -/ def cast_hom (h : m ∣ n) (R : Type*) [ring R] [char_p R m] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one h, map_add' := cast_add h, map_mul' := cast_mul h } @[simp] lemma cast_hom_apply {h : m ∣ n} (i : zmod n) : cast_hom h R i = i := rfl @[simp, norm_cast] lemma cast_sub (h : m ∣ n) (a b : zmod n) : ((a - b : zmod n) : R) = a - b := (cast_hom h R).map_sub a b @[simp, norm_cast] lemma cast_neg (h : m ∣ n) (a : zmod n) : ((-a : zmod n) : R) = -a := (cast_hom h R).map_neg a @[simp, norm_cast] lemma cast_pow (h : m ∣ n) (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := (cast_hom h R).map_pow a k @[simp, norm_cast] lemma cast_nat_cast (h : m ∣ n) (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom h R).map_nat_cast k @[simp, norm_cast] lemma cast_int_cast (h : m ∣ n) (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom h R).map_int_cast k end char_dvd section char_eq /-! Some specialised simp lemmas which apply when `R` has characteristic `n`. -/ variable [char_p R n] @[simp] lemma cast_one' : ((1 : zmod n) : R) = 1 := cast_one dvd_rfl @[simp] lemma cast_add' (a b : zmod n) : ((a + b : zmod n) : R) = a + b := cast_add dvd_rfl a b @[simp] lemma cast_mul' (a b : zmod n) : ((a * b : zmod n) : R) = a * b := cast_mul dvd_rfl a b @[simp] lemma cast_sub' (a b : zmod n) : ((a - b : zmod n) : R) = a - b := cast_sub dvd_rfl a b @[simp] lemma cast_pow' (a : zmod n) (k : ℕ) : ((a ^ k : zmod n) : R) = a ^ k := cast_pow dvd_rfl a k @[simp, norm_cast] lemma cast_nat_cast' (k : ℕ) : ((k : zmod n) : R) = k := cast_nat_cast dvd_rfl k @[simp, norm_cast] lemma cast_int_cast' (k : ℤ) : ((k : zmod n) : R) = k := cast_int_cast dvd_rfl k variables (R) lemma cast_hom_injective : function.injective (zmod.cast_hom (dvd_refl n) R) := begin rw ring_hom.injective_iff, intro x, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective x, rw [ring_hom.map_int_cast, char_p.int_cast_eq_zero_iff R n, char_p.int_cast_eq_zero_iff (zmod n) n], exact id end lemma cast_hom_bijective [fintype R] (h : fintype.card R = n) : function.bijective (zmod.cast_hom (dvd_refl n) R) := begin haveI : fact (0 < n) := ⟨begin rw [pos_iff_ne_zero], intro hn, rw hn at h, exact (fintype.card_eq_zero_iff.mp h).elim' 0 end⟩, rw [fintype.bijective_iff_injective_and_card, zmod.card, h, eq_self_iff_true, and_true], apply zmod.cast_hom_injective end /-- The unique ring isomorphism between `zmod n` and a ring `R` of characteristic `n` and cardinality `n`. -/ noncomputable def ring_equiv [fintype R] (h : fintype.card R = n) : zmod n ≃+* R := ring_equiv.of_bijective _ (zmod.cast_hom_bijective R h) end char_eq end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma int_coe_eq_int_coe_iff' (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a % c = b % c := zmod.int_coe_eq_int_coe_iff a b c lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq_iff_dvd, int.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq_zero_iff_dvd], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq_zero_iff_dvd], end @[push_cast, simp] lemma int_cast_mod (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.mod_modeq, end lemma ker_int_cast_add_hom (n : ℕ) : (int.cast_add_hom (zmod n)).ker = add_subgroup.gmultiples n := by { ext, rw [int.mem_gmultiples_iff, add_monoid_hom.mem_ker, int.coe_cast_add_hom, int_coe_zmod_eq_zero_iff_dvd] } lemma ker_int_cast_ring_hom (n : ℕ) : (int.cast_ring_hom (zmod n)).ker = ideal.span ({n} : set ℤ) := by { ext, rw [ideal.mem_span_singleton, ring_hom.mem_ker, int.coe_cast_ring_hom, int_coe_zmod_eq_zero_iff_dvd] } local attribute [semireducible] int.nonneg @[simp] lemma nat_cast_to_nat (p : ℕ) : ∀ {z : ℤ} (h : 0 ≤ z), (z.to_nat : zmod p) = z | (n : ℕ) h := by simp only [int.cast_coe_nat, int.to_nat_coe_nat] | -[1+n] h := false.elim h lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_nat_cast] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt (fact.out _) } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out _) }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nontrivial (n : ℕ) [fact (1 < n)] : nontrivial (zmod n) := ⟨⟨0, 1, assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n ⟩⟩ /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [nat_cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw nat_cast_zmod_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma nat_cast_mod (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_nat_cast, ← val_nat_cast], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_nat_cast, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma coe_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; simp }, apply nat.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← nat_cast_zmod_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, nat_cast_mod], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (nat_cast_zmod_val _), right_inv := λ ⟨_, _⟩, by simp } /-- The **Chinese remainder theorem**. For a pair of coprime natural numbers, `m` and `n`, the rings `zmod (m * n)` and `zmod m × zmod n` are isomorphic. See `ideal.quotient_inf_ring_equiv_pi_quotient` for the Chinese remainder theorem for ideals in any ring. -/ def chinese_remainder {m n : ℕ} (h : m.coprime n) : zmod (m * n) ≃+* zmod m × zmod n := let to_fun : zmod (m * n) → zmod m × zmod n := zmod.cast_hom (show m.lcm n ∣ m * n, by simp [nat.lcm_dvd_iff]) (zmod m × zmod n) in let inv_fun : zmod m × zmod n → zmod (m * n) := λ x, if m * n = 0 then if m = 1 then ring_hom.snd _ _ x else ring_hom.fst _ _ x else nat.chinese_remainder h x.1.val x.2.val in have inv : function.left_inverse inv_fun to_fun ∧ function.right_inverse inv_fun to_fun := if hmn0 : m * n = 0 then begin rcases h.eq_of_mul_eq_zero hmn0 with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩; simp [inv_fun, to_fun, function.left_inverse, function.right_inverse, ring_hom.eq_int_cast, prod.ext_iff] end else begin haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩, haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩, haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩, have left_inv : function.left_inverse inv_fun to_fun, { intro x, dsimp only [dvd_mul_left, dvd_mul_right, zmod.cast_hom_apply, coe_coe, inv_fun, to_fun], conv_rhs { rw ← zmod.nat_cast_zmod_val x }, rw [if_neg hmn0, zmod.eq_iff_modeq_nat, ← nat.modeq_and_modeq_iff_modeq_mul h, prod.fst_zmod_cast, prod.snd_zmod_cast], refine ⟨(nat.chinese_remainder h (x : zmod m).val (x : zmod n).val).2.left.trans _, (nat.chinese_remainder h (x : zmod m).val (x : zmod n).val).2.right.trans _⟩, { rw [← zmod.eq_iff_modeq_nat, zmod.nat_cast_zmod_val, zmod.nat_cast_val] }, { rw [← zmod.eq_iff_modeq_nat, zmod.nat_cast_zmod_val, zmod.nat_cast_val] } }, exact ⟨left_inv, fintype.right_inverse_of_left_inverse_of_card_le left_inv (by simp)⟩, end, { to_fun := to_fun, inv_fun := inv_fun, map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _, left_inv := inv.1, right_inv := inv.2 } instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin ext1, cases x with x xi hx1 hx2, cases y with y yi hy1 hy2, revert hx1 hx2 hy1 hy2, fin_cases x; fin_cases y; simp end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := ⟨by { apply (nat.eq_zero_or_pos n).resolve_left, unfreezingI { rintro rfl }, simpa [fact_iff] using hn, }⟩, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos.1).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos.1]}, rw [← nat.two_mul_odd_div_two hn.1, two_mul, ← nat.succ_add, add_tsub_cancel_right], }, have hxn : (n : ℕ) - x.val < n, { rw [tsub_lt_iff_tsub_lt x.val_le le_rfl, tsub_self], rw ← zmod.nat_cast_zmod_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.nat_cast_self, ← sub_eq_add_neg, ← zmod.nat_cast_zmod_val x, ← nat.cast_sub x.val_le, zmod.val_nat_cast, nat.mod_eq_of_lt hxn, tsub_le_tsub_iff_left x.val_le] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two (a : zmod 2) : -a = a := by fin_cases a; ext; simp [fin.coe_neg, int.nat_mod]; norm_num @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_nat_cast, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.add_right_cancel' _ (by rw [nat.modeq, ←val_add, add_left_neg, tsub_add_cancel_of_le a.val_le, nat.mod_self, val_zero]) lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, tsub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt (fact.out (0 < n)), contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin casesI n, { exfalso, exact nat.not_lt_zero 0 (fact.out (0 < 0)) }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, nat_cast_zmod_val] }, { rw [int.cast_sub, int.cast_coe_nat, nat_cast_zmod_val, int.cast_coe_nat, nat_cast_self, sub_zero] } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact x.val_le, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring_nf, ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma nat_cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact a.val_le, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, nat_cast_zmod_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, nat_cast_self, sub_zero, nat_cast_zmod_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub a.val_le], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [tsub_le_iff_tsub_le, two_mul, ← add_assoc, add_tsub_cancel_right, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.nat_cast_zmod_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq_zero_iff_dvd, ← hp.1.coprime_iff_not_dvd, nat.coprime_primes hp.1 hq.1] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_zmod_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd (fact.out p.prime), ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.has_inv p, .. zmod.nontrivial p } /-- `zmod p` is an integral domain when `p` is prime. -/ instance (p : ℕ) [hp : fact p.prime] : is_domain (zmod p) := begin -- We need `cases p` here in order to resolve which `comm_ring` instance is being used. unfreezingI { cases p, { exfalso, rcases hp with ⟨⟨⟨⟩⟩⟩, }, }, exact @field.is_domain (zmod _) (zmod.field _) end end zmod lemma ring_hom.ext_zmod {n : ℕ} {R : Type*} [semiring R] (f g : (zmod n) →+* R) : f = g := begin ext a, obtain ⟨k, rfl⟩ := zmod.int_cast_surjective a, let φ : ℤ →+* R := f.comp (int.cast_ring_hom (zmod n)), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom (zmod n)), show φ k = ψ k, rw φ.ext_int ψ, end namespace zmod variables {n : ℕ} {R : Type*} instance subsingleton_ring_hom [semiring R] : subsingleton ((zmod n) →+* R) := ⟨ring_hom.ext_zmod⟩ instance subsingleton_ring_equiv [semiring R] : subsingleton (zmod n ≃+* R) := ⟨λ f g, by { rw ring_equiv.coe_ring_hom_inj_iff, apply ring_hom.ext_zmod _ _ }⟩ @[simp] lemma ring_hom_map_cast [ring R] (f : R →+* (zmod n)) (k : zmod n) : f k = k := by { cases n; simp } lemma ring_hom_right_inverse [ring R] (f : R →+* (zmod n)) : function.right_inverse (coe : zmod n → R) f := ring_hom_map_cast f lemma ring_hom_surjective [ring R] (f : R →+* (zmod n)) : function.surjective f := (ring_hom_right_inverse f).surjective lemma ring_hom_eq_of_ker_eq [comm_ring R] (f g : R →+* (zmod n)) (h : f.ker = g.ker) : f = g := begin have := f.lift_of_right_inverse_comp _ (zmod.ring_hom_right_inverse f) ⟨g, le_of_eq h⟩, rw subtype.coe_mk at this, rw [←this, ring_hom.ext_zmod (f.lift_of_right_inverse _ _ _) (ring_hom.id _), ring_hom.id_comp], end section lift variables (n) {A : Type*} [add_group A] /-- The map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. -/ @[simps] def lift : {f : ℤ →+ A // f n = 0} ≃ (zmod n →+ A) := (equiv.subtype_equiv_right $ begin intro f, rw ker_int_cast_add_hom, split, { rintro hf _ ⟨x, rfl⟩, simp only [f.map_gsmul, gsmul_zero, f.mem_ker, hf] }, { intro h, refine h (add_subgroup.mem_gmultiples _) } end).trans $ ((int.cast_add_hom (zmod n)).lift_of_right_inverse coe int_cast_zmod_cast) variables (f : {f : ℤ →+ A // f n = 0}) @[simp] lemma lift_coe (x : ℤ) : lift n f (x : zmod n) = f x := add_monoid_hom.lift_of_right_inverse_comp_apply _ _ _ _ _ lemma lift_cast_add_hom (x : ℤ) : lift n f (int.cast_add_hom (zmod n) x) = f x := add_monoid_hom.lift_of_right_inverse_comp_apply _ _ _ _ _ @[simp] lemma lift_comp_coe : zmod.lift n f ∘ coe = f := funext $ lift_coe _ _ @[simp] lemma lift_comp_cast_add_hom : (zmod.lift n f).comp (int.cast_add_hom (zmod n)) = f := add_monoid_hom.ext $ lift_cast_add_hom _ _ end lift end zmod
9a6bb2ec770e85d06bda7bfac485a58da7c6cd38
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/covariant_and_contravariant.lean
c327e664b7e187cd77ad213acc31760fd4d2aa9b
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,043
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group.defs /-! # Covariants and contravariants This file contains general lemmas and instances to work with the interactions between a relation and an action on a Type. The intended application is the splitting of the ordering from the algebraic assumptions on the operations in the `ordered_[...]` hierarchy. The strategy is to introduce two more flexible typeclasses, `covariant_class` and `contravariant_class`: * `covariant_class` models the implication `a ≤ b → c * a ≤ c * b` (multiplication is monotone), * `contravariant_class` models the implication `a * b < a * c → b < c`. Since `co(ntra)variant_class` takes as input the operation (typically `(+)` or `(*)`) and the order relation (typically `(≤)` or `(<)`), these are the only two typeclasses that I have used. The general approach is to formulate the lemma that you are interested in and prove it, with the `ordered_[...]` typeclass of your liking. After that, you convert the single typeclass, say `[ordered_cancel_monoid M]`, into three typeclasses, e.g. `[left_cancel_semigroup M] [partial_order M] [covariant_class M M (function.swap (*)) (≤)]` and have a go at seeing if the proof still works! Note that it is possible to combine several co(ntra)variant_class assumptions together. Indeed, the usual ordered typeclasses arise from assuming the pair `[covariant_class M M (*) (≤)] [contravariant_class M M (*) (<)]` on top of order/algebraic assumptions. A formal remark is that normally `covariant_class` uses the `(≤)`-relation, while `contravariant_class` uses the `(<)`-relation. This need not be the case in general, but seems to be the most common usage. In the opposite direction, the implication ```lean [semigroup α] [partial_order α] [contravariant_class α α (*) (≤)] => left_cancel_semigroup α ``` holds -- note the `co*ntra*` assumption on the `(≤)`-relation. # Formalization notes We stick to the convention of using `function.swap (*)` (or `function.swap (+)`), for the typeclass assumptions, since `function.swap` is slightly better behaved than `flip`. However, sometimes as a **non-typeclass** assumption, we prefer `flip (*)` (or `flip (+)`), as it is easier to use. -/ -- TODO: convert `has_exists_mul_of_le`, `has_exists_add_of_le`? -- TODO: relationship with `con/add_con` -- TODO: include equivalence of `left_cancel_semigroup` with -- `semigroup partial_order contravariant_class α α (*) (≤)`? -- TODO : use ⇒, as per Eric's suggestion? See -- https://leanprover.zulipchat.com/#narrow/stream/116395-maths/topic/ordered.20stuff/near/236148738 -- for a discussion. section variants variables {M N : Type*} (μ : M → N → N) (r : N → N → Prop) variables (M N) /-- `covariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `covariant_class` doc-string for its meaning. -/ def covariant : Prop := ∀ (m) {n₁ n₂}, r n₁ n₂ → r (μ m n₁) (μ m n₂) /-- `contravariant` is useful to formulate succintly statements about the interactions between an action of a Type on another one and a relation on the acted-upon Type. See the `contravariant_class` doc-string for its meaning. -/ def contravariant : Prop := ∀ (m) {n₁ n₂}, r (μ m n₁) (μ m n₂) → r n₁ n₂ /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `covariant_class` says that "the action `μ` preserves the relation `r`. More precisely, the `covariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N`. Its unique field `elim` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(n₁, n₂)`, then, the relation `r` also holds for the pair `(μ m n₁, μ m n₂)`, obtained from `(n₁, n₂)` by "acting upon it by `m`". If `m : M` and `h : r n₁ n₂`, then `covariant_class.elim m h : r (μ m n₁) (μ m n₂)`. -/ @[protect_proj] class covariant_class : Prop := (elim : covariant M N μ r) /-- Given an action `μ` of a Type `M` on a Type `N` and a relation `r` on `N`, informally, the `contravariant_class` says that "if the result of the action `μ` on a pair satisfies the relation `r`, then the initial pair satisfied the relation `r`. More precisely, the `contravariant_class` is a class taking two Types `M N`, together with an "action" `μ : M → N → N` and a relation `r : N → N`. Its unique field `elim` is the assertion that for all `m ∈ M` and all elements `n₁, n₂ ∈ N`, if the relation `r` holds for the pair `(μ m n₁, μ m n₂)` obtained from `(n₁, n₂)` by "acting upon it by `m`"", then, the relation `r` also holds for the pair `(n₁, n₂)`. If `m : M` and `h : r (μ m n₁) (μ m n₂)`, then `contravariant_class.elim m h : r n₁ n₂`. -/ @[protect_proj] class contravariant_class : Prop := (elim : contravariant M N μ r) lemma rel_iff_cov [covariant_class M N μ r] [contravariant_class M N μ r] (m : M) {a b : N} : r (μ m a) (μ m b) ↔ r a b := ⟨contravariant_class.elim _, covariant_class.elim _⟩ section flip variables {M N μ r} lemma covariant.flip (h : covariant M N μ r) : covariant M N μ (flip r) := λ a b c hbc, h a hbc lemma contravariant.flip (h : contravariant M N μ r) : contravariant M N μ (flip r) := λ a b c hbc, h a hbc end flip section covariant variables {M N μ r} [covariant_class M N μ r] lemma act_rel_act_of_rel (m : M) {a b : N} (ab : r a b) : r (μ m a) (μ m b) := covariant_class.elim _ ab @[to_additive] lemma group.covariant_iff_contravariant [group N] : covariant N N (*) r ↔ contravariant N N (*) r := begin refine ⟨λ h a b c bc, _, λ h a b c bc, _⟩, { rw [← inv_mul_cancel_left a b, ← inv_mul_cancel_left a c], exact h a⁻¹ bc }, { rw [← inv_mul_cancel_left a b, ← inv_mul_cancel_left a c] at bc, exact h a⁻¹ bc } end @[to_additive] lemma group.covconv [group N] [covariant_class N N (*) r] : contravariant_class N N (*) r := ⟨group.covariant_iff_contravariant.mp covariant_class.elim⟩ section is_trans variables [is_trans N r] (m n : M) {a b c d : N} /- Lemmas with 3 elements. -/ lemma act_rel_of_rel_of_act_rel (ab : r a b) (rl : r (μ m b) c) : r (μ m a) c := trans (act_rel_act_of_rel m ab) rl lemma rel_act_of_rel_of_rel_act (ab : r a b) (rr : r c (μ m a)) : r c (μ m b) := trans rr (act_rel_act_of_rel _ ab) end is_trans end covariant /- Lemma with 4 elements. -/ section M_eq_N variables {M N μ r} {mu : N → N → N} [is_trans N r] [covariant_class N N mu r] [covariant_class N N (function.swap mu) r] {a b c d : N} lemma act_rel_act_of_rel_of_rel (ab : r a b) (cd : r c d) : r (mu a c) (mu b d) := trans (act_rel_act_of_rel c ab : _) (act_rel_act_of_rel b cd) end M_eq_N section contravariant variables {M N μ r} [contravariant_class M N μ r] lemma rel_of_act_rel_act (m : M) {a b : N} (ab : r (μ m a) (μ m b)) : r a b := contravariant_class.elim _ ab section is_trans variables [is_trans N r] (m n : M) {a b c d : N} /- Lemmas with 3 elements. -/ lemma act_rel_of_act_rel_of_rel_act_rel (ab : r (μ m a) b) (rl : r (μ m b) (μ m c)) : r (μ m a) c := trans ab (rel_of_act_rel_act m rl) lemma rel_act_of_act_rel_act_of_rel_act (ab : r (μ m a) (μ m b)) (rr : r b (μ m c)) : r a (μ m c) := trans (rel_of_act_rel_act m ab) rr end is_trans end contravariant lemma covariant_le_of_covariant_lt [partial_order N] : covariant M N μ (<) → covariant M N μ (≤) := begin refine λ h a b c bc, _, rcases le_iff_eq_or_lt.mp bc with rfl | bc, { exact rfl.le }, { exact (h _ bc).le } end lemma contravariant_lt_of_contravariant_le [partial_order N] : contravariant M N μ (≤) → contravariant M N μ (<) := begin refine λ h a b c bc, lt_iff_le_and_ne.mpr ⟨h a bc.le, _⟩, rintro rfl, exact lt_irrefl _ bc, end lemma covariant_le_iff_contravariant_lt [linear_order N] : covariant M N μ (≤) ↔ contravariant M N μ (<) := ⟨ λ h a b c bc, not_le.mp (λ k, not_le.mpr bc (h _ k)), λ h a b c bc, not_lt.mp (λ k, not_lt.mpr bc (h _ k))⟩ lemma covariant_lt_iff_contravariant_le [linear_order N] : covariant M N μ (<) ↔ contravariant M N μ (≤) := ⟨ λ h a b c bc, not_lt.mp (λ k, not_lt.mpr bc (h _ k)), λ h a b c bc, not_le.mp (λ k, not_le.mpr bc (h _ k))⟩ @[to_additive] lemma covariant_flip_mul_iff [comm_semigroup N] : covariant N N (flip (*)) (r) ↔ covariant N N (*) (r) := by rw is_symm_op.flip_eq @[to_additive] lemma contravariant_flip_mul_iff [comm_semigroup N] : contravariant N N (flip (*)) (r) ↔ contravariant N N (*) (r) := by rw is_symm_op.flip_eq @[to_additive] instance contravariant_mul_lt_of_covariant_mul_le [has_mul N] [linear_order N] [covariant_class N N (*) (≤)] : contravariant_class N N (*) (<) := { elim := (covariant_le_iff_contravariant_lt N N (*)).mp covariant_class.elim } @[to_additive] instance covariant_mul_lt_of_contravariant_mul_le [has_mul N] [linear_order N] [contravariant_class N N (*) (≤)] : covariant_class N N (*) (<) := { elim := (covariant_lt_iff_contravariant_le N N (*)).mpr contravariant_class.elim } @[to_additive] instance covariant_swap_mul_le_of_covariant_mul_le [comm_semigroup N] [has_le N] [covariant_class N N (*) (≤)] : covariant_class N N (function.swap (*)) (≤) := { elim := (covariant_flip_mul_iff N (≤)).mpr covariant_class.elim } @[to_additive] instance contravariant_swap_mul_le_of_contravariant_mul_le [comm_semigroup N] [has_le N] [contravariant_class N N (*) (≤)] : contravariant_class N N (function.swap (*)) (≤) := { elim := (contravariant_flip_mul_iff N (≤)).mpr contravariant_class.elim } @[to_additive] instance contravariant_swap_mul_lt_of_contravariant_mul_lt [comm_semigroup N] [has_lt N] [contravariant_class N N (*) (<)] : contravariant_class N N (function.swap (*)) (<) := { elim := (contravariant_flip_mul_iff N (<)).mpr contravariant_class.elim } @[to_additive] instance covariant_swap_mul_lt_of_covariant_mul_lt [comm_semigroup N] [has_lt N] [covariant_class N N (*) (<)] : covariant_class N N (function.swap (*)) (<) := { elim := (covariant_flip_mul_iff N (<)).mpr covariant_class.elim } @[to_additive] instance left_cancel_semigroup.covariant_mul_lt_of_covariant_mul_le [left_cancel_semigroup N] [partial_order N] [covariant_class N N (*) (≤)] : covariant_class N N (*) (<) := { elim := λ a b c bc, by { cases lt_iff_le_and_ne.mp bc with bc cb, exact lt_iff_le_and_ne.mpr ⟨covariant_class.elim a bc, (mul_ne_mul_right a).mpr cb⟩ } } @[to_additive] instance right_cancel_semigroup.covariant_swap_mul_lt_of_covariant_swap_mul_le [right_cancel_semigroup N] [partial_order N] [covariant_class N N (function.swap (*)) (≤)] : covariant_class N N (function.swap (*)) (<) := { elim := λ a b c bc, by { cases lt_iff_le_and_ne.mp bc with bc cb, exact lt_iff_le_and_ne.mpr ⟨covariant_class.elim a bc, (mul_ne_mul_left a).mpr cb⟩ } } @[to_additive] instance left_cancel_semigroup.contravariant_mul_le_of_contravariant_mul_lt [left_cancel_semigroup N] [partial_order N] [contravariant_class N N (*) (<)] : contravariant_class N N (*) (≤) := { elim := λ a b c bc, by { cases le_iff_eq_or_lt.mp bc with h h, { exact ((mul_right_inj a).mp h).le }, { exact (contravariant_class.elim _ h).le } } } @[to_additive] instance right_cancel_semigroup.contravariant_swap_mul_le_of_contravariant_swap_mul_lt [right_cancel_semigroup N] [partial_order N] [contravariant_class N N (function.swap (*)) (<)] : contravariant_class N N (function.swap (*)) (≤) := { elim := λ a b c bc, by { cases le_iff_eq_or_lt.mp bc with h h, { exact ((mul_left_inj a).mp h).le }, { exact (contravariant_class.elim _ h).le } } } end variants
3cc72afd24efcf9cc0764396cf6723d6ccc7b65b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/real/enat_ennreal.lean
34c1e850517162dfe5a3cd2e20e5cf3361624ac0
[ "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
2,741
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.enat.basic import data.real.ennreal /-! # Coercion from `ℕ∞` to `ℝ≥0∞` In this file we define a coercion from `ℕ∞` to `ℝ≥0∞` and prove some basic lemmas about this map. -/ open_locale classical nnreal ennreal noncomputable theory namespace enat variables {m n : ℕ∞} instance has_coe_ennreal : has_coe_t ℕ∞ ℝ≥0∞ := ⟨with_top.map coe⟩ @[simp] lemma map_coe_nnreal : with_top.map (coe : ℕ → ℝ≥0) = (coe : ℕ∞ → ℝ≥0∞) := rfl /-- Coercion `ℕ∞ → ℝ≥0∞` as an `order_embedding`. -/ @[simps { fully_applied := ff }] def to_ennreal_order_embedding : ℕ∞ ↪o ℝ≥0∞ := nat.cast_order_embedding.with_top_map /-- Coercion `ℕ∞ → ℝ≥0∞` as a ring homomorphism. -/ @[simps { fully_applied := ff }] def to_ennreal_ring_hom : ℕ∞ →+* ℝ≥0∞ := (nat.cast_ring_hom ℝ≥0).with_top_map nat.cast_injective @[simp, norm_cast] lemma coe_ennreal_top : ((⊤ : ℕ∞) : ℝ≥0∞) = ⊤ := rfl @[simp, norm_cast] lemma coe_ennreal_coe (n : ℕ) : ((n : ℕ∞) : ℝ≥0∞) = n := rfl @[simp, norm_cast] lemma coe_ennreal_le : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := to_ennreal_order_embedding.le_iff_le @[simp, norm_cast] lemma coe_ennreal_lt : (m : ℝ≥0∞) < n ↔ m < n := to_ennreal_order_embedding.lt_iff_lt @[mono] lemma coe_ennreal_mono : monotone (coe : ℕ∞ → ℝ≥0∞) := to_ennreal_order_embedding.monotone @[mono] lemma coe_ennreal_strict_mono : strict_mono (coe : ℕ∞ → ℝ≥0∞) := to_ennreal_order_embedding.strict_mono @[simp, norm_cast] lemma coe_ennreal_zero : ((0 : ℕ∞) : ℝ≥0∞) = 0 := map_zero to_ennreal_ring_hom @[simp] lemma coe_ennreal_add (m n : ℕ∞) : ↑(m + n) = (m + n : ℝ≥0∞) := map_add to_ennreal_ring_hom m n @[simp] lemma coe_ennreal_one : ((1 : ℕ∞) : ℝ≥0∞) = 1 := map_one to_ennreal_ring_hom @[simp] lemma coe_ennreal_bit0 (n : ℕ∞) : ↑(bit0 n) = bit0 (n : ℝ≥0∞) := coe_ennreal_add n n @[simp] lemma coe_ennreal_bit1 (n : ℕ∞) : ↑(bit1 n) = bit1 (n : ℝ≥0∞) := map_bit1 to_ennreal_ring_hom n @[simp] lemma coe_ennreal_mul (m n : ℕ∞) : ↑(m * n) = (m * n : ℝ≥0∞) := map_mul to_ennreal_ring_hom m n @[simp] lemma coe_ennreal_min (m n : ℕ∞) : ↑(min m n) = (min m n : ℝ≥0∞) := coe_ennreal_mono.map_min @[simp] lemma coe_ennreal_max (m n : ℕ∞) : ↑(max m n) = (max m n : ℝ≥0∞) := coe_ennreal_mono.map_max @[simp] lemma coe_ennreal_sub (m n : ℕ∞) : ↑(m - n) = (m - n : ℝ≥0∞) := with_top.map_sub nat.cast_tsub nat.cast_zero m n end enat
e762e50169c30c125f57eaec6b8a1b2b6933d1ef
c777c32c8e484e195053731103c5e52af26a25d1
/src/field_theory/abel_ruffini.lean
d5d694479963dea5f5bef3934c3b5ebc4d431397
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
17,018
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import group_theory.solvable import field_theory.polynomial_galois_group import ring_theory.roots_of_unity /-! # The Abel-Ruffini Theorem This file proves one direction of the Abel-Ruffini theorem, namely that if an element is solvable by radicals, then its minimal polynomial has solvable Galois group. ## Main definitions * `solvable_by_rad F E` : the intermediate field of solvable-by-radicals elements ## Main results * the Abel-Ruffini Theorem `solvable_by_rad.is_solvable'` : An irreducible polynomial with a root that is solvable by radicals has a solvable Galois group. -/ noncomputable theory open_locale classical polynomial open polynomial intermediate_field section abel_ruffini variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] lemma gal_zero_is_solvable : is_solvable (0 : F[X]).gal := by apply_instance lemma gal_one_is_solvable : is_solvable (1 : F[X]).gal := by apply_instance lemma gal_C_is_solvable (x : F) : is_solvable (C x).gal := by apply_instance lemma gal_X_is_solvable : is_solvable (X : F[X]).gal := by apply_instance lemma gal_X_sub_C_is_solvable (x : F) : is_solvable (X - C x).gal := by apply_instance lemma gal_X_pow_is_solvable (n : ℕ) : is_solvable (X ^ n : F[X]).gal := by apply_instance lemma gal_mul_is_solvable {p q : F[X]} (hp : is_solvable p.gal) (hq : is_solvable q.gal) : is_solvable (p * q).gal := solvable_of_solvable_injective (gal.restrict_prod_injective p q) lemma gal_prod_is_solvable {s : multiset F[X]} (hs : ∀ p ∈ s, is_solvable (gal p)) : is_solvable s.prod.gal := begin apply multiset.induction_on' s, { exact gal_one_is_solvable }, { intros p t hps hts ht, rw [multiset.insert_eq_cons, multiset.prod_cons], exact gal_mul_is_solvable (hs p hps) ht }, end lemma gal_is_solvable_of_splits {p q : F[X]} (hpq : fact (p.splits (algebra_map F q.splitting_field))) (hq : is_solvable q.gal) : is_solvable p.gal := begin haveI : is_solvable (q.splitting_field ≃ₐ[F] q.splitting_field) := hq, exact solvable_of_surjective (alg_equiv.restrict_normal_hom_surjective q.splitting_field), end lemma gal_is_solvable_tower (p q : F[X]) (hpq : p.splits (algebra_map F q.splitting_field)) (hp : is_solvable p.gal) (hq : is_solvable (q.map (algebra_map F p.splitting_field)).gal) : is_solvable q.gal := begin let K := p.splitting_field, let L := q.splitting_field, haveI : fact (p.splits (algebra_map F L)) := ⟨hpq⟩, let ϕ : (L ≃ₐ[K] L) ≃* (q.map (algebra_map F K)).gal := (is_splitting_field.alg_equiv L (q.map (algebra_map F K))).aut_congr, have ϕ_inj : function.injective ϕ.to_monoid_hom := ϕ.injective, haveI : is_solvable (K ≃ₐ[F] K) := hp, haveI : is_solvable (L ≃ₐ[K] L) := solvable_of_solvable_injective ϕ_inj, exact is_solvable_of_is_scalar_tower F p.splitting_field q.splitting_field, end section gal_X_pow_sub_C lemma gal_X_pow_sub_one_is_solvable (n : ℕ) : is_solvable (X ^ n - 1 : F[X]).gal := begin by_cases hn : n = 0, { rw [hn, pow_zero, sub_self], exact gal_zero_is_solvable }, have hn' : 0 < n := pos_iff_ne_zero.mpr hn, have hn'' : (X ^ n - 1 : F[X]) ≠ 0 := X_pow_sub_C_ne_zero hn' 1, apply is_solvable_of_comm, intros σ τ, ext a ha, simp only [mem_root_set_of_ne hn'', map_sub, aeval_X_pow, aeval_one, sub_eq_zero] at ha, have key : ∀ σ : (X ^ n - 1 : F[X]).gal, ∃ m : ℕ, σ a = a ^ m, { intro σ, lift n to ℕ+ using hn', exact map_root_of_unity_eq_pow_self σ.to_alg_hom (roots_of_unity.mk_of_pow_eq a ha) }, obtain ⟨c, hc⟩ := key σ, obtain ⟨d, hd⟩ := key τ, rw [σ.mul_apply, τ.mul_apply, hc, τ.map_pow, hd, σ.map_pow, hc, ←pow_mul, pow_mul'], end lemma gal_X_pow_sub_C_is_solvable_aux (n : ℕ) (a : F) (h : (X ^ n - 1 : F[X]).splits (ring_hom.id F)) : is_solvable (X ^ n - C a).gal := begin by_cases ha : a = 0, { rw [ha, C_0, sub_zero], exact gal_X_pow_is_solvable n }, have ha' : algebra_map F (X ^ n - C a).splitting_field a ≠ 0 := mt ((injective_iff_map_eq_zero _).mp (ring_hom.injective _) a) ha, by_cases hn : n = 0, { rw [hn, pow_zero, ←C_1, ←C_sub], exact gal_C_is_solvable (1 - a) }, have hn' : 0 < n := pos_iff_ne_zero.mpr hn, have hn'' : X ^ n - C a ≠ 0 := X_pow_sub_C_ne_zero hn' a, have hn''' : (X ^ n - 1 : F[X]) ≠ 0 := X_pow_sub_C_ne_zero hn' 1, have mem_range : ∀ {c}, c ^ n = 1 → ∃ d, algebra_map F (X ^ n - C a).splitting_field d = c := λ c hc, ring_hom.mem_range.mp (minpoly.mem_range_of_degree_eq_one F c (h.def.resolve_left hn''' (minpoly.irreducible ((splitting_field.normal (X ^ n - C a)).is_integral c)) (minpoly.dvd F c (by rwa [map_id, alg_hom.map_sub, sub_eq_zero, aeval_X_pow, aeval_one])))), apply is_solvable_of_comm, intros σ τ, ext b hb, simp only [mem_root_set_of_ne hn'', map_sub, aeval_X_pow, aeval_C, sub_eq_zero] at hb, have hb' : b ≠ 0, { intro hb', rw [hb', zero_pow hn'] at hb, exact ha' hb.symm }, have key : ∀ σ : (X ^ n - C a).gal, ∃ c, σ b = b * algebra_map F _ c, { intro σ, have key : (σ b / b) ^ n = 1 := by rw [div_pow, ←σ.map_pow, hb, σ.commutes, div_self ha'], obtain ⟨c, hc⟩ := mem_range key, use c, rw [hc, mul_div_cancel' (σ b) hb'] }, obtain ⟨c, hc⟩ := key σ, obtain ⟨d, hd⟩ := key τ, rw [σ.mul_apply, τ.mul_apply, hc, τ.map_mul, τ.commutes, hd, σ.map_mul, σ.commutes, hc], rw [mul_assoc, mul_assoc, mul_right_inj' hb', mul_comm], end lemma splits_X_pow_sub_one_of_X_pow_sub_C {F : Type*} [field F] {E : Type*} [field E] (i : F →+* E) (n : ℕ) {a : F} (ha : a ≠ 0) (h : (X ^ n - C a).splits i) : (X ^ n - 1).splits i := begin have ha' : i a ≠ 0 := mt ((injective_iff_map_eq_zero i).mp (i.injective) a) ha, by_cases hn : n = 0, { rw [hn, pow_zero, sub_self], exact splits_zero i }, have hn' : 0 < n := pos_iff_ne_zero.mpr hn, have hn'' : (X ^ n - C a).degree ≠ 0 := ne_of_eq_of_ne (degree_X_pow_sub_C hn' a) (mt with_bot.coe_eq_coe.mp hn), obtain ⟨b, hb⟩ := exists_root_of_splits i h hn'', rw [eval₂_sub, eval₂_X_pow, eval₂_C, sub_eq_zero] at hb, have hb' : b ≠ 0, { intro hb', rw [hb', zero_pow hn'] at hb, exact ha' hb.symm }, let s := ((X ^ n - C a).map i).roots, have hs : _ = _ * (s.map _).prod := eq_prod_roots_of_splits h, rw [leading_coeff_X_pow_sub_C hn', ring_hom.map_one, C_1, one_mul] at hs, have hs' : s.card = n := (nat_degree_eq_card_roots h).symm.trans nat_degree_X_pow_sub_C, apply @splits_of_exists_multiset F E _ _ i (X ^ n - 1) (s.map (λ c : E, c / b)), rw [leading_coeff_X_pow_sub_one hn', ring_hom.map_one, C_1, one_mul, multiset.map_map], have C_mul_C : (C (i a⁻¹)) * (C (i a)) = 1, { rw [←C_mul, ←i.map_mul, inv_mul_cancel ha, i.map_one, C_1] }, have key1 : (X ^ n - 1).map i = C (i a⁻¹) * ((X ^ n - C a).map i).comp (C b * X), { rw [polynomial.map_sub, polynomial.map_sub, polynomial.map_pow, map_X, map_C, polynomial.map_one, sub_comp, pow_comp, X_comp, C_comp, mul_pow, ←C_pow, hb, mul_sub, ←mul_assoc, C_mul_C, one_mul] }, have key2 : (λ q : E[X], q.comp (C b * X)) ∘ (λ c : E, X - C c) = (λ c : E, C b * (X - C (c / b))), { ext1 c, change (X - C c).comp (C b * X) = C b * (X - C (c / b)), rw [sub_comp, X_comp, C_comp, mul_sub, ←C_mul, mul_div_cancel' c hb'] }, rw [key1, hs, multiset_prod_comp, multiset.map_map, key2, multiset.prod_map_mul, multiset.map_const, multiset.prod_replicate, hs', ←C_pow, hb, ←mul_assoc, C_mul_C, one_mul], all_goals { exact field.to_nontrivial F }, end lemma gal_X_pow_sub_C_is_solvable (n : ℕ) (x : F) : is_solvable (X ^ n - C x).gal := begin by_cases hx : x = 0, { rw [hx, C_0, sub_zero], exact gal_X_pow_is_solvable n }, apply gal_is_solvable_tower (X ^ n - 1) (X ^ n - C x), { exact splits_X_pow_sub_one_of_X_pow_sub_C _ n hx (splitting_field.splits _) }, { exact gal_X_pow_sub_one_is_solvable n }, { rw [polynomial.map_sub, polynomial.map_pow, map_X, map_C], apply gal_X_pow_sub_C_is_solvable_aux, have key := splitting_field.splits (X ^ n - 1 : F[X]), rwa [←splits_id_iff_splits, polynomial.map_sub, polynomial.map_pow, map_X, polynomial.map_one] at key } end end gal_X_pow_sub_C variables (F) /-- Inductive definition of solvable by radicals -/ inductive is_solvable_by_rad : E → Prop | base (a : F) : is_solvable_by_rad (algebra_map F E a) | add (a b : E) : is_solvable_by_rad a → is_solvable_by_rad b → is_solvable_by_rad (a + b) | neg (α : E) : is_solvable_by_rad α → is_solvable_by_rad (-α) | mul (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α * β) | inv (α : E) : is_solvable_by_rad α → is_solvable_by_rad α⁻¹ | rad (α : E) (n : ℕ) (hn : n ≠ 0) : is_solvable_by_rad (α^n) → is_solvable_by_rad α variables (E) /-- The intermediate field of solvable-by-radicals elements -/ def solvable_by_rad : intermediate_field F E := { carrier := is_solvable_by_rad F, zero_mem' := by { convert is_solvable_by_rad.base (0 : F), rw ring_hom.map_zero }, add_mem' := is_solvable_by_rad.add, neg_mem' := is_solvable_by_rad.neg, one_mem' := by { convert is_solvable_by_rad.base (1 : F), rw ring_hom.map_one }, mul_mem' := is_solvable_by_rad.mul, inv_mem' := is_solvable_by_rad.inv, algebra_map_mem' := is_solvable_by_rad.base } namespace solvable_by_rad variables {F} {E} {α : E} lemma induction (P : solvable_by_rad F E → Prop) (base : ∀ α : F, P (algebra_map F (solvable_by_rad F E) α)) (add : ∀ α β : solvable_by_rad F E, P α → P β → P (α + β)) (neg : ∀ α : solvable_by_rad F E, P α → P (-α)) (mul : ∀ α β : solvable_by_rad F E, P α → P β → P (α * β)) (inv : ∀ α : solvable_by_rad F E, P α → P α⁻¹) (rad : ∀ α : solvable_by_rad F E, ∀ n : ℕ, n ≠ 0 → P (α^n) → P α) (α : solvable_by_rad F E) : P α := begin revert α, suffices : ∀ (α : E), is_solvable_by_rad F α → (∃ β : solvable_by_rad F E, ↑β = α ∧ P β), { intro α, obtain ⟨α₀, hα₀, Pα⟩ := this α (subtype.mem α), convert Pα, exact subtype.ext hα₀.symm }, apply is_solvable_by_rad.rec, { exact λ α, ⟨algebra_map F (solvable_by_rad F E) α, rfl, base α⟩ }, { intros α β hα hβ Pα Pβ, obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩, exact ⟨α₀ + β₀, by {rw [←hα₀, ←hβ₀], refl }, add α₀ β₀ Pα Pβ⟩ }, { intros α hα Pα, obtain ⟨α₀, hα₀, Pα⟩ := Pα, exact ⟨-α₀, by {rw ←hα₀, refl }, neg α₀ Pα⟩ }, { intros α β hα hβ Pα Pβ, obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩, exact ⟨α₀ * β₀, by {rw [←hα₀, ←hβ₀], refl }, mul α₀ β₀ Pα Pβ⟩ }, { intros α hα Pα, obtain ⟨α₀, hα₀, Pα⟩ := Pα, exact ⟨α₀⁻¹, by {rw ←hα₀, refl }, inv α₀ Pα⟩ }, { intros α n hn hα Pα, obtain ⟨α₀, hα₀, Pα⟩ := Pα, refine ⟨⟨α, is_solvable_by_rad.rad α n hn hα⟩, rfl, rad _ n hn _⟩, convert Pα, exact subtype.ext (eq.trans ((solvable_by_rad F E).coe_pow _ n) hα₀.symm) } end theorem is_integral (α : solvable_by_rad F E) : is_integral F α := begin revert α, apply solvable_by_rad.induction, { exact λ _, is_integral_algebra_map }, { exact λ _ _, is_integral_add }, { exact λ _, is_integral_neg }, { exact λ _ _, is_integral_mul }, { exact λ α hα, subalgebra.inv_mem_of_algebraic (integral_closure F (solvable_by_rad F E)) (show is_algebraic F ↑(⟨α, hα⟩ : integral_closure F (solvable_by_rad F E)), by exact is_algebraic_iff_is_integral.mpr hα) }, { intros α n hn hα, obtain ⟨p, h1, h2⟩ := is_algebraic_iff_is_integral.mpr hα, refine is_algebraic_iff_is_integral.mp ⟨p.comp (X ^ n), ⟨λ h, h1 (leading_coeff_eq_zero.mp _), by rw [aeval_comp, aeval_X_pow, h2]⟩⟩, rwa [←leading_coeff_eq_zero, leading_coeff_comp, leading_coeff_X_pow, one_pow, mul_one] at h, rwa nat_degree_X_pow } end /-- The statement to be proved inductively -/ def P (α : solvable_by_rad F E) : Prop := is_solvable (minpoly F α).gal /-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/ lemma induction3 {α : solvable_by_rad F E} {n : ℕ} (hn : n ≠ 0) (hα : P (α ^ n)) : P α := begin let p := minpoly F (α ^ n), have hp : p.comp (X ^ n) ≠ 0, { intro h, cases (comp_eq_zero_iff.mp h) with h' h', { exact minpoly.ne_zero (is_integral (α ^ n)) h' }, { exact hn (by rw [←nat_degree_C _, ←h'.2, nat_degree_X_pow]) } }, apply gal_is_solvable_of_splits, { exact ⟨splits_of_splits_of_dvd _ hp (splitting_field.splits (p.comp (X ^ n))) (minpoly.dvd F α (by rw [aeval_comp, aeval_X_pow, minpoly.aeval]))⟩ }, { refine gal_is_solvable_tower p (p.comp (X ^ n)) _ hα _, { exact gal.splits_in_splitting_field_of_comp _ _ (by rwa [nat_degree_X_pow]) }, { obtain ⟨s, hs⟩ := (splits_iff_exists_multiset _).1 (splitting_field.splits p), rw [map_comp, polynomial.map_pow, map_X, hs, mul_comp, C_comp], apply gal_mul_is_solvable (gal_C_is_solvable _), rw multiset_prod_comp, apply gal_prod_is_solvable, intros q hq, rw multiset.mem_map at hq, obtain ⟨q, hq, rfl⟩ := hq, rw multiset.mem_map at hq, obtain ⟨q, hq, rfl⟩ := hq, rw [sub_comp, X_comp, C_comp], exact gal_X_pow_sub_C_is_solvable n q } }, end /-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/ lemma induction2 {α β γ : solvable_by_rad F E} (hγ : γ ∈ F⟮α, β⟯) (hα : P α) (hβ : P β) : P γ := begin let p := (minpoly F α), let q := (minpoly F β), have hpq := polynomial.splits_of_splits_mul _ (mul_ne_zero (minpoly.ne_zero (is_integral α)) (minpoly.ne_zero (is_integral β))) (splitting_field.splits (p * q)), let f : F⟮α, β⟯ →ₐ[F] (p * q).splitting_field := classical.choice (alg_hom_mk_adjoin_splits begin intros x hx, cases hx, rw hx, exact ⟨is_integral α, hpq.1⟩, cases hx, exact ⟨is_integral β, hpq.2⟩, end), have key : minpoly F γ = minpoly F (f ⟨γ, hγ⟩) := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible (is_integral γ)) begin suffices : aeval (⟨γ, hγ⟩ : F ⟮α, β⟯) (minpoly F γ) = 0, { rw [aeval_alg_hom_apply, this, alg_hom.map_zero] }, apply (algebra_map F⟮α, β⟯ (solvable_by_rad F E)).injective, rw [ring_hom.map_zero, ← aeval_algebra_map_apply], exact minpoly.aeval F γ, end (minpoly.monic (is_integral γ)), rw [P, key], exact gal_is_solvable_of_splits ⟨normal.splits (splitting_field.normal _) _⟩ (gal_mul_is_solvable hα hβ), end /-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/ lemma induction1 {α β : solvable_by_rad F E} (hβ : β ∈ F⟮α⟯) (hα : P α) : P β := induction2 (adjoin.mono F _ _ (ge_of_eq (set.pair_eq_singleton α)) hβ) hα hα theorem is_solvable (α : solvable_by_rad F E) : is_solvable (minpoly F α).gal := begin revert α, apply solvable_by_rad.induction, { exact λ α, by { rw minpoly.eq_X_sub_C, exact gal_X_sub_C_is_solvable α } }, { exact λ α β, induction2 (add_mem (subset_adjoin F _ (set.mem_insert α _)) (subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) }, { exact λ α, induction1 (neg_mem (mem_adjoin_simple_self F α)) }, { exact λ α β, induction2 (mul_mem (subset_adjoin F _ (set.mem_insert α _)) (subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) }, { exact λ α, induction1 (inv_mem (mem_adjoin_simple_self F α)) }, { exact λ α n, induction3 }, end /-- **Abel-Ruffini Theorem** (one direction): An irreducible polynomial with an `is_solvable_by_rad` root has solvable Galois group -/ lemma is_solvable' {α : E} {q : F[X]} (q_irred : irreducible q) (q_aeval : aeval α q = 0) (hα : is_solvable_by_rad F α) : _root_.is_solvable q.gal := begin haveI : _root_.is_solvable (q * C q.leading_coeff⁻¹).gal, { rw [minpoly.eq_of_irreducible q_irred q_aeval, ←show minpoly F (⟨α, hα⟩ : solvable_by_rad F E) = minpoly F α, from minpoly.eq_of_algebra_map_eq (ring_hom.injective _) (is_integral ⟨α, hα⟩) rfl], exact is_solvable ⟨α, hα⟩ }, refine solvable_of_surjective (gal.restrict_dvd_surjective ⟨C q.leading_coeff⁻¹, rfl⟩ _), rw [mul_ne_zero_iff, ne, ne, C_eq_zero, inv_eq_zero], exact ⟨q_irred.ne_zero, leading_coeff_ne_zero.mpr q_irred.ne_zero⟩, end end solvable_by_rad end abel_ruffini
3298de8aee6f720e5e76e5c7fc4a918e18fe99af
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/smt_ematch2.lean
a365f5bc2ed8be9ad289944e4baafd32fbe10b53
[ "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
2,775
lean
universe variables u namespace foo variables {α : Type u} open smt_tactic meta def no_ac : smt_config := { default_smt_config with cc_cfg := { default_cc_config with ac := ff }} meta def blast : tactic unit := using_smt_core no_ac $ intros >> repeat (ematch >> try close) section add_comm_monoid variables [add_comm_monoid α] attribute [ematch] add_comm add_assoc theorem add_comm_three (a b c : α) : a + b + c = c + b + a := by blast theorem add.comm4 : ∀ (n m k l : α), n + m + (k + l) = n + k + (m + l) := by blast end add_comm_monoid section group variable [group α] attribute [ematch] mul_assoc mul_left_inv one_mul theorem inv_mul_cancel_left (a b : α) : a⁻¹ * (a * b) = b := by blast end group namespace subt constant subt : nat → nat → Prop axiom subt_trans {a b c : nat} : subt a b → subt b c → subt a c attribute [ematch] subt_trans lemma ex (a b c d : nat) : subt a b → subt b c → subt c d → subt a d := by blast end subt section ring variables [ring α] (a b : α) attribute [ematch] zero_mul lemma ex2 : a = 0 → a * b = 0 := by blast definition ex1 (a b : int) : a = 0 → a * b = 0 := by blast end ring namespace cast1 constant C : nat → Type constant f : ∀ n, C n → C n axiom fax (n : nat) (a : C (2*n)) : (: f (2*n) a :) = a attribute [ematch] fax lemma ex3 (n m : nat) (a : C n) : n = 2*m → f n a = a := by blast end cast1 namespace cast2 constant C : nat → Type constant f : ∀ n, C n → C n constant g : ∀ n, C n → C n → C n axiom gffax (n : nat) (a b : C n) : (: g n (f n a) (f n b) :) = a attribute [ematch] gffax lemma ex4 (n m : nat) (a c : C n) (b : C m) : n = m → a == f m b → g n a (f n c) == b := by blast end cast2 namespace cast3 constant C : nat → Type constant f : ∀ n, C n → C n constant g : ∀ n, C n → C n → C n axiom gffax (n : nat) (a b : C n) : (: g n a b :) = a attribute [ematch] gffax lemma ex5 (n m : nat) (a c : C n) (b : C m) (e : m = n) : a == b → g n a a == b := by blast end cast3 namespace tuple constant {α} tuple: Type α → nat → Type α constant nil {α : Type u} : tuple α 0 constant append {α : Type u} {n m : nat} : tuple α n → tuple α m → tuple α (n + m) infix ` ++ ` := append axiom append_assoc {α : Type u} {n₁ n₂ n₃ : nat} (v₁ : tuple α n₁) (v₂ : tuple α n₂) (v₃ : tuple α n₃) : (v₁ ++ v₂) ++ v₃ == v₁ ++ (v₂ ++ v₃) attribute [ematch] append_assoc variables {p m n q : nat} variables {xs : tuple α m} variables {ys : tuple α n} variables {zs : tuple α p} variables {ws : tuple α q} lemma ex6 : p = m + n → zs == xs ++ ys → zs ++ ws == xs ++ (ys ++ ws) := by blast def ex : p = n + m → zs == xs ++ ys → zs ++ ws == xs ++ (ys ++ ws) := by blast end tuple end foo
f63ae0a17a1cbdb49b448f1bf20a02e720335025
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/pi.lean
b874c5e60dbab20d9e0669de970325cbf975fb2c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,813
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.pi.basic import Mathlib.category_theory.limits.limits import Mathlib.PostPort universes u₁ v₁ namespace Mathlib /-! # Limits in the category of indexed families of objects. Given a functor `F : J ⥤ Π i, C i` into a category of indexed families, 1. we can assemble a collection of cones over `F ⋙ pi.eval C i` into a cone over `F` 2. if all those cones are limit cones, the assembled cone is a limit cone, and 3. if we have limits for each of `F ⋙ pi.eval C i`, we can produce a `has_limit F` instance -/ namespace category_theory.pi /-- A cone over `F : J ⥤ Π i, C i` has as its components cones over each of the `F ⋙ pi.eval C i`. -/ def cone_comp_eval {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} (c : limits.cone F) (i : I) : limits.cone (F ⋙ eval C i) := limits.cone.mk (limits.cone.X c i) (nat_trans.mk fun (j : J) => nat_trans.app (limits.cone.π c) j i) /-- A cocone over `F : J ⥤ Π i, C i` has as its components cocones over each of the `F ⋙ pi.eval C i`. -/ def cocone_comp_eval {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} (c : limits.cocone F) (i : I) : limits.cocone (F ⋙ eval C i) := limits.cocone.mk (limits.cocone.X c i) (nat_trans.mk fun (j : J) => nat_trans.app (limits.cocone.ι c) j i) /-- Given a family of cones over the `F ⋙ pi.eval C i`, we can assemble these together as a `cone F`. -/ def cone_of_cone_comp_eval {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} (c : (i : I) → limits.cone (F ⋙ eval C i)) : limits.cone F := limits.cone.mk (fun (i : I) => limits.cone.X (c i)) (nat_trans.mk fun (j : J) (i : I) => nat_trans.app (limits.cone.π (c i)) j) /-- Given a family of cocones over the `F ⋙ pi.eval C i`, we can assemble these together as a `cocone F`. -/ def cocone_of_cocone_comp_eval {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} (c : (i : I) → limits.cocone (F ⋙ eval C i)) : limits.cocone F := limits.cocone.mk (fun (i : I) => limits.cocone.X (c i)) (nat_trans.mk fun (j : J) (i : I) => nat_trans.app (limits.cocone.ι (c i)) j) /-- Given a family of limit cones over the `F ⋙ pi.eval C i`, assembling them together as a `cone F` produces a limit cone. -/ def cone_of_cone_eval_is_limit {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} {c : (i : I) → limits.cone (F ⋙ eval C i)} (P : (i : I) → limits.is_limit (c i)) : limits.is_limit (cone_of_cone_comp_eval c) := limits.is_limit.mk fun (s : limits.cone F) (i : I) => limits.is_limit.lift (P i) (cone_comp_eval s i) /-- Given a family of colimit cocones over the `F ⋙ pi.eval C i`, assembling them together as a `cocone F` produces a colimit cocone. -/ def cocone_of_cocone_eval_is_colimit {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} {c : (i : I) → limits.cocone (F ⋙ eval C i)} (P : (i : I) → limits.is_colimit (c i)) : limits.is_colimit (cocone_of_cocone_comp_eval c) := limits.is_colimit.mk fun (s : limits.cocone F) (i : I) => limits.is_colimit.desc (P i) (cocone_comp_eval s i) /-- If we have a functor `F : J ⥤ Π i, C i` into a category of indexed families, and we have limits for each of the `F ⋙ pi.eval C i`, then `F` has a limit. -/ theorem has_limit_of_has_limit_comp_eval {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} [∀ (i : I), limits.has_limit (F ⋙ eval C i)] : limits.has_limit F := limits.has_limit.mk (limits.limit_cone.mk (cone_of_cone_comp_eval fun (i : I) => limits.limit.cone (F ⋙ eval (fun (i : I) => C i) i)) (cone_of_cone_eval_is_limit fun (i : I) => limits.limit.is_limit (F ⋙ eval (fun (i : I) => C i) i))) /-- If we have a functor `F : J ⥤ Π i, C i` into a category of indexed families, and colimits exist for each of the `F ⋙ pi.eval C i`, there is a colimit for `F`. -/ theorem has_colimit_of_has_colimit_comp_eval {I : Type v₁} {C : I → Type u₁} [(i : I) → category (C i)] {J : Type v₁} [small_category J] {F : J ⥤ ((i : I) → C i)} [∀ (i : I), limits.has_colimit (F ⋙ eval C i)] : limits.has_colimit F := sorry
5c853987a64542e020568102b8b139f142d61bf5
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/shapes/finite_limits.lean
d0d61a432192657a9216c6d17c5c53d6371a47d9
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
6,879
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fintype.basic import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.pullbacks universes v u namespace category_theory instance discrete_fintype {α : Type*} [fintype α] : fintype (discrete α) := by { dsimp [discrete], apply_instance } instance discrete_hom_fintype {α : Type*} [decidable_eq α] (X Y : discrete α) : fintype (X ⟶ Y) := by { apply ulift.fintype } /-- A category with a `fintype` of objects, and a `fintype` for each morphism space. -/ class fin_category (J : Type v) [small_category J] := (decidable_eq_obj : decidable_eq J . tactic.apply_instance) (fintype_obj : fintype J . tactic.apply_instance) (decidable_eq_hom : Π (j j' : J), decidable_eq (j ⟶ j') . tactic.apply_instance) (fintype_hom : Π (j j' : J), fintype (j ⟶ j') . tactic.apply_instance) attribute [instance] fin_category.decidable_eq_obj fin_category.fintype_obj fin_category.decidable_eq_hom fin_category.fintype_hom -- We need a `decidable_eq` instance here to construct `fintype` on the morphism spaces. instance fin_category_discrete_of_decidable_fintype (J : Type v) [fintype J] [decidable_eq J] : fin_category (discrete J) := { } end category_theory open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] class has_finite_limits := (has_limits_of_shape : Π (J : Type v) [small_category J] [fin_category J], has_limits_of_shape J C) class has_finite_colimits := (has_colimits_of_shape : Π (J : Type v) [small_category J] [fin_category J], has_colimits_of_shape J C) attribute [instance, priority 100] -- see Note [lower instance priority] has_finite_limits.has_limits_of_shape has_finite_colimits.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_limits C] : has_finite_limits C := { has_limits_of_shape := λ J _ _, by { resetI, apply_instance } } @[priority 100] -- see Note [lower instance priority] instance [has_colimits C] : has_finite_colimits C := { has_colimits_of_shape := λ J _ _, by { resetI, apply_instance } } section open walking_parallel_pair walking_parallel_pair_hom instance fintype_walking_parallel_pair : fintype walking_parallel_pair := { elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset, complete := λ x, by { cases x; simp } } local attribute [tidy] tactic.case_bash instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') := { elems := walking_parallel_pair.rec_on j (walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset [left, right].to_finset) (walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset), complete := by tidy } end instance : fin_category walking_parallel_pair := { } /-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/ def has_equalizers_of_has_finite_limits [has_finite_limits C] : has_equalizers C := { has_limits_of_shape := infer_instance } /-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all coequalizers -/ def has_coequalizers_of_has_finite_colimits [has_finite_colimits C] : has_coequalizers C := { has_colimits_of_shape := infer_instance } variables {J : Type v} local attribute [tidy] tactic.case_bash namespace wide_pullback_shape instance fintype_obj [fintype J] : fintype (wide_pullback_shape J) := by { rw wide_pullback_shape, apply_instance } instance fintype_hom [decidable_eq J] (j j' : wide_pullback_shape J) : fintype (j ⟶ j') := { elems := begin cases j', { cases j, { exact {hom.id none} }, { exact {hom.term j} } }, { by_cases some j' = j, { rw h, exact {hom.id j} }, { exact ∅ } } end, complete := by tidy } end wide_pullback_shape namespace wide_pushout_shape instance fintype_obj [fintype J] : fintype (wide_pushout_shape J) := by { rw wide_pushout_shape, apply_instance } instance fintype_hom [decidable_eq J] (j j' : wide_pushout_shape J) : fintype (j ⟶ j') := { elems := begin cases j, { cases j', { exact {hom.id none} }, { exact {hom.init j'} } }, { by_cases some j = j', { rw h, exact {hom.id j'} }, { exact ∅ } } end, complete := by tidy } end wide_pushout_shape instance fin_category_wide_pullback [fintype J] [decidable_eq J] : fin_category (wide_pullback_shape J) := { fintype_hom := wide_pullback_shape.fintype_hom } instance fin_category_wide_pushout [fintype J] [decidable_eq J] : fin_category (wide_pushout_shape J) := { fintype_hom := wide_pushout_shape.fintype_hom } /-- `has_finite_wide_pullbacks` represents a choice of wide pullback for every finite collection of morphisms -/ class has_finite_wide_pullbacks := (has_limits_of_shape : Π (J : Type v) [decidable_eq J] [fintype J], has_limits_of_shape (wide_pullback_shape J) C) attribute [instance] has_finite_wide_pullbacks.has_limits_of_shape /-- `has_finite_wide_pushouts` represents a choice of wide pushout for every finite collection of morphisms -/ class has_finite_wide_pushouts := (has_colimits_of_shape : Π (J : Type v) [decidable_eq J] [fintype J], has_colimits_of_shape (wide_pushout_shape J) C) attribute [instance] has_finite_wide_pushouts.has_colimits_of_shape /-- Finite wide pullbacks are finite limits, so if `C` has all finite limits, it also has finite wide pullbacks -/ def has_finite_wide_pullbacks_of_has_finite_limits [has_finite_limits C] : has_finite_wide_pullbacks C := { has_limits_of_shape := λ J _ _, by exactI (has_finite_limits.has_limits_of_shape _) } /-- Finite wide pushouts are finite colimits, so if `C` has all finite colimits, it also has finite wide pushouts -/ def has_finite_wide_pushouts_of_has_finite_limits [has_finite_colimits C] : has_finite_wide_pushouts C := { has_colimits_of_shape := λ J _ _, by exactI (has_finite_colimits.has_colimits_of_shape _) } instance fintype_walking_pair : fintype walking_pair := { elems := {walking_pair.left, walking_pair.right}, complete := λ x, by { cases x; simp } } /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ def has_pullbacks_of_has_finite_limits [has_finite_wide_pullbacks C] : has_pullbacks C := { has_limits_of_shape := has_finite_wide_pullbacks.has_limits_of_shape walking_pair } /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ def has_pushouts_of_has_finite_colimits [has_finite_wide_pushouts C] : has_pushouts C := { has_colimits_of_shape := has_finite_wide_pushouts.has_colimits_of_shape walking_pair } end category_theory.limits
40331bdda72c91c996b326f4a99cd099359aabc8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/module/strong_topology.lean
8acfe0b4abcded9a0bd6c902dfdcdaefd135af86
[ "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
9,379
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import topology.algebra.uniform_convergence /-! # Strong topologies on the space of continuous linear maps In this file, we define the strong topologies on `E →L[𝕜] F` associated with a family `𝔖 : set (set E)` to be the topology of uniform convergence on the elements of `𝔖` (also called the topology of `𝔖`-convergence). The lemma `uniform_on_fun.has_continuous_smul_of_image_bounded` tells us that this is a vector space topology if the continuous linear image of any element of `𝔖` is bounded (in the sense of `bornology.is_vonN_bounded`). We then declare an instance for the case where `𝔖` is exactly the set of all bounded subsets of `E`, giving us the so-called "topology of uniform convergence on bounded sets" (or "topology of bounded convergence"), which coincides with the operator norm topology in the case of `normed_space`s. Other useful examples include the weak-* topology (when `𝔖` is the set of finite sets or the set of singletons) and the topology of compact convergence (when `𝔖` is the set of relatively compact sets). ## Main definitions * `continuous_linear_map.strong_topology` is the topology mentioned above for an arbitrary `𝔖`. * `continuous_linear_map.topological_space` is the topology of bounded convergence. This is declared as an instance. ## Main statements * `continuous_linear_map.strong_topology.topological_add_group` and `continuous_linear_map.strong_topology.has_continuous_smul` show that the strong topology makes `E →L[𝕜] F` a topological vector space, with the assumptions on `𝔖` mentioned above. * `continuous_linear_map.topological_add_group` and `continuous_linear_map.has_continuous_smul` register these facts as instances for the special case of bounded convergence. ## References * [N. Bourbaki, *Topological Vector Spaces*][bourbaki1987] ## TODO * show that these topologies are T₂ and locally convex if the topology on `F` is * add a type alias for continuous linear maps with the topology of `𝔖`-convergence? ## Tags uniform convergence, bounded convergence -/ open_locale topological_space uniform_convergence namespace continuous_linear_map section general variables {𝕜₁ 𝕜₂ : Type*} [normed_field 𝕜₁] [normed_field 𝕜₂] (σ : 𝕜₁ →+* 𝕜₂) {E : Type*} (F : Type*) [add_comm_group E] [module 𝕜₁ E] [add_comm_group F] [module 𝕜₂ F] [topological_space E] /-- Given `E` and `F` two topological vector spaces and `𝔖 : set (set E)`, then `strong_topology σ F 𝔖` is the "topology of uniform convergence on the elements of `𝔖`" on `E →L[𝕜] F`. If the continuous linear image of any element of `𝔖` is bounded, this makes `E →L[𝕜] F` a topological vector space. -/ def strong_topology [topological_space F] [topological_add_group F] (𝔖 : set (set E)) : topological_space (E →SL[σ] F) := (@uniform_on_fun.topological_space E F (topological_add_group.to_uniform_space F) 𝔖).induced coe_fn /-- The uniform structure associated with `continuous_linear_map.strong_topology`. We make sure that this has nice definitional properties. -/ def strong_uniformity [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : uniform_space (E →SL[σ] F) := @uniform_space.replace_topology _ (strong_topology σ F 𝔖) ((uniform_on_fun.uniform_space E F 𝔖).comap coe_fn) (by rw [strong_topology, uniform_add_group.to_uniform_space_eq]; refl) @[simp] lemma strong_uniformity_topology_eq [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : (strong_uniformity σ F 𝔖).to_topological_space = strong_topology σ F 𝔖 := rfl lemma strong_uniformity.uniform_add_group [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : @uniform_add_group (E →SL[σ] F) (strong_uniformity σ F 𝔖) _ := begin letI : uniform_space (E →SL[σ] F) := strong_uniformity σ F 𝔖, rw [strong_uniformity, uniform_space.replace_topology_eq], let φ : (E →SL[σ] F) →+ E →ᵤ[𝔖] F := ⟨(coe_fn : (E →SL[σ] F) → E →ᵤ F), rfl, λ _ _, rfl⟩, exact uniform_add_group_comap φ end lemma strong_topology.topological_add_group [topological_space F] [topological_add_group F] (𝔖 : set (set E)) : @topological_add_group (E →SL[σ] F) (strong_topology σ F 𝔖) _ := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, letI : uniform_space (E →SL[σ] F) := strong_uniformity σ F 𝔖, haveI : uniform_add_group (E →SL[σ] F) := strong_uniformity.uniform_add_group σ F 𝔖, apply_instance end lemma strong_topology.has_continuous_smul [ring_hom_surjective σ] [ring_hom_isometric σ] [topological_space F] [topological_add_group F] [has_continuous_smul 𝕜₂ F] (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (⊆) 𝔖) (h𝔖₃ : ∀ S ∈ 𝔖, bornology.is_vonN_bounded 𝕜₁ S) : @has_continuous_smul 𝕜₂ (E →SL[σ] F) _ _ (strong_topology σ F 𝔖) := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, letI : topological_space (E →SL[σ] F) := strong_topology σ F 𝔖, let φ : (E →SL[σ] F) →ₗ[𝕜₂] E →ᵤ[𝔖] F := ⟨(coe_fn : (E →SL[σ] F) → E → F), λ _ _, rfl, λ _ _, rfl⟩, exact uniform_on_fun.has_continuous_smul_induced_of_image_bounded 𝕜₂ E F (E →SL[σ] F) h𝔖₁ h𝔖₂ φ ⟨rfl⟩ (λ u s hs, (h𝔖₃ s hs).image u) end lemma strong_topology.has_basis_nhds_zero_of_basis [topological_space F] [topological_add_group F] {ι : Type*} (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (⊆) 𝔖) {p : ι → Prop} {b : ι → set F} (h : (𝓝 0 : filter F).has_basis p b) : (@nhds (E →SL[σ] F) (strong_topology σ F 𝔖) 0).has_basis (λ Si : set E × ι, Si.1 ∈ 𝔖 ∧ p Si.2) (λ Si, {f : E →SL[σ] F | ∀ x ∈ Si.1, f x ∈ b Si.2}) := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, rw nhds_induced, exact (uniform_on_fun.has_basis_nhds_zero_of_basis 𝔖 h𝔖₁ h𝔖₂ h).comap coe_fn end lemma strong_topology.has_basis_nhds_zero [topological_space F] [topological_add_group F] (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (⊆) 𝔖) : (@nhds (E →SL[σ] F) (strong_topology σ F 𝔖) 0).has_basis (λ SV : set E × set F, SV.1 ∈ 𝔖 ∧ SV.2 ∈ (𝓝 0 : filter F)) (λ SV, {f : E →SL[σ] F | ∀ x ∈ SV.1, f x ∈ SV.2}) := strong_topology.has_basis_nhds_zero_of_basis σ F 𝔖 h𝔖₁ h𝔖₂ (𝓝 0).basis_sets end general section bounded_sets variables {𝕜₁ 𝕜₂ : Type*} [normed_field 𝕜₁] [normed_field 𝕜₂] {σ : 𝕜₁ →+* 𝕜₂} {E F : Type*} [add_comm_group E] [module 𝕜₁ E] [add_comm_group F] [module 𝕜₂ F] [topological_space E] /-- The topology of bounded convergence on `E →L[𝕜] F`. This coincides with the topology induced by the operator norm when `E` and `F` are normed spaces. -/ instance [topological_space F] [topological_add_group F] : topological_space (E →SL[σ] F) := strong_topology σ F {S | bornology.is_vonN_bounded 𝕜₁ S} instance [topological_space F] [topological_add_group F] : topological_add_group (E →SL[σ] F) := strong_topology.topological_add_group σ F _ instance [ring_hom_surjective σ] [ring_hom_isometric σ] [topological_space F] [topological_add_group F] [has_continuous_smul 𝕜₂ F] : has_continuous_smul 𝕜₂ (E →SL[σ] F) := strong_topology.has_continuous_smul σ F {S | bornology.is_vonN_bounded 𝕜₁ S} ⟨∅, bornology.is_vonN_bounded_empty 𝕜₁ E⟩ (directed_on_of_sup_mem $ λ _ _, bornology.is_vonN_bounded.union) (λ s hs, hs) instance [uniform_space F] [uniform_add_group F] : uniform_space (E →SL[σ] F) := strong_uniformity σ F {S | bornology.is_vonN_bounded 𝕜₁ S} instance [uniform_space F] [uniform_add_group F] : uniform_add_group (E →SL[σ] F) := strong_uniformity.uniform_add_group σ F _ protected lemma has_basis_nhds_zero_of_basis [topological_space F] [topological_add_group F] {ι : Type*} {p : ι → Prop} {b : ι → set F} (h : (𝓝 0 : filter F).has_basis p b) : (𝓝 (0 : E →SL[σ] F)).has_basis (λ Si : set E × ι, bornology.is_vonN_bounded 𝕜₁ Si.1 ∧ p Si.2) (λ Si, {f : E →SL[σ] F | ∀ x ∈ Si.1, f x ∈ b Si.2}) := strong_topology.has_basis_nhds_zero_of_basis σ F {S | bornology.is_vonN_bounded 𝕜₁ S} ⟨∅, bornology.is_vonN_bounded_empty 𝕜₁ E⟩ (directed_on_of_sup_mem $ λ _ _, bornology.is_vonN_bounded.union) h protected lemma has_basis_nhds_zero [topological_space F] [topological_add_group F] : (𝓝 (0 : E →SL[σ] F)).has_basis (λ SV : set E × set F, bornology.is_vonN_bounded 𝕜₁ SV.1 ∧ SV.2 ∈ (𝓝 0 : filter F)) (λ SV, {f : E →SL[σ] F | ∀ x ∈ SV.1, f x ∈ SV.2}) := continuous_linear_map.has_basis_nhds_zero_of_basis (𝓝 0).basis_sets end bounded_sets end continuous_linear_map
0807cddc951a70520abd3f973a17e3930e043dd4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/pattern_pp.lean
64977ca8965855e348392c4e80e09806d1106d75
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
496
lean
noncomputable definition Sum : nat → (nat → nat) → nat := sorry attribute [forward] definition Sum_weird (f g h : nat → nat) (n : nat) : (Sum n (λ x, f (g (h x)))) = 1 := sorry print Sum_weird /- attribute [forward] definition Sum_weird : ∀ (f g h : nat → nat) (n : nat), eq (Sum n (λ (x : nat), f (g (h x)))) 1 := λ (f g h : nat → nat) (n : nat), sorry (multi-)patterns: ?M_1 : nat → nat, ?M_2 : nat → nat, ?M_3 : nat → nat, ?M_4 : nat {Sum ?M_4 (λ (x : nat), ?M_1)} -/
47a37908cc7152a21337806b0625f36e8d625ca5
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/meta/coinductive_predicates.lean
cbe756db64ece8696619f2acfa0ea5145035e755
[ "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
23,077
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 (CMU) -/ namespace name def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace expr open expr meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none meta def local_binder_info : expr → binder_info | (local_const x n bi t) := bi | e := binder_info.default meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] end expr namespace tactic open level expr tactic meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ const n $ ls.map param meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h, h'], _)] ← induction e [], elim_gen_prod n h' (hs ++ [h]) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] end tactic section universe u @[user_attribute] meta def monotonicity : user_attribute := { name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← whnf p, (expr.pi qn qbi qd qb) ← whnf q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply ((const `monotonicity.pi [u] : expr) pd p' q'), skip) <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply ((const `monotonicity.imp []: expr) pd p' qd q'), skip))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← mk_local_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← mk_local_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m.2), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h) ← elim_gen_prod pds.length h [], (hs, h) ← elim_gen_prod pds.length h [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply (pd.destruct.app_of_list ps) >> skip)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [], if n_eqs > 0 then do (eqs, eq') ← elim_gen_prod (n_eqs - 1) h [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), iterate assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework open lean.parser open interactive @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules (i.e. only a since C -/ meta def coinduction (rule : expr) : tactic unit := focus1 $ do ctxts' ← intros, ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v.2 ≠ g), tgt ← target, (is, ty) ← mk_local_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m.2)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars), rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, iterate (econstructor >> skip)), -- clean up remaining coinduction steps all_goals (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [], (match eqs with | [] := clear h | (e::eqs) := do (hs, h) ← elim_gen_prod eqs.length h [], (h::(hs.reverse)).mmap' subst end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule, skip end interactive end tactic
620a9322613a374d2c5602f2df91e83a804d42af
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/representation_theory/maschke.lean
f9c6e9bdf82fe09f1c16547445d7014b457c615e
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
5,918
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison -/ import data.monoid_algebra import ring_theory.algebra import algebra.invertible import algebra.char_p import linear_algebra.basis /-! # Maschke's theorem We prove Maschke's theorem for finite groups, in the formulation that every submodule of a `k[G]` module has a complement, when `k` is a field with `¬(ring_char k ∣ fintype.card G)`. We do the core computation in greater generality. For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`, and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`, we produce a `k[G]`-linear retraction by taking the average over `G` of the conjugates of `π`. ## Future work It's not so far to give the usual statement, that every finite dimensional representation of a finite group is semisimple (i.e. a direct sum of irreducibles). -/ universes u noncomputable theory open module open monoid_algebra open_locale big_operators section -- At first we work with any `[comm_ring k]`, and add the assumption that -- `[invertible (fintype.card G : k)]` when it is required. variables {k : Type u} [comm_ring k] {G : Type u} [group G] variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V] variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W] /-! We now do the key calculation in Maschke's theorem. Given `V → W`, an inclusion of `k[G]` modules,, assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`), just as a `k`-linear map. (When `k` is a field, this will be available cheaply, by choosing a basis.) We now construct a retraction of the inclusion as a `k[G]`-linear map, by the formula $$ \frac{1}{|G|} \sum_{g \mem G} g⁻¹ • π(g • -). $$ -/ variables (π : (restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V)) include π /-- We define the conjugate of `π` by `g`, as a `k`-linear map. -/ def conjugate (g : G) : (restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) := ((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g) variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v) section include h lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v := begin dsimp [conjugate], simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv], change (1 : monoid_algebra k G) • v = v, simp, end end variables [fintype G] /-- The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map. (We postpone dividing by the size of the group as long as possible.) -/ def sum_of_conjugates : (restrict_scalars k (monoid_algebra k G) W) →ₗ[k] (restrict_scalars k (monoid_algebra k G) V) := ∑ g : G, conjugate π g /-- In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map. -/ def sum_of_conjugates_equivariant : W →ₗ[monoid_algebra k G] V := monoid_algebra.equivariant_of_linear_of_comm (sum_of_conjugates π) (λ g v, begin dsimp [sum_of_conjugates], simp only [linear_map.sum_apply, finset.smul_sum], dsimp [conjugate], conv_lhs { rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)], simp only [mul_right_embedding], }, simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk, finset.sum_map, inv_inv, inv_mul_cancel_right], end) section variables [inv : invertible (fintype.card G : k)] include inv section local attribute [instance] linear_map_algebra_module /-- We construct our `k[G]`-linear retraction of `i` as $$ \frac{1}{|G|} \sum_{g \mem G} g⁻¹ • π(g • -). $$ -/ def equivariant_projection : W →ₗ[monoid_algebra k G] V := ⅟(fintype.card G : k) • (sum_of_conjugates_equivariant π) end include h lemma equivariant_projection_condition (v : V) : (equivariant_projection π) (i v) = v := begin rw [equivariant_projection, linear_map_algebra_module.smul_apply, sum_of_conjugates_equivariant, equivariant_of_linear_of_comm_apply, sum_of_conjugates], rw [linear_map.sum_apply], simp only [conjugate_i π i h], rw [finset.sum_const, finset.card_univ, @semimodule.nsmul_eq_smul k _ (restrict_scalars k (monoid_algebra k G) V) _ _ (fintype.card G) v, ←mul_smul, invertible.inv_of_mul_self, one_smul], end end end -- Now we work over a `[field k]`, and replace the assumption `[invertible (fintype.card G : k)]` -- with `¬(ring_char k ∣ fintype.card G)`. variables {k : Type u} [field k] {G : Type u} [fintype G] [group G] variables {V : Type u} [add_comm_group V] [module (monoid_algebra k G) V] variables {W : Type u} [add_comm_group W] [module (monoid_algebra k G) W] lemma monoid_algebra.exists_left_inverse_of_injective (not_dvd : ¬(ring_char k ∣ fintype.card G)) (f : V →ₗ[monoid_algebra k G] W) (hf_inj : f.ker = ⊥) : ∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id := begin let E := linear_map.exists_left_inverse_of_injective (by convert f.restrict_scalars k) (by simp [hf_inj]), fsplit, haveI : invertible (fintype.card G : k) := invertible_of_ring_char_not_dvd not_dvd, exact equivariant_projection (classical.some E), { ext v, apply equivariant_projection_condition, intro v, have := classical.some_spec E, have := congr_arg linear_map.to_fun this, exact congr_fun this v, } end lemma monoid_algebra.submodule.exists_is_compl (not_dvd : ¬(ring_char k ∣ fintype.card G)) (p : submodule (monoid_algebra k G) V) : ∃ q : submodule (monoid_algebra k G) V, is_compl p q := let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective not_dvd p.subtype p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩