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
10c215b7a714208c9765cce116ece54ad4c739d1
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/algebra/basic.lean
b8e5192711f68a322208e0051284ee38a0c9ba8d
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,104
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.iterate_hom import data.equiv.ring_aut import linear_algebra.tensor_product import tactic.nth_rewrite /-! # Algebra over Commutative Semiring In this file we define `algebra`s over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`. We also define usual operations on `alg_hom`s (`id`, `comp`). `subalgebra`s are defined in `algebra.algebra.subalgebra`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. For the category of `R`-algebras, denoted `Algebra R`, see the file `algebra/category/Algebra/basic.lean`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ universes u v w u₁ v₁ open_locale tensor_product big_operators section prio -- We set this priority to 0 later in this file set_option extends_priority 200 /- control priority of `instance [algebra R A] : has_scalar R A` -/ /-- Given a commutative (semi)ring `R`, an `R`-algebra is a (possibly noncommutative) (semi)ring `A` endowed with a morphism of rings `R →+* A` which lands in the center of `A`. For convenience, this typeclass extends `has_scalar R A` where the scalar action must agree with left multiplication by the image of the structure morphism. Given an `algebra R A` instance, the structure morphism `R →+* A` is denoted `algebra_map R A`. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, to_ring_hom := i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ lemma ring_hom.algebra_map_to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : @algebra_map R S _ _ i.to_algebra = i := rfl namespace algebra variables {R : Type u} {S : Type v} {A : Type w} {B : Type*} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `module R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. See note [reducible non-instances]. -/ @[reducible] def of_module' [comm_semiring R] [semiring A] [module R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `module R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. See note [reducible non-instances]. -/ @[reducible] def of_module [comm_semiring R] [semiring A] [module R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_module' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] variables [semiring A] [algebra R A] [semiring B] [algebra R B] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra ℤ M` is a subsingleton. @[ext] lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A) (w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) : P = Q := begin unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ }, congr, { funext r a, replace w := congr_arg (λ s, s * a) (w r), simp only [←algebra.smul_def''] at w, apply w, }, { ext r, exact w r, }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, }, end @[priority 200] -- see Note [lower instance priority] instance to_module : module R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 := calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm ... = r • 1 : (algebra.smul_def r 1).symm lemma algebra_map_eq_smul_one' : ⇑(algebra_map R A) = λ r, r • (1 : A) := funext algebra_map_eq_smul_one /-- `mul_comm` for `algebra`s when one element is from the base ring. -/ theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x /-- `mul_left_comm` for `algebra`s when one element is from the base ring. -/ theorem left_comm (x : A) (r : R) (y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] /-- `mul_right_comm` for `algebra`s when one element is from the base ring. -/ theorem right_comm (x : A) (r : R) (y : A) : (x * algebra_map R A r) * y = (x * y) * algebra_map R A r := by rw [mul_assoc, commutes, ←mul_assoc] instance _root_.is_scalar_tower.right : is_scalar_tower R A A := ⟨λ x y z, by rw [smul_eq_mul, smul_eq_mul, smul_def, smul_def, mul_assoc]⟩ /-- This is just a special case of the global `mul_smul_comm` lemma that requires less typeclass search (and was here first). -/ @[simp] protected lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := -- TODO: set up `is_scalar_tower.smul_comm_class` earlier so that we can actually prove this using -- `mul_smul_comm s x y`. by rw [smul_def, smul_def, left_comm] /-- This is just a special case of the global `smul_mul_assoc` lemma that requires less typeclass search (and was here first). -/ @[simp] protected lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := smul_mul_assoc r x y instance _root_.is_scalar_tower.opposite_right : is_scalar_tower R Aᵒᵖ A := ⟨λ x y z, algebra.mul_smul_comm _ _ _⟩ section variables {r : R} {a : A} @[simp] lemma bit0_smul_one : bit0 r • (1 : A) = bit0 (r • (1 : A)) := by simp [bit0, add_smul] lemma bit0_smul_one' : bit0 r • (1 : A) = r • 2 := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) := by simp [bit0, add_smul, smul_add] @[simp] lemma bit1_smul_one : bit1 r • (1 : A) = bit1 (r • (1 : A)) := by simp [bit1, add_smul] lemma bit1_smul_one' : bit1 r • (1 : A) = r • 2 + 1 := by simp [bit1, bit0, add_smul, smul_add] @[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a := by simp [bit1, add_smul, smul_add] @[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a := by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel } end variables (R A) /-- The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map : R →ₗ[R] A := { map_smul' := λ x y, by simp [algebra.smul_def], ..algebra_map R A } @[simp] lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl instance id : algebra R R := (ring_hom.id R).to_algebra variables {R A} namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id section prod variables (R A B) instance : algebra R (A × B) := { commutes' := by { rintro r ⟨a, b⟩, dsimp, rw [commutes r a, commutes r b] }, smul_def' := by { rintro r ⟨a, b⟩, dsimp, rw [smul_def r a, smul_def r b] }, .. prod.module, .. ring_hom.prod (algebra_map R A) (algebra_map R B) } variables {R A B} @[simp] lemma algebra_map_prod_apply (r : R) : algebra_map R (A × B) r = (algebra_map R A r, algebra_map R B r) := rfl end prod /-- Algebra over a subsemiring. This builds upon `subsemiring.module`. -/ instance of_subsemiring (S : subsemiring R) : algebra S A := { smul := (•), commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp S.subtype } /-- Algebra over a subring. This builds upon `subring.module`. -/ instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subring R) : algebra S A := { smul := (•), .. algebra.of_subsemiring S.to_subsemiring, .. (algebra_map R A).comp S.subtype } lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S →+* R) = subring.subtype S := rfl lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S → R) = subtype.val := rfl lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) : algebra_map S R x = x := rfl /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S] (M : submonoid R) : (submonoid S) := submonoid.map (algebra_map R S : R →* S) M lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) : (algebra_map R S x) ∈ algebra_map_submonoid S M := set.mem_image_of_mem (algebra_map R S) x.2 end semiring section ring variables [comm_ring R] variables (R) /-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure. See note [reducible non-instances]. -/ @[reducible] def semiring_to_ring [semiring A] [algebra R A] : ring A := { ..module.add_comm_monoid_to_add_comm_group R, ..(infer_instance : semiring A) } variables {R} lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) : x * (x - algebra_map R A r) = (x - algebra_map R A r) * x := by rw [mul_sub, ←commutes, sub_mul] lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) : x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x := begin induction n with n ih, { simp }, { rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes, mul_assoc, ih, ←mul_assoc], } end end ring end algebra namespace no_zero_smul_divisors variables {R A : Type*} open algebra section ring variables [comm_ring R] /-- If `algebra_map R A` is injective and `A` has no zero divisors, `R`-multiples in `A` are zero only if one of the factors is zero. Cannot be an instance because there is no `injective (algebra_map R A)` typeclass. -/ lemma of_algebra_map_injective [semiring A] [algebra R A] [no_zero_divisors A] (h : function.injective (algebra_map R A)) : no_zero_smul_divisors R A := ⟨λ c x hcx, (mul_eq_zero.mp ((smul_def c x).symm.trans hcx)).imp_left ((algebra_map R A).injective_iff.mp h _)⟩ variables (R A) lemma algebra_map_injective [ring A] [nontrivial A] [algebra R A] [no_zero_smul_divisors R A] : function.injective (algebra_map R A) := suffices function.injective (λ (c : R), c • (1 : A)), by { convert this, ext, rw [algebra.smul_def, mul_one] }, smul_left_injective R one_ne_zero variables {R A} lemma iff_algebra_map_injective [domain A] [algebra R A] : no_zero_smul_divisors R A ↔ function.injective (algebra_map R A) := ⟨@@no_zero_smul_divisors.algebra_map_injective R A _ _ _ _, no_zero_smul_divisors.of_algebra_map_injective⟩ end ring section field variables [field R] [semiring A] [algebra R A] @[priority 100] -- see note [lower instance priority] instance algebra.no_zero_smul_divisors [nontrivial A] [no_zero_divisors A] : no_zero_smul_divisors R A := no_zero_smul_divisors.of_algebra_map_injective (algebra_map R A).injective end field end no_zero_smul_divisors namespace opposite variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R Aᵒᵖ := { to_ring_hom := (algebra_map R A).to_opposite $ λ x y, algebra.commutes _ _, smul_def' := λ c x, unop_injective $ by { dsimp, simp only [op_mul, algebra.smul_def, algebra.commutes, op_unop] }, commutes' := λ r, op_induction $ λ x, by dsimp; simp only [← op_mul, algebra.commutes], ..opposite.has_scalar A R } @[simp] lemma algebra_map_apply (c : R) : algebra_map R Aᵒᵖ c = op (algebra_map R A c) := rfl end opposite namespace module variables (R : Type u) (M : Type v) [comm_semiring R] [add_comm_monoid M] [module R M] instance endomorphism_algebra : algebra R (M →ₗ[R] M) := { to_fun := λ r, r • linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul _ _ _, map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } lemma algebra_map_End_eq_smul_id (a : R) : (algebra_map R (End R M)) a = a • linear_map.id := rfl @[simp] lemma algebra_map_End_apply (a : R) (m : M) : (algebra_map R (End R M)) a m = a • m := rfl @[simp] lemma ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [module K V] (a : K) (ha : a ≠ 0) : ((algebra_map K (End K V)) a).ker = ⊥ := linear_map.ker_smul _ _ ha end module set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ initialize_simps_projections alg_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl -- make the coercion the simp-normal form @[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ := by { cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x := H ▸ rfl protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y := h ▸ rfl @[ext] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_inj $ funext H theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := ⟨alg_hom.congr_fun, ext⟩ @[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) : (⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl @[simp] theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (∑ x in s, f x) = ∑ x in s, φ (f x) := φ.to_ring_hom.map_sum f s lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.sum g) = f.sum (λ i a, φ (g i a)) := φ.map_sum _ _ @[simp] lemma map_nat_cast (n : ℕ) : φ n = n := φ.to_ring_hom.map_nat_cast n @[simp] lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := φ.to_ring_hom.map_bit0 x @[simp] lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := φ.to_ring_hom.map_bit1 x /-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/ def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B := { to_fun := f, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one], .. f } @[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } @[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl @[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl end lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ[R] B := { to_fun := φ, map_add' := φ.map_add, map_smul' := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) := λ φ₁ φ₂ h, ext $ linear_map.congr_fun h @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl @[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id := linear_map.ext $ λ _, rfl /-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/ @[simps] def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) : A →ₐ[R] B := { to_fun := f, map_one' := map_one, map_mul' := map_mul, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one], .. f.to_add_monoid_hom } @[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) : of_linear_map φ.to_linear_map map_one map_mul = φ := by { ext, refl } @[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) : to_linear_map (of_linear_map f map_one map_mul) = f := by { ext, refl } @[simp] lemma of_linear_map_id (map_one) (map_mul) : of_linear_map linear_map.id map_one map_mul = alg_hom.id R A := ext $ λ _, rfl lemma map_list_prod (s : list A) : φ s.prod = (s.map φ).prod := φ.to_ring_hom.map_list_prod s section prod /-- First projection as `alg_hom`. -/ def fst : A × B →ₐ[R] A := { commutes' := λ r, rfl, .. ring_hom.fst A B} /-- Second projection as `alg_hom`. -/ def snd : A × B →ₐ[R] B := { commutes' := λ r, rfl, .. ring_hom.snd A B} end prod lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) : algebra_map R B y = f x := h ▸ (f.commutes _).symm end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) lemma map_multiset_prod (s : multiset A) : φ s.prod = (s.map φ).prod := φ.to_ring_hom.map_multiset_prod s lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (∏ x in s, f x) = ∏ x in s, φ (f x) := φ.to_ring_hom.map_prod f s lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.prod g) = f.prod (λ i a, φ (g i a)) := φ.map_prod _ _ end comm_semiring section ring variables [comm_semiring R] [ring A] [ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y @[simp] lemma map_int_cast (n : ℤ) : φ n = n := φ.to_ring_hom.map_int_cast n end ring section division_ring variables [comm_ring R] [division_ring A] [division_ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) @[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ := φ.to_ring_hom.map_inv x @[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y := φ.to_ring_hom.map_div x y end division_ring theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : function.injective f ↔ (∀ x, f x = 0 → x = 0) := ring_hom.injective_iff (f : A →+* B) end alg_hom @[simp] lemma rat.smul_one_eq_coe {A : Type*} [division_ring A] [algebra ℚ A] (m : ℚ) : m • (1 : A) = ↑m := by rw [algebra.smul_def, mul_one, ring_hom.eq_rat_cast] set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} section semiring variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] variables (e : A₁ ≃ₐ[R] A₂) instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end protected lemma congr_arg {f : A₁ ≃ₐ[R] A₂} : Π {x x' : A₁}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : A₁ ≃ₐ[R] A₂} (h : f = g) (x : A₁) : f x = g x := h ▸ rfl lemma ext_iff {f g : A₁ ≃ₐ[R] A₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) := begin intros f g w, ext, exact congr_fun w a, end instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp] lemma coe_mk {to_fun inv_fun left_inv right_inv map_mul map_add commutes} : ⇑(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) = to_fun := rfl @[simp] theorem mk_coe (e : A₁ ≃ₐ[R] A₂) (e' h₁ h₂ h₃ h₄ h₅) : (⟨e, e', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂) = e := ext $ λ _, rfl @[simp] lemma to_fun_eq_coe (e : A₁ ≃ₐ[R] A₂) : e.to_fun = e := rfl -- TODO: decide on a simp-normal form so that only one of these two lemmas is needed @[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl @[simp] lemma coe_ring_equiv' : (e.to_ring_equiv : A₁ → A₂) = e := rfl lemma coe_ring_equiv_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ ≃+* A₂)) := λ e₁ e₂ h, ext $ ring_equiv.congr_fun h @[simp] lemma map_add : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' lemma map_sum {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∑ x in s, f x) = ∑ x in s, e (f x) := e.to_add_equiv.map_sum f s lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) : e (f.sum g) = f.sum (λ i b, e (g i b)) := e.map_sum _ _ /-- Interpret an algebra equivalence as an algebra homomorphism. This definition is included for symmetry with the other `to_*_hom` projections. The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/ def to_alg_hom : A₁ →ₐ[R] A₂ := { map_one' := e.map_one, map_zero' := e.map_zero, ..e } instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨to_alg_hom⟩ @[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl @[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma coe_alg_hom_injective : function.injective (coe : (A₁ ≃ₐ[R] A₂) → (A₁ →ₐ[R] A₂)) := λ e₁ e₂ h, ext $ alg_hom.congr_fun h /-- The two paths coercion can take to a `ring_hom` are equivalent -/ lemma coe_ring_hom_commutes : ((e : A₁ →ₐ[R] A₂) : A₁ →+* A₂) = ((e : A₁ ≃+* A₂) : A₁ →+* A₂) := rfl @[simp] lemma map_pow : ∀ (x : A₁) (n : ℕ), e (x ^ n) = (e x) ^ n := e.to_alg_hom.map_pow lemma injective : function.injective e := e.to_equiv.injective lemma surjective : function.surjective e := e.to_equiv.surjective lemma bijective : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 @[simp] lemma refl_to_alg_hom : ↑(refl : A₁ ≃ₐ[R] A₁) = alg_hom.id R A₁ := rfl @[simp] lemma coe_refl : ⇑(refl : A₁ ≃ₐ[R] A₁) = id := rfl /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } /-- See Note [custom simps projection] -/ def simps.symm_apply (e : A₁ ≃ₐ[R] A₂) : A₂ → A₁ := e.symm initialize_simps_projections alg_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm {e : A₁ ≃ₐ[R] A₂} : e.inv_fun = e.symm := rfl @[simp] lemma symm_symm (e : A₁ ≃ₐ[R] A₂) : e.symm.symm = e := by { ext, refl, } lemma symm_bijective : function.bijective (symm : (A₁ ≃ₐ[R] A₂) → (A₂ ≃ₐ[R] A₁)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : A₁ ≃ₐ[R] A₂) (f h₁ h₂ h₃ h₄ h₅) : (⟨f, e, h₁, h₂, h₃, h₄, h₅⟩ : A₂ ≃ₐ[R] A₁) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f f') (h₁ h₂ h₃ h₄ h₅) : (⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm = { to_fun := f', inv_fun := f, ..(⟨f, f', h₁, h₂, h₃, h₄, h₅⟩ : A₁ ≃ₐ[R] A₂).symm } := rfl /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp] lemma coe_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ := by { ext, simp } @[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ := by { ext, simp } theorem left_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.left_inverse e.symm e := e.left_inv theorem right_inverse_symm (e : A₁ ≃ₐ[R] A₂) : function.right_inverse e.symm e := e.right_inv /-- If `A₁` is equivalent to `A₁'` and `A₂` is equivalent to `A₂'`, then the type of maps `A₁ →ₐ[R] A₂` is equivalent to the type of maps `A₁' →ₐ[R] A₂'`. -/ def arrow_congr {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (A₁ →ₐ[R] A₂) ≃ (A₁' →ₐ[R] A₂') := { to_fun := λ f, (e₂.to_alg_hom.comp f).comp e₁.symm.to_alg_hom, inv_fun := λ f, (e₂.symm.to_alg_hom.comp f).comp e₁.to_alg_hom, left_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, symm_comp], simp only [←alg_hom.comp_assoc, symm_comp, alg_hom.id_comp, alg_hom.comp_id] }, right_inv := λ f, by { simp only [alg_hom.comp_assoc, to_alg_hom_eq_coe, comp_symm], simp only [←alg_hom.comp_assoc, comp_symm, alg_hom.id_comp, alg_hom.comp_id] } } lemma arrow_congr_comp {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') (e₃ : A₃ ≃ₐ[R] A₃') (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [arrow_congr, equiv.coe_fn_mk, alg_hom.comp_apply], congr, exact (e₂.symm_apply_apply _).symm } @[simp] lemma arrow_congr_refl : arrow_congr alg_equiv.refl alg_equiv.refl = equiv.refl (A₁ →ₐ[R] A₂) := by { ext, refl } @[simp] lemma arrow_congr_trans {A₁' A₂' A₃' : Type*} [semiring A₁'] [semiring A₂'] [semiring A₃'] [algebra R A₁'] [algebra R A₂'] [algebra R A₃'] (e₁ : A₁ ≃ₐ[R] A₂) (e₁' : A₁' ≃ₐ[R] A₂') (e₂ : A₂ ≃ₐ[R] A₃) (e₂' : A₂' ≃ₐ[R] A₃') : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := by { ext, refl } @[simp] lemma arrow_congr_symm {A₁' A₂' : Type*} [semiring A₁'] [semiring A₂'] [algebra R A₁'] [algebra R A₂'] (e₁ : A₁ ≃ₐ[R] A₁') (e₂ : A₂ ≃ₐ[R] A₂') : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := by { ext, refl } /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ := { to_fun := f, inv_fun := g, left_inv := alg_hom.ext_iff.1 h₂, right_inv := alg_hom.ext_iff.1 h₁, ..f } lemma coe_alg_hom_of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : ↑(of_alg_hom f g h₁ h₂) = f := alg_hom.ext $ λ _, rfl @[simp] lemma of_alg_hom_coe_alg_hom (f : A₁ ≃ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : of_alg_hom ↑f g h₁ h₂ = f := ext $ λ _, rfl lemma of_alg_hom_symm (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ h₂) : (of_alg_hom f g h₁ h₂).symm = of_alg_hom g f h₂ h₁ := rfl /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ := { .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f } /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ @[simps apply] def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ := { to_fun := e, map_smul' := λ r x, by simp [algebra.smul_def''], inv_fun := e.symm, .. e } @[simp] lemma to_linear_equiv_refl : (alg_equiv.refl : A₁ ≃ₐ[R] A₁).to_linear_equiv = linear_equiv.refl R A₁ := rfl @[simp] lemma to_linear_equiv_symm (e : A₁ ≃ₐ[R] A₂) : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl @[simp] lemma to_linear_equiv_trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := rfl theorem to_linear_equiv_injective : function.injective (to_linear_equiv : _ → (A₁ ≃ₗ[R] A₂)) := λ e₁ e₂ h, ext $ linear_equiv.congr_fun h /-- Interpret an algebra equivalence as a linear map. -/ def to_linear_map : A₁ →ₗ[R] A₂ := e.to_alg_hom.to_linear_map @[simp] lemma to_alg_hom_to_linear_map : (e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_equiv_to_linear_map : e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A₁ →ₗ[R] A₂)) := λ e₁ e₂ h, ext $ linear_map.congr_fun h @[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) : (f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl section of_linear_equiv variables (l : A₁ ≃ₗ[R] A₂) (map_mul : ∀ x y : A₁, l (x * y) = l x * l y) (commutes : ∀ r : R, l (algebra_map R A₁ r) = algebra_map R A₂ r) /-- Upgrade a linear equivalence to an algebra equivalence, given that it distributes over multiplication and action of scalars. -/ @[simps apply] def of_linear_equiv : A₁ ≃ₐ[R] A₂ := { to_fun := l, inv_fun := l.symm, map_mul' := map_mul, commutes' := commutes, ..l } @[simp] lemma of_linear_equiv_symm : (of_linear_equiv l map_mul commutes).symm = of_linear_equiv l.symm ((of_linear_equiv l map_mul commutes).symm.map_mul) ((of_linear_equiv l map_mul commutes).symm.commutes) := rfl @[simp] lemma of_linear_equiv_to_linear_equiv (map_mul) (commutes) : of_linear_equiv e.to_linear_equiv map_mul commutes = e := by { ext, refl } @[simp] lemma to_linear_equiv_of_linear_equiv : to_linear_equiv (of_linear_equiv l map_mul commutes) = l := by { ext, refl } end of_linear_equiv instance aut : group (A₁ ≃ₐ[R] A₁) := { mul := λ ϕ ψ, ψ.trans ϕ, mul_assoc := λ ϕ ψ χ, rfl, one := 1, one_mul := λ ϕ, by { ext, refl }, mul_one := λ ϕ, by { ext, refl }, inv := symm, mul_left_inv := λ ϕ, by { ext, exact symm_apply_apply ϕ a } } @[simp] lemma mul_apply (e₁ e₂ : A₁ ≃ₐ[R] A₁) (x : A₁) : (e₁ * e₂) x = e₁ (e₂ x) := rfl /-- An algebra isomorphism induces a group isomorphism between automorphism groups -/ @[simps apply] def aut_congr (ϕ : A₁ ≃ₐ[R] A₂) : (A₁ ≃ₐ[R] A₁) ≃* (A₂ ≃ₐ[R] A₂) := { to_fun := λ ψ, ϕ.symm.trans (ψ.trans ϕ), inv_fun := λ ψ, ϕ.trans (ψ.trans ϕ.symm), left_inv := λ ψ, by { ext, simp_rw [trans_apply, symm_apply_apply] }, right_inv := λ ψ, by { ext, simp_rw [trans_apply, apply_symm_apply] }, map_mul' := λ ψ χ, by { ext, simp only [mul_apply, trans_apply, symm_apply_apply] } } @[simp] lemma aut_congr_refl : aut_congr (alg_equiv.refl) = mul_equiv.refl (A₁ ≃ₐ[R] A₁) := by { ext, refl } @[simp] lemma aut_congr_symm (ϕ : A₁ ≃ₐ[R] A₂) : (aut_congr ϕ).symm = aut_congr ϕ.symm := rfl @[simp] lemma aut_congr_trans (ϕ : A₁ ≃ₐ[R] A₂) (ψ : A₂ ≃ₐ[R] A₃) : (aut_congr ϕ).trans (aut_congr ψ) = aut_congr (ϕ.trans ψ) := rfl /-- The tautological action by `A₁ ≃ₐ[R] A₁` on `A₁`. This generalizes `function.End.apply_mul_action`. -/ instance apply_mul_semiring_action : mul_semiring_action (A₁ ≃ₐ[R] A₁) A₁ := { smul := ($), smul_zero := alg_equiv.map_zero, smul_add := alg_equiv.map_add, smul_one := alg_equiv.map_one, smul_mul := alg_equiv.map_mul, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : A₁ ≃ₐ[R] A₁) (a : A₁) : f • a = f a := rfl instance apply_has_faithful_scalar : has_faithful_scalar (A₁ ≃ₐ[R] A₁) A₁ := ⟨λ _ _, alg_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (A₁ ≃ₐ[R] A₁) A₁ := { smul_comm := λ r e a, (e.to_linear_equiv.map_smul r a).symm } instance apply_smul_comm_class' : smul_comm_class (A₁ ≃ₐ[R] A₁) R A₁ := { smul_comm := λ e r a, (e.to_linear_equiv.map_smul r a) } @[simp] lemma algebra_map_eq_apply (e : A₁ ≃ₐ[R] A₂) {y : R} {x : A₁} : (algebra_map R A₂ y = e x) ↔ (algebra_map R A₁ y = x) := ⟨λ h, by simpa using e.symm.to_alg_hom.algebra_map_eq_apply h, λ h, e.to_alg_hom.algebra_map_eq_apply h⟩ end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A₁] [comm_semiring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) lemma map_prod {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∏ x in s, f x) = ∏ x in s, e (f x) := e.to_alg_hom.map_prod f s lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A₁) : e (f.prod g) = f.prod (λ i a, e (g i a)) := e.to_alg_hom.map_finsupp_prod f g end comm_semiring section ring variables [comm_ring R] [ring A₁] [ring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) @[simp] lemma map_neg (x) : e (-x) = -e x := e.to_alg_hom.map_neg x @[simp] lemma map_sub (x y) : e (x - y) = e x - e y := e.to_alg_hom.map_sub x y end ring section division_ring variables [comm_ring R] [division_ring A₁] [division_ring A₂] variables [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) @[simp] lemma map_inv (x) : e (x⁻¹) = (e x)⁻¹ := e.to_alg_hom.map_inv x @[simp] lemma map_div (x y) : e (x / y) = e x / e y := e.to_alg_hom.map_div x y end division_ring end alg_equiv namespace mul_semiring_action variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A] section variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A] /-- Each element of the monoid defines a algebra homomorphism. This is a stronger version of `mul_semiring_action.to_ring_hom` and `distrib_mul_action.to_linear_map`. -/ @[simps] def to_alg_hom (m : M) : A →ₐ[R] A := alg_hom.mk' (mul_semiring_action.to_ring_hom _ _ m) (smul_comm _) theorem to_alg_hom_injective [has_faithful_scalar M A] : function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r end section variables [group G] [mul_semiring_action G A] [smul_comm_class G R A] /-- Each element of the group defines a algebra equivalence. This is a stronger version of `mul_semiring_action.to_ring_equiv` and `distrib_mul_action.to_linear_equiv`. -/ @[simps] def to_alg_equiv (g : G) : A ≃ₐ[R] A := { .. mul_semiring_action.to_ring_equiv _ _ g, .. mul_semiring_action.to_alg_hom R A g } theorem to_alg_equiv_injective [has_faithful_scalar G A] : function.injective (mul_semiring_action.to_alg_equiv R A : G → A ≃ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_equiv.ext_iff.1 h r end end mul_semiring_action section nat variables {R : Type*} [semiring R] -- Lower the priority so that `algebra.id` is picked most of the time when working with -- `ℕ`-algebras. This is only an issue since `algebra.id` and `algebra_nat` are not yet defeq. -- TODO: fix this by adding an `of_nat` field to semirings. /-- Semiring ⥤ ℕ-Alg -/ @[priority 99] instance algebra_nat : algebra ℕ R := { commutes' := nat.cast_commute, smul_def' := λ _ _, nsmul_eq_mul _ _, to_ring_hom := nat.cast_ring_hom R } instance nat_algebra_subsingleton : subsingleton (algebra ℕ R) := ⟨λ P Q, by { ext, simp, }⟩ end nat namespace ring_hom variables {R S : Type*} /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) : R →ₐ[ℕ] S := { to_fun := f, commutes' := λ n, by simp, .. f } /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ n, by simp, .. f } @[simp] lemma map_rat_algebra_map [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) (r : ℚ) : f (algebra_map ℚ R r) = algebra_map ℚ S r := ring_hom.ext_iff.1 (subsingleton.elim (f.comp (algebra_map ℚ R)) (algebra_map ℚ S)) r /-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. -/ def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : R →ₐ[ℚ] S := { commutes' := f.map_rat_algebra_map, .. f } end ring_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x @[simp] theorem algebra_map_rat_rat : algebra_map ℚ ℚ = ring_hom.id ℚ := subsingleton.elim _ _ -- TODO[gh-6025]: make this an instance once safe to do so lemma algebra_rat_subsingleton {α} [semiring α] : subsingleton (algebra ℚ α) := ⟨λ x y, algebra.algebra_ext x y $ ring_hom.congr_fun $ subsingleton.elim _ _⟩ end rat namespace char_zero variables {R : Type*} (S : Type*) [comm_semiring R] [semiring S] [algebra R S] lemma of_algebra [char_zero S] : char_zero R := ⟨begin suffices : function.injective (algebra_map R S ∘ coe), { exact this.of_comp }, convert char_zero.cast_injective, ext n, rw [function.comp_app, ← (algebra_map ℕ _).eq_nat_cast, ← ring_hom.comp_apply, ring_hom.eq_nat_cast], all_goals { apply_instance } end⟩ end char_zero namespace algebra open module variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl variables (R A) /-- The multiplication in an algebra is a bilinear map. A weaker version of this for semirings exists as `add_monoid_hom.mul`. -/ def lmul : A →ₐ[R] (End R A) := { map_one' := by { ext a, exact one_mul a }, map_mul' := by { intros a b, ext c, exact mul_assoc a b c }, map_zero' := by { ext a, exact zero_mul a }, commutes' := by { intro r, ext a, dsimp, rw [smul_def] }, .. (show A →ₗ[R] A →ₗ[R] A, from linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm])) } variables {A} /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A →ₗ[R] A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A →ₗ[R] A := (lmul R A).to_linear_map.flip r /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (vw: A × A) : A →ₗ[R] A := (lmul_right R vw.2).comp (lmul_left R vw.1) /-- The multiplication map on an algebra, as an `R`-linear map from `A ⊗[R] A` to `A`. -/ def lmul' : A ⊗[R] A →ₗ[R] A := tensor_product.lift (lmul R A).to_linear_map lemma commute_lmul_left_right (a b : A) : commute (lmul_left R a) (lmul_right R b) := by { ext c, exact (mul_assoc a c b).symm, } variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R p q = q * p := rfl @[simp] lemma lmul_left_right_apply (vw : A × A) (p : A) : lmul_left_right R vw p = vw.1 * p * vw.2 := rfl @[simp] lemma lmul_left_one : lmul_left R (1:A) = linear_map.id := by { ext, simp only [linear_map.id_coe, one_mul, id.def, lmul_left_apply] } @[simp] lemma lmul_left_mul (a b : A) : lmul_left R (a * b) = (lmul_left R a).comp (lmul_left R b) := by { ext, simp only [lmul_left_apply, linear_map.comp_apply, mul_assoc] } @[simp] lemma lmul_right_one : lmul_right R (1:A) = linear_map.id := by { ext, simp only [linear_map.id_coe, mul_one, id.def, lmul_right_apply] } @[simp] lemma lmul_right_mul (a b : A) : lmul_right R (a * b) = (lmul_right R b).comp (lmul_right R a) := by { ext, simp only [lmul_right_apply, linear_map.comp_apply, mul_assoc] } @[simp] lemma lmul_left_zero_eq_zero : lmul_left R (0 : A) = 0 := (lmul R A).map_zero @[simp] lemma lmul_right_zero_eq_zero : lmul_right R (0 : A) = 0 := (lmul R A).to_linear_map.flip.map_zero @[simp] lemma lmul_left_eq_zero_iff (a : A) : lmul_left R a = 0 ↔ a = 0 := begin split; intros h, { rw [← mul_one a, ← lmul_left_apply a 1, h, linear_map.zero_apply], }, { rw h, exact lmul_left_zero_eq_zero, }, end @[simp] lemma lmul_right_eq_zero_iff (a : A) : lmul_right R a = 0 ↔ a = 0 := begin split; intros h, { rw [← one_mul a, ← lmul_right_apply a 1, h, linear_map.zero_apply], }, { rw h, exact lmul_right_zero_eq_zero, }, end @[simp] lemma pow_lmul_left (a : A) (n : ℕ) : (lmul_left R a) ^ n = lmul_left R (a ^ n) := ((lmul R A).map_pow a n).symm @[simp] lemma pow_lmul_right (a : A) (n : ℕ) : (lmul_right R a) ^ n = lmul_right R (a ^ n) := linear_map.coe_injective $ ((lmul_right R a).coe_pow n).symm ▸ (mul_right_iterate a n) @[simp] lemma lmul'_apply {x y : A} : lmul' R (x ⊗ₜ y) = x * y := by simp only [algebra.lmul', tensor_product.lift.tmul, alg_hom.to_linear_map_apply, lmul_apply] instance linear_map.module' (R : Type u) [comm_semiring R] (M : Type v) [add_comm_monoid M] [module R M] (S : Type w) [comm_semiring S] [algebra R S] : module S (M →ₗ[R] S) := { smul := λ s f, linear_map.llcomp _ _ _ _ (algebra.lmul R S s) f, one_smul := λ f, linear_map.ext $ λ x, one_mul _, mul_smul := λ s₁ s₂ f, linear_map.ext $ λ x, mul_assoc _ _ _, smul_add := λ s f g, linear_map.map_add _ _ _, smul_zero := λ s, linear_map.map_zero _, add_smul := λ s₁ s₂ f, linear_map.ext $ λ x, add_mul _ _ _, zero_smul := λ f, linear_map.ext $ λ x, zero_mul _ } end algebra section ring namespace algebra variables {R A : Type*} [comm_semiring R] [ring A] [algebra R A] lemma lmul_left_injective [no_zero_divisors A] {x : A} (hx : x ≠ 0) : function.injective (lmul_left R x) := by { letI : domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..‹ring A›, ..‹no_zero_divisors A› }, exact mul_right_injective' hx } lemma lmul_right_injective [no_zero_divisors A] {x : A} (hx : x ≠ 0) : function.injective (lmul_right R x) := by { letI : domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..‹ring A›, ..‹no_zero_divisors A› }, exact mul_left_injective' hx } lemma lmul_injective [no_zero_divisors A] {x : A} (hx : x ≠ 0) : function.injective (lmul R A x) := by { letI : domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..‹ring A›, ..‹no_zero_divisors A› }, exact mul_right_injective' hx } end algebra end ring section int variables (R : Type*) [ring R] -- Lower the priority so that `algebra.id` is picked most of the time when working with -- `ℤ`-algebras. This is only an issue since `algebra.id ℤ` and `algebra_int ℤ` are not yet defeq. -- TODO: fix this by adding an `of_int` field to rings. /-- Ring ⥤ ℤ-Alg -/ @[priority 99] instance algebra_int : algebra ℤ R := { commutes' := int.cast_commute, smul_def' := λ _ _, gsmul_eq_mul _ _, to_ring_hom := int.cast_ring_hom R } variables {R} instance int_algebra_subsingleton : subsingleton (algebra ℤ R) := ⟨λ P Q, by { ext, simp, }⟩ end int /-! The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi variable {I : Type u} -- The indexing type variable {R : Type*} -- The scalar type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) variables (I f) instance algebra {r : comm_semiring R} [s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] : algebra R (Π i : I, f i) := { commutes' := λ a f, begin ext, simp [algebra.commutes], end, smul_def' := λ a f, begin ext, simp [algebra.smul_def''], end, ..(pi.ring_hom (λ i, algebra_map R (f i)) : R →+* Π i : I, f i) } @[simp] lemma algebra_map_apply {r : comm_semiring R} [s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) (i : I) : algebra_map R (Π i, f i) a i = algebra_map R (f i) a := rfl -- One could also build a `Π i, R i`-algebra structure on `Π i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. variables {I} (R) (f) /-- `function.eval` as an `alg_hom`. The name matches `pi.eval_ring_hom`, `pi.eval_monoid_hom`, etc. -/ @[simps] def eval_alg_hom {r : comm_semiring R} [Π i, semiring (f i)] [Π i, algebra R (f i)] (i : I) : (Π i, f i) →ₐ[R] f i := { to_fun := λ f, f i, commutes' := λ r, rfl, .. pi.eval_ring_hom f i} variables (A B : Type*) [comm_semiring R] [semiring B] [algebra R B] /-- `function.const` as an `alg_hom`. The name matches `pi.const_ring_hom`, `pi.const_monoid_hom`, etc. -/ @[simps] def const_alg_hom : B →ₐ[R] (A → B) := { to_fun := function.const _, commutes' := λ r, rfl, .. pi.const_ring_hom A B} /-- When `R` is commutative and permits an `algebra_map`, `pi.const_ring_hom` is equal to that map. -/ @[simp] lemma const_ring_hom_eq_algebra_map : const_ring_hom A R = algebra_map R (A → R) := rfl @[simp] lemma const_alg_hom_eq_algebra_of_id : const_alg_hom R A R = algebra.of_id R (A → R) := rfl end pi section is_scalar_tower variables {R : Type*} [comm_semiring R] variables (A : Type*) [semiring A] [algebra R A] variables {M : Type*} [add_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M] variables {N : Type*} [add_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N] lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m := by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul] @[simp] lemma algebra_map_smul (r : R) (m : M) : ((algebra_map R A) r) • m = r • m := (algebra_compatible_smul A r m).symm variable {A} @[priority 100] -- see Note [lower instance priority] instance is_scalar_tower.to_smul_comm_class : smul_comm_class R A M := ⟨λ r a m, by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul]⟩ @[priority 100] -- see Note [lower instance priority] instance is_scalar_tower.to_smul_comm_class' : smul_comm_class A R M := smul_comm_class.symm _ _ _ lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m := smul_comm _ _ _ namespace linear_map instance coe_is_scalar_tower : has_coe (M →ₗ[A] N) (M →ₗ[R] N) := ⟨restrict_scalars R⟩ variables (R) {A M N} @[simp, norm_cast squash] lemma coe_restrict_scalars_eq_coe (f : M →ₗ[A] N) : (f.restrict_scalars R : M → N) = f := rfl @[simp, norm_cast squash] lemma coe_coe_is_scalar_tower (f : M →ₗ[A] N) : ((f : M →ₗ[R] N) : M → N) = f := rfl /-- `A`-linearly coerce a `R`-linear map from `M` to `A` to a function, given an algebra `A` over a commutative semiring `R` and `M` a module over `R`. -/ def lto_fun (R : Type u) (M : Type v) (A : Type w) [comm_semiring R] [add_comm_monoid M] [module R M] [comm_ring A] [algebra R A] : (M →ₗ[R] A) →ₗ[A] (M → A) := { to_fun := linear_map.to_fun, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } end linear_map end is_scalar_tower /-! TODO: The following lemmas no longer involve `algebra` at all, and could be moved closer to `algebra/module/submodule.lean`. Currently this is tricky because `ker`, `range`, `⊤`, and `⊥` are all defined in `linear_algebra/basic.lean`. -/ section module open module variables (R S M N : Type*) [semiring R] [semiring S] [has_scalar R S] variables [add_comm_monoid M] [module R M] [module S M] [is_scalar_tower R S M] variables [add_comm_monoid N] [module R N] [module S N] [is_scalar_tower R S N] variables {S M N} namespace submodule variables (R S M) /-- If `S` is an `R`-algebra, then the `R`-module generated by a set `X` is included in the `S`-module generated by `X`. -/ lemma span_le_restrict_scalars (X : set M) : span R (X : set M) ≤ restrict_scalars R (span S X) := submodule.span_le.mpr submodule.subset_span end submodule @[simp] lemma linear_map.ker_restrict_scalars (f : M →ₗ[S] N) : (f.restrict_scalars R).ker = f.ker.restrict_scalars R := rfl end module namespace submodule variables (R A M : Type*) variables [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] variables [module R M] [module A M] [is_scalar_tower R A M] /-- If `A` is an `R`-algebra such that the induced morhpsim `R →+* A` is surjective, then the `R`-module generated by a set `X` equals the `A`-module generated by `X`. -/ lemma span_eq_restrict_scalars (X : set M) (hsur : function.surjective (algebra_map R A)) : span R X = restrict_scalars R (span A X) := begin apply (span_le_restrict_scalars R A M X).antisymm (λ m hm, _), refine span_induction hm subset_span (zero_mem _) (λ _ _, add_mem _) (λ a m hm, _), obtain ⟨r, rfl⟩ := hsur a, simpa [algebra_map_smul] using smul_mem _ r hm end end submodule namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {I : Type*} variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] /-- `R`-algebra homomorphism between the function spaces `I → A` and `I → B`, induced by an `R`-algebra homomorphism `f` between `A` and `B`. -/ @[simps] protected def comp_left (f : A →ₐ[R] B) (I : Type*) : (I → A) →ₐ[R] (I → B) := { to_fun := λ h, f ∘ h, commutes' := λ c, by { ext, exact f.commutes' c }, .. f.to_ring_hom.comp_left I } end alg_hom
a916c9a127c17ce7631f13b630d3a346c6f4c780
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/hom/group_action.lean
55bc58e2807212b7b1833425511bbeb4f754362a
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
11,321
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.group_ring_action import group_theory.group_action.defs /-! # Equivariant homomorphisms ## Main definitions * `mul_action_hom M X Y`, the type of equivariant functions from `X` to `Y`, where `M` is a monoid that acts on the types `X` and `Y`. * `distrib_mul_action_hom M A B`, the type of equivariant additive monoid homomorphisms from `A` to `B`, where `M` is a monoid that acts on the additive monoids `A` and `B`. * `mul_semiring_action_hom M R S`, the type of equivariant ring homomorphisms from `R` to `S`, where `M` is a monoid that acts on the rings `R` and `S`. ## Notations * `X →[M] Y` is `mul_action_hom M X Y`. * `A →+[M] B` is `distrib_mul_action_hom M X Y`. * `R →+*[M] S` is `mul_semiring_action_hom M X Y`. -/ variables (M' : Type*) variables (X : Type*) [has_scalar M' X] variables (Y : Type*) [has_scalar M' Y] variables (Z : Type*) [has_scalar M' Z] variables (M : Type*) [monoid M] variables (A : Type*) [add_monoid A] [distrib_mul_action M A] variables (A' : Type*) [add_group A'] [distrib_mul_action M A'] variables (B : Type*) [add_monoid B] [distrib_mul_action M B] variables (B' : Type*) [add_group B'] [distrib_mul_action M B'] variables (C : Type*) [add_monoid C] [distrib_mul_action M C] variables (R : Type*) [semiring R] [mul_semiring_action M R] variables (R' : Type*) [ring R'] [mul_semiring_action M R'] variables (S : Type*) [semiring S] [mul_semiring_action M S] variables (S' : Type*) [ring S'] [mul_semiring_action M S'] variables (T : Type*) [semiring T] [mul_semiring_action M T] variables (G : Type*) [group G] (H : subgroup G) set_option old_structure_cmd true /-- Equivariant functions. -/ @[nolint has_inhabited_instance] structure mul_action_hom := (to_fun : X → Y) (map_smul' : ∀ (m : M') (x : X), to_fun (m • x) = m • to_fun x) notation X ` →[`:25 M:25 `] `:0 Y:0 := mul_action_hom M X Y namespace mul_action_hom instance : has_coe_to_fun (X →[M'] Y) (λ _, X → Y) := ⟨mul_action_hom.to_fun⟩ variables {M M' X Y} @[simp] lemma map_smul (f : X →[M'] Y) (m : M') (x : X) : f (m • x) = m • f x := f.map_smul' m x @[ext] theorem ext : ∀ {f g : X →[M'] Y}, (∀ x, f x = g x) → f = g | ⟨f, _⟩ ⟨g, _⟩ H := by { congr' 1 with x, exact H x } theorem ext_iff {f g : X →[M'] Y} : f = g ↔ ∀ x, f x = g x := ⟨λ H x, by rw H, ext⟩ protected lemma congr_fun {f g : X →[M'] Y} (h : f = g) (x : X) : f x = g x := h ▸ rfl variables (M M') {X} /-- The identity map as an equivariant map. -/ protected def id : X →[M'] X := ⟨id, λ _ _, rfl⟩ @[simp] lemma id_apply (x : X) : mul_action_hom.id M' x = x := rfl variables {M M' X Y Z} /-- Composition of two equivariant maps. -/ def comp (g : Y →[M'] Z) (f : X →[M'] Y) : X →[M'] Z := ⟨g ∘ f, λ m x, calc g (f (m • x)) = g (m • f x) : by rw f.map_smul ... = m • g (f x) : g.map_smul _ _⟩ @[simp] lemma comp_apply (g : Y →[M'] Z) (f : X →[M'] Y) (x : X) : g.comp f x = g (f x) := rfl @[simp] lemma id_comp (f : X →[M'] Y) : (mul_action_hom.id M').comp f = f := ext $ λ x, by rw [comp_apply, id_apply] @[simp] lemma comp_id (f : X →[M'] Y) : f.comp (mul_action_hom.id M') = f := ext $ λ x, by rw [comp_apply, id_apply] variables {A B} /-- The inverse of a bijective equivariant map is equivariant. -/ @[simps] def inverse (f : A →[M] B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →[M] A := { to_fun := g, map_smul' := λ m x, calc g (m • x) = g (m • (f (g x))) : by rw h₂ ... = g (f (m • (g x))) : by rw f.map_smul ... = m • g x : by rw h₁, } end mul_action_hom /-- Equivariant additive monoid homomorphisms. -/ structure distrib_mul_action_hom extends A →[M] B, A →+ B. /-- Reinterpret an equivariant additive monoid homomorphism as an additive monoid homomorphism. -/ add_decl_doc distrib_mul_action_hom.to_add_monoid_hom /-- Reinterpret an equivariant additive monoid homomorphism as an equivariant function. -/ add_decl_doc distrib_mul_action_hom.to_mul_action_hom notation A ` →+[`:25 M:25 `] `:0 B:0 := distrib_mul_action_hom M A B namespace distrib_mul_action_hom instance has_coe : has_coe (A →+[M] B) (A →+ B) := ⟨to_add_monoid_hom⟩ instance has_coe' : has_coe (A →+[M] B) (A →[M] B) := ⟨to_mul_action_hom⟩ instance : has_coe_to_fun (A →+[M] B) (λ _, A → B) := ⟨to_fun⟩ variables {M A B} @[simp] lemma to_fun_eq_coe (f : A →+[M] B) : f.to_fun = ⇑f := rfl @[norm_cast] lemma coe_fn_coe (f : A →+[M] B) : ((f : A →+ B) : A → B) = f := rfl @[norm_cast] lemma coe_fn_coe' (f : A →+[M] B) : ((f : A →[M] B) : A → B) = f := rfl @[ext] theorem ext : ∀ {f g : A →+[M] B}, (∀ x, f x = g x) → f = g | ⟨f, _, _, _⟩ ⟨g, _, _, _⟩ H := by { congr' 1 with x, exact H x } theorem ext_iff {f g : A →+[M] B} : f = g ↔ ∀ x, f x = g x := ⟨λ H x, by rw H, ext⟩ protected lemma congr_fun {f g : A →+[M] B} (h : f = g) (x : A) : f x = g x := h ▸ rfl lemma to_mul_action_hom_injective {f g : A →+[M] B} (h : (f : A →[M] B) = (g : A →[M] B)) : f = g := by { ext a, exact mul_action_hom.congr_fun h a, } lemma to_add_monoid_hom_injective {f g : A →+[M] B} (h : (f : A →+ B) = (g : A →+ B)) : f = g := by { ext a, exact add_monoid_hom.congr_fun h a, } @[simp] lemma map_zero (f : A →+[M] B) : f 0 = 0 := f.map_zero' @[simp] lemma map_add (f : A →+[M] B) (x y : A) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_neg (f : A' →+[M] B') (x : A') : f (-x) = -f x := (f : A' →+ B').map_neg x @[simp] lemma map_sub (f : A' →+[M] B') (x y : A') : f (x - y) = f x - f y := (f : A' →+ B').map_sub x y @[simp] lemma map_smul (f : A →+[M] B) (m : M) (x : A) : f (m • x) = m • f x := f.map_smul' m x variables (M) {A} /-- The identity map as an equivariant additive monoid homomorphism. -/ protected def id : A →+[M] A := ⟨id, λ _ _, rfl, rfl, λ _ _, rfl⟩ @[simp] lemma id_apply (x : A) : distrib_mul_action_hom.id M x = x := rfl variables {M A B C} instance : has_zero (A →+[M] B) := ⟨{ map_smul' := by simp, .. (0 : A →+ B) }⟩ instance : has_one (A →+[M] A) := ⟨distrib_mul_action_hom.id M⟩ @[simp] lemma coe_zero : ((0 : A →+[M] B) : A → B) = 0 := rfl @[simp] lemma coe_one : ((1 : A →+[M] A) : A → A) = id := rfl lemma zero_apply (a : A) : (0 : A →+[M] B) a = 0 := rfl lemma one_apply (a : A) : (1 : A →+[M] A) a = a := rfl instance : inhabited (A →+[M] B) := ⟨0⟩ /-- Composition of two equivariant additive monoid homomorphisms. -/ def comp (g : B →+[M] C) (f : A →+[M] B) : A →+[M] C := { .. mul_action_hom.comp (g : B →[M] C) (f : A →[M] B), .. add_monoid_hom.comp (g : B →+ C) (f : A →+ B), } @[simp] lemma comp_apply (g : B →+[M] C) (f : A →+[M] B) (x : A) : g.comp f x = g (f x) := rfl @[simp] lemma id_comp (f : A →+[M] B) : (distrib_mul_action_hom.id M).comp f = f := ext $ λ x, by rw [comp_apply, id_apply] @[simp] lemma comp_id (f : A →+[M] B) : f.comp (distrib_mul_action_hom.id M) = f := ext $ λ x, by rw [comp_apply, id_apply] /-- The inverse of a bijective `distrib_mul_action_hom` is a `distrib_mul_action_hom`. -/ @[simps] def inverse (f : A →+[M] B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →+[M] A := { to_fun := g, .. (f : A →+ B).inverse g h₁ h₂, .. (f : A →[M] B).inverse g h₁ h₂ } section semiring variables {R M'} [add_monoid M'] [distrib_mul_action R M'] @[ext] lemma ext_ring {f g : R →+[R] M'} (h : f 1 = g 1) : f = g := by { ext x, rw [← mul_one x, ← smul_eq_mul R, f.map_smul, g.map_smul, h], } lemma ext_ring_iff {f g : R →+[R] M'} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end semiring end distrib_mul_action_hom /-- Equivariant ring homomorphisms. -/ @[nolint has_inhabited_instance] structure mul_semiring_action_hom extends R →+[M] S, R →+* S. /-- Reinterpret an equivariant ring homomorphism as a ring homomorphism. -/ add_decl_doc mul_semiring_action_hom.to_ring_hom /-- Reinterpret an equivariant ring homomorphism as an equivariant additive monoid homomorphism. -/ add_decl_doc mul_semiring_action_hom.to_distrib_mul_action_hom notation R ` →+*[`:25 M:25 `] `:0 S:0 := mul_semiring_action_hom M R S namespace mul_semiring_action_hom instance has_coe : has_coe (R →+*[M] S) (R →+* S) := ⟨to_ring_hom⟩ instance has_coe' : has_coe (R →+*[M] S) (R →+[M] S) := ⟨to_distrib_mul_action_hom⟩ instance : has_coe_to_fun (R →+*[M] S) (λ _, R → S) := ⟨λ c, c.to_fun⟩ variables {M R S} @[norm_cast] lemma coe_fn_coe (f : R →+*[M] S) : ((f : R →+* S) : R → S) = f := rfl @[norm_cast] lemma coe_fn_coe' (f : R →+*[M] S) : ((f : R →+[M] S) : R → S) = f := rfl @[ext] theorem ext : ∀ {f g : R →+*[M] S}, (∀ x, f x = g x) → f = g | ⟨f, _, _, _, _, _⟩ ⟨g, _, _, _, _, _⟩ H := by { congr' 1 with x, exact H x } theorem ext_iff {f g : R →+*[M] S} : f = g ↔ ∀ x, f x = g x := ⟨λ H x, by rw H, ext⟩ @[simp] lemma map_zero (f : R →+*[M] S) : f 0 = 0 := f.map_zero' @[simp] lemma map_add (f : R →+*[M] S) (x y : R) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_neg (f : R' →+*[M] S') (x : R') : f (-x) = -f x := (f : R' →+* S').map_neg x @[simp] lemma map_sub (f : R' →+*[M] S') (x y : R') : f (x - y) = f x - f y := (f : R' →+* S').map_sub x y @[simp] lemma map_one (f : R →+*[M] S) : f 1 = 1 := f.map_one' @[simp] lemma map_mul (f : R →+*[M] S) (x y : R) : f (x * y) = f x * f y := f.map_mul' x y @[simp] lemma map_smul (f : R →+*[M] S) (m : M) (x : R) : f (m • x) = m • f x := f.map_smul' m x variables (M) {R} /-- The identity map as an equivariant ring homomorphism. -/ protected def id : R →+*[M] R := ⟨id, λ _ _, rfl, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ @[simp] lemma id_apply (x : R) : mul_semiring_action_hom.id M x = x := rfl variables {M R S T} /-- Composition of two equivariant additive monoid homomorphisms. -/ def comp (g : S →+*[M] T) (f : R →+*[M] S) : R →+*[M] T := { .. distrib_mul_action_hom.comp (g : S →+[M] T) (f : R →+[M] S), .. ring_hom.comp (g : S →+* T) (f : R →+* S), } @[simp] lemma comp_apply (g : S →+*[M] T) (f : R →+*[M] S) (x : R) : g.comp f x = g (f x) := rfl @[simp] lemma id_comp (f : R →+*[M] S) : (mul_semiring_action_hom.id M).comp f = f := ext $ λ x, by rw [comp_apply, id_apply] @[simp] lemma comp_id (f : R →+*[M] S) : f.comp (mul_semiring_action_hom.id M) = f := ext $ λ x, by rw [comp_apply, id_apply] end mul_semiring_action_hom section variables (M) {R'} (U : subring R') [is_invariant_subring M U] /-- The canonical inclusion from an invariant subring. -/ def is_invariant_subring.subtype_hom : U →+*[M] R' := { map_smul' := λ m s, rfl, ..U.subtype } @[simp] theorem is_invariant_subring.coe_subtype_hom : (is_invariant_subring.subtype_hom M U : U → R') = coe := rfl @[simp] theorem is_invariant_subring.coe_subtype_hom' : (is_invariant_subring.subtype_hom M U : U →+* R') = U.subtype := rfl end
088881748b6bf8e6008b1c05a5c9f9f2639628a3
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/real/pi/wallis.lean
2f114d5606c4e6aea24e61cd5184610ddb00757d
[ "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
4,727
lean
/- Copyright (c) 2021 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import analysis.special_functions.integrals /-! # The Wallis formula for Pi This file establishes the Wallis product for `π` (`real.tendsto_prod_pi_div_two`). Our proof is largely about analyzing the behaviour of the sequence `∫ x in 0..π, sin x ^ n` as `n → ∞`. See: https://en.wikipedia.org/wiki/Wallis_product The proof can be broken down into two pieces. The first step (carried out in `analysis.special_functions.integrals`) is to use repeated integration by parts to obtain an explicit formula for this integral, which is rational if `n` is odd and a rational multiple of `π` if `n` is even. The second step, carried out here, is to estimate the ratio `∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that it converges to one using the squeeze theorem. The final product for `π` is obtained after some algebraic manipulation. ## Main statements * `real.wallis.W`: the product of the first `k` terms in Wallis' formula for `π`. * `real.wallis.W_eq_integral_sin_pow_div_integral_sin_pow`: express `W n` as a ratio of integrals. * `real.wallis.W_le` and `real.wallis.le_W`: upper and lower bounds for `W n`. * `real.tendsto_prod_pi_div_two`: the Wallis product formula. -/ open_locale real topology big_operators nat open filter finset interval_integral namespace real namespace wallis /-- The product of the first `k` terms in Wallis' formula for `π`. -/ noncomputable def W (k : ℕ) : ℝ := ∏ i in range k, (2 * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3)) lemma W_succ (k : ℕ) : W (k + 1) = W k * ((2 * k + 2) / (2 * k + 1) * ((2 * k + 2) / (2 * k + 3))) := prod_range_succ _ _ lemma W_pos (k : ℕ) : 0 < W k := begin induction k with k hk, { unfold W, simp }, { rw W_succ, refine mul_pos hk (mul_pos (div_pos _ _) (div_pos _ _)); positivity } end lemma W_eq_factorial_ratio (n : ℕ) : W n = (2 ^ (4 * n) * n! ^ 4) / ((2 * n)!^ 2 * (2 * n + 1)) := begin induction n with n IH, { simp only [W, prod_range_zero, nat.factorial_zero, mul_zero, pow_zero, algebra_map.coe_one, one_pow, mul_one, algebra_map.coe_zero, zero_add, div_self, ne.def, one_ne_zero, not_false_iff] }, { unfold W at ⊢ IH, rw [prod_range_succ, IH, _root_.div_mul_div_comm, _root_.div_mul_div_comm], refine (div_eq_div_iff _ _).mpr _, any_goals { exact ne_of_gt (by positivity) }, simp_rw [nat.mul_succ, nat.factorial_succ, pow_succ], push_cast, ring_nf } end lemma W_eq_integral_sin_pow_div_integral_sin_pow (k : ℕ) : (π/2)⁻¹ * W k = (∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1)) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k) := begin rw [integral_sin_pow_even, integral_sin_pow_odd, mul_div_mul_comm, ←prod_div_distrib, inv_div], simp_rw [div_div_div_comm, div_div_eq_mul_div, mul_div_assoc], refl, end lemma W_le (k : ℕ) : W k ≤ π / 2 := begin rw [←div_le_one pi_div_two_pos, div_eq_inv_mul], rw [W_eq_integral_sin_pow_div_integral_sin_pow, div_le_one (integral_sin_pow_pos _)], apply integral_sin_pow_succ_le, end lemma le_W (k : ℕ) : ((2:ℝ) * k + 1) / (2 * k + 2) * (π / 2) ≤ W k := begin rw [←le_div_iff pi_div_two_pos, div_eq_inv_mul (W k) _], rw [W_eq_integral_sin_pow_div_integral_sin_pow, le_div_iff (integral_sin_pow_pos _)], convert integral_sin_pow_succ_le (2 * k + 1), rw integral_sin_pow (2 * k), simp only [sin_zero, zero_pow', ne.def, nat.succ_ne_zero, not_false_iff, zero_mul, sin_pi, tsub_zero, nat.cast_mul, nat.cast_bit0, algebra_map.coe_one, zero_div, zero_add], end lemma tendsto_W_nhds_pi_div_two : tendsto W at_top (𝓝 $ π / 2) := begin refine tendsto_of_tendsto_of_tendsto_of_le_of_le _ tendsto_const_nhds le_W W_le, have : 𝓝 (π / 2) = 𝓝 ((1 - 0) * (π / 2)), by rw [sub_zero, one_mul], rw this, refine tendsto.mul _ tendsto_const_nhds, have h : ∀ (n:ℕ), ((2:ℝ) * n + 1) / (2 * n + 2) = 1 - 1 / (2 * n + 2), { intro n, rw [sub_div' _ _ _ (ne_of_gt (add_pos_of_nonneg_of_pos (mul_nonneg ((two_pos : 0 < (2:ℝ)).le) (nat.cast_nonneg _)) two_pos)), one_mul], congr' 1, ring }, simp_rw h, refine (tendsto_const_nhds.div_at_top _).const_sub _, refine tendsto.at_top_add _ tendsto_const_nhds, exact tendsto_coe_nat_at_top_at_top.const_mul_at_top two_pos end end wallis end real /-- Wallis' product formula for `π / 2`. -/ theorem real.tendsto_prod_pi_div_two : tendsto (λ k, ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 (π/2)) := real.wallis.tendsto_W_nhds_pi_div_two
752f6d751180da6c2ebbc51a62c0379c34ee4f80
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/deps/galois_stdlib/src/galois/data/bitvec/basic.lean
29ab4c341368950ce0bd1bbd107235da5e92145b
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
11,910
lean
/- Copyright (c) 2015 Joe Hendrix. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joe Hendrix, Sebastian Ullrich, Jason Dagit Basic operations on bitvectors. This is a work-in-progress, and contains additions to other theories. -/ import galois.data.nat.basic import data.vector -- A `bitvec n` is a subtype of natural numbers such that the value of -- the bitvec is strictly less than 2^n. structure bitvec (sz:ℕ) := (to_nat : ℕ) (property : to_nat < (2 ^ sz)) namespace bitvec instance (w:ℕ) : decidable_eq (bitvec w) := by tactic.mk_dec_eq_instance -- By default just show a bitvector as a nat. instance (w:ℕ) : has_repr (bitvec w) := ⟨λv, repr (v.to_nat)⟩ section zero -- Create a zero bitvector protected def zero (n : ℕ) : bitvec n := ⟨0, nat.pos_pow_of_pos n dec_trivial⟩ -- bitvectors have a zero, at every length instance {n:ℕ} : has_zero (bitvec n) := ⟨bitvec.zero n⟩ @[simp] lemma bitvec_zero_zero (x : bitvec 0) : x.to_nat = 0 := begin cases x with x_val x_prop, { simp [nat.pow_zero, nat.lt_one_is_zero] at x_prop, simp, assumption } end end zero section one lemma one_le_pow_2 {n: ℕ} (h : n > 0) : 1 < 2^n := calc 1 < 2^1 : by exact (of_as_true trivial) ... ≤ 2^n : nat.pow_le_pow_of_le_right (of_as_true trivial) h -- In pratice, it's more useful to allow 0 length bitvectors to have 1 -- as well. This leads to a special case where the 0-length bitvector -- 1 is really just 0. This turns out to simplify things. protected def one : Π(n:ℕ), bitvec n | 0 := 0 | (nat.succ _) := ⟨1, one_le_pow_2 (nat.zero_lt_succ _)⟩ instance {n:ℕ} : has_one (bitvec n) := ⟨bitvec.one n⟩ end one protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b | ⟨x, p⟩ := ⟨x, h ▸ p⟩ lemma cong_val {n m : ℕ} {H : n = m} (x : bitvec n) : (bitvec.cong H x).to_nat = x.to_nat := begin cases x, simp [bitvec.cong] end protected lemma intro {n:ℕ} : Π(x y : bitvec n), x.to_nat = y.to_nat → x = y | ⟨x, h1⟩ ⟨.(_), h2⟩ rfl := rfl protected def of_nat (n : ℕ) (x:ℕ) : bitvec n := ⟨ x % 2^n, nat.mod_lt _ (nat.pos_pow_of_pos n (of_as_true trivial))⟩ theorem of_nat_to_nat {n : ℕ} (x : bitvec n) : bitvec.of_nat n (bitvec.to_nat x) = x := begin cases x, simp [bitvec.to_nat, bitvec.of_nat], apply nat.mod_eq_of_lt x_property, end theorem to_nat_of_nat (k n : ℕ) : bitvec.to_nat (bitvec.of_nat k n) = n % 2^k := begin simp [bitvec.of_nat, bitvec.to_nat] end --- Most significant bit def msb {n:ℕ} (x: bitvec n) : bool := (nat.shiftr x.to_nat (n-1)) = 1 --- Least significant bit. def lsb {n:ℕ} (x: bitvec n) : bool := nat.bodd x.to_nat section conversion -- Operations for converting to/from bitvectors protected def to_int {n:ℕ} (x: bitvec n) : int := match msb x with | ff := int.of_nat x.to_nat | tt := int.neg_of_nat (2^n - x.to_nat) end --- Convert an int to two's complement bitvector. protected def of_int : Π(n : ℕ), ℤ → bitvec n | n (int.of_nat x) := bitvec.of_nat n x | n -[1+ x] := bitvec.of_nat n (nat.ldiff (2^n-1) x) end conversion section bitwise -- bitwise negation def not {w:ℕ} (x: bitvec w) : bitvec w := ⟨2^w - x.to_nat - 1, begin have xval_pos : 0 < x.to_nat + 1, { apply (nat.succ_pos x.to_nat) }, apply (nat.sub_lt _ xval_pos), apply nat.pos_pow_of_pos, apply (nat.succ_pos 1) end⟩ -- logical bitwise and def and {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.land x.to_nat y.to_nat) -- diff x y = x & not y def diff {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.ldiff x.to_nat y.to_nat) -- logical bitwise or def or {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.lor x.to_nat y.to_nat) -- logical bitwise xor def xor {w:ℕ} (x y : bitvec w) : bitvec w := bitvec.of_nat w (nat.lxor x.to_nat y.to_nat) infix `.&&.`:70 := and infix `.||.`:65 := or end bitwise section arith -- Arithmetic operations on bitvectors variable {n : ℕ} protected def add (x y : bitvec n) : bitvec n := bitvec.of_nat n (x.to_nat + y.to_nat) def adc (x y : bitvec n) : bitvec n × bool := ⟨ bitvec.add x y , x.to_nat + y.to_nat ≥ 2^n ⟩ -- Usual arithmetic subtraction protected def sub (x y : bitvec n) : bitvec n := bitvec.of_int n (x.to_int - y.to_int) -- 2s complement negation protected def neg {n:ℕ} (x : bitvec n) : bitvec n := ⟨if x.to_nat = 0 then 0 else 2^n - x.to_nat, begin by_cases (x.to_nat = 0), { simp [h], exact nat.pos_pow_of_pos _ (of_as_true trivial), }, { simp [h], --x.to_nat (2^n) x_to_nat_pos, have pos : 0 < 2^n - x.to_nat, { apply nat.sub_pos_of_lt x.property }, have x_to_nat_pos: 0 < x.to_nat, { apply nat.pos_of_ne_zero h }, apply nat.sub_lt_of_pos_le x.to_nat (2^n) x_to_nat_pos, apply le_of_lt x.property, } end⟩ instance : has_add (bitvec n) := ⟨bitvec.add⟩ instance : has_sub (bitvec n) := ⟨bitvec.sub⟩ instance : has_neg (bitvec n) := ⟨bitvec.neg⟩ protected def mul (x y : bitvec n) : bitvec n := bitvec.of_nat n (x.to_nat * y.to_nat) instance : has_mul (bitvec n) := ⟨bitvec.mul⟩ def bitvec_pow (x: bitvec n) (k:ℕ) : bitvec n := bitvec.of_nat n (x.to_nat^k) instance bitvec_has_pow : has_pow (bitvec n) ℕ := ⟨bitvec_pow⟩ end arith section shift -- Shift related operations, including signed and unsigned shift. variable {n : ℕ} -- shift left def shl (x : bitvec n) (i : ℕ) : bitvec n := bitvec.of_nat n (nat.shiftl x.to_nat i) -- unsigned shift right def ushr (x : bitvec n) (i : ℕ) : bitvec n := bitvec.of_nat n (nat.shiftr x.to_nat i) -- signed shift right def sshr (x: bitvec n) (i:ℕ) : bitvec n := bitvec.of_int n (int.shiftr (bitvec.to_int x) i) end shift section listlike -- Operations that treat bitvectors as a list of bits. --- Test if a specific bit with given index is set. def nth {w:ℕ} (x : bitvec w) (idx : ℕ) : bool := nat.test_bit x.to_nat idx -- Change number of bits result while preserving unsigned value modulo output width. def uresize {m:ℕ} (x: bitvec m) (n:ℕ) : bitvec n := bitvec.of_nat _ x.to_nat -- Change number of bits result while preserving signed value modulo output width. def sresize {m:ℕ} (x: bitvec m) (n:ℕ) : bitvec n := bitvec.of_int _ x.to_int open nat -- bitvec specific version of vector.append def append {m n} (x: bitvec m) (y: bitvec n) : bitvec (m + n) := ⟨ x.to_nat * 2^n + y.to_nat, nat.mul_pow_add_lt_pow x.property y.property ⟩ protected def bsf' : Π(n:ℕ), ℕ → ℕ → option ℕ | 0 idx _ := none | (succ m) idx x := if nat.test_bit x idx then some idx else bsf' m (idx+1) x --- index of least-significant bit that is 1. def bsf : Π{n:ℕ}, bitvec n → option ℕ | n x := bitvec.bsf' n 0 x.to_nat protected def bsr' : ℕ → ℕ → option ℕ | x zero := none | x (succ idx) := if nat.test_bit x idx then some idx else bsr' x idx --- index of the most-significant bit that is 1. def bsr : Π{n:ℕ}, bitvec n → option ℕ | n x := bitvec.bsr' x.to_nat n example : bsf (bitvec.of_nat 3 0) = none := of_as_true trivial example : bsr (bitvec.of_nat 3 0) = none := of_as_true trivial example : bsf (bitvec.of_nat 3 5) = some 0 := of_as_true trivial example : bsr (bitvec.of_nat 3 5) = some 2 := of_as_true trivial def slice {w: ℕ} (u l k:ℕ) (H: w = k + (u + 1 - l)) (x: bitvec w) : bitvec (u + 1 - l) := bitvec.of_nat _ (nat.shiftr x.to_nat l) end listlike section comparison -- Comparison operations, including signed and unsigned versions variable {n : ℕ} def ult (x y : bitvec n) : Prop := x.to_nat < y.to_nat def ugt (x y : bitvec n) : Prop := ult y x def ule (x y : bitvec n) : Prop := ¬ (ult y x) def uge (x y : bitvec n) : Prop := ule y x def slt (x y : bitvec n) : Prop := x.to_int < y.to_int def sgt (x y : bitvec n) : Prop := slt y x def sle (x y : bitvec n) : Prop := ¬ (slt y x) def sge (x y : bitvec n) : Prop := sle y x local attribute [reducible] ult local attribute [reducible] ugt local attribute [reducible] ule local attribute [reducible] uge instance decidable_ult {n} {x y : bitvec n} : decidable (bitvec.ult x y) := by apply_instance instance decidable_ugt {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := by apply_instance instance decidable_ule {n} {x y : bitvec n} : decidable (bitvec.ule x y) := by apply_instance instance decidable_uge {n} {x y : bitvec n} : decidable (bitvec.uge x y) := by apply_instance local attribute [reducible] slt local attribute [reducible] sgt local attribute [reducible] sle local attribute [reducible] sge instance decidable_slt {n} {x y : bitvec n} : decidable (bitvec.slt x y) := by apply_instance instance decidable_sgt {n} {x y : bitvec n} : decidable (bitvec.sgt x y) := by apply_instance instance decidable_sle {n} {x y : bitvec n} : decidable (bitvec.sle x y) := by apply_instance instance decidable_sge {n} {x y : bitvec n} : decidable (bitvec.sge x y) := by apply_instance end comparison def concat' {n:ℕ} (input: list (bitvec n)): ℕ := list.foldl (λv (a:bitvec n), nat.shiftl v n + a.to_nat) 0 input --- Concatenation all bitvectors in the list together and return a new bitvector. -- -- The most significant bits of are returned first. def concat_list {m:ℕ}(input: list (bitvec m)) (n:ℕ) : bitvec n := bitvec.of_nat _ (concat' input) --- Concatenation all bitvectors in the vector together and return a new bitvector. -- -- The most significant bits of are returned first. -- -- To minimize the need for proofs, we intentionally do not force that the output -- has a specific length. def concat_vec {w m : ℕ}(input: vector (bitvec w) m) (n:ℕ) : bitvec n := bitvec.of_nat _ (concat' input.to_list) example : concat_list [(1 : bitvec 4), 0] 8 = (16 : bitvec 8) := by exact (of_as_true trivial) --- Forms a list of bitvectors by taking a specific number of bits from parts of the -- first argument. -- -- The head of the list has the most-significant bits. def split_to_list (x:ℕ) (w:ℕ) : ℕ → list (bitvec w) | nat.zero := [] | (nat.succ n) := bitvec.of_nat w (nat.shiftr x (n*w)) :: split_to_list n theorem length_split_to_list (x:ℕ) (w : ℕ) (m:ℕ) : list.length (split_to_list x w m) = m := begin induction m, case nat.zero { simp [split_to_list], }, case nat.succ : m ind { simp [split_to_list, ind, nat.succ_add], }, end /- Split a single bitvector into a list of bitvectors with most-significant bits first. -/ def split_list {n:ℕ} (x:bitvec n) (w:ℕ) : list (bitvec w) := split_to_list x.to_nat w (nat.div n w) /- Split a single bitvector into a vector of bitvectors with most-significant bits first. -/ def split_vec {n:ℕ} (x:bitvec n) (w m:ℕ) : vector (bitvec w) m := ⟨split_to_list x.to_nat w m, length_split_to_list _ _ _⟩ example : split_list (16 : bitvec 8) 4 = [(1 : bitvec 4), 0] := by exact (of_as_true trivial) --- Git bits [i..i+m] out of n. def get_bits {n} (x:bitvec n) (i m : ℕ) (p:i+m ≤ n) : bitvec m := bitvec.of_nat m (nat.shiftr x.to_nat i) --#eval ((get_bits (0x01234567 : bitvec 32) 8 16 (of_as_true trivial) = 0x2345) : bool) --- Set bits at given index. def set_bits {n} (x:bitvec n) (i:ℕ) {m} (y:bitvec m) (p:i+m ≤ n) : bitvec n := let mask := bitvec.of_nat n (nat.shiftl ((2^m)-1) i) in or (diff x mask) (bitvec.of_nat n (nat.shiftl y.to_nat i)) --#eval ((set_bits (0x01234567 : bitvec 32) 8 (0x5432 : bitvec 16) (of_as_true trivial) = 0x01543267) : bool) end bitvec
63d06c704eb96e580bbe6e9bad38a8fecbed3f59
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/gcd.lean
ade5f30cd9ba2b2554fadab7df52b177122e2a77
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,686
lean
import data.nat data.prod logic.wf_k open nat well_founded decidable prod eq.ops namespace playground -- Setup definition pair_nat.lt := lex lt lt definition pair_nat.lt.wf [instance] : well_founded pair_nat.lt := intro_k (prod.lex.wf lt.wf lt.wf) 20 -- the '20' is for being able to execute the examples... it means 20 recursive call without proof computation infixl `≺`:50 := pair_nat.lt -- Lemma for justifying recursive call private lemma lt₁ (x₁ y₁ : nat) : (x₁ - y₁, succ y₁) ≺ (succ x₁, succ y₁) := !lex.left (le_imp_lt_succ (sub_le_self x₁ y₁)) -- Lemma for justifying recursive call private lemma lt₂ (x₁ y₁ : nat) : (succ x₁, y₁ - x₁) ≺ (succ x₁, succ y₁) := !lex.right (le_imp_lt_succ (sub_le_self y₁ x₁)) definition gcd.F (p₁ : nat × nat) : (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat := prod.cases_on p₁ (λ (x y : nat), nat.cases_on x (λ f, y) -- x = 0 (λ x₁, nat.cases_on y (λ f, succ x₁) -- y = 0 (λ y₁ (f : (Π p₂ : nat × nat, p₂ ≺ (succ x₁, succ y₁) → nat)), if y₁ ≤ x₁ then f (x₁ - y₁, succ y₁) !lt₁ else f (succ x₁, y₁ - x₁) !lt₂))) definition gcd (x y : nat) := fix gcd.F (pair x y) theorem gcd_def_z_y (y : nat) : gcd 0 y = y := well_founded.fix_eq gcd.F (0, y) theorem gcd_def_sx_z (x : nat) : gcd (x+1) 0 = x+1 := well_founded.fix_eq gcd.F (x+1, 0) theorem gcd_def_sx_sy (x y : nat) : gcd (x+1) (y+1) = if y ≤ x then gcd (x-y) (y+1) else gcd (x+1) (y-x) := well_founded.fix_eq gcd.F (x+1, y+1) example : gcd 4 6 = 2 := rfl example : gcd 15 6 = 3 := rfl example : gcd 0 2 = 2 := rfl end playground
ed5bf4334551666eaaf72bbaf3176c8fd712e034
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/ring/prod.lean
4829806640b10671f8396da7ac977a9b0adf14e0
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
5,998
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Chris Hughes, Mario Carneiro, Yury Kudryashov -/ import algebra.group.prod import algebra.ring.basic import data.equiv.ring /-! # Semiring, ring etc structures on `R × S` In this file we define two-binop (`semiring`, `ring` etc) structures on `R × S`. We also prove trivial `simp` lemmas, and define the following operations on `ring_hom`s: * `fst R S : R × S →+* R`, `snd R S : R × S →+* R`: projections `prod.fst` and `prod.snd` as `ring_hom`s; * `f.prod g : `R →+* S × T`: sends `x` to `(f x, g x)`; * `f.prod_map g : `R × S → R' × S'`: `prod.map f g` as a `ring_hom`, sends `(x, y)` to `(f x, g y)`. -/ variables {R : Type*} {R' : Type*} {S : Type*} {S' : Type*} {T : Type*} {T' : Type*} namespace prod /-- Product of two distributive types is distributive. -/ instance [distrib R] [distrib S] : distrib (R × S) := { left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩, right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩, .. prod.has_add, .. prod.has_mul } /-- Product of two `non_unital_non_assoc_semiring`s is a `non_unital_non_assoc_semiring`. -/ instance [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] : non_unital_non_assoc_semiring (R × S) := { .. prod.add_comm_monoid, .. prod.mul_zero_class, .. prod.distrib } /-- Product of two `non_unital_semiring`s is a `non_unital_semiring`. -/ instance [non_unital_semiring R] [non_unital_semiring S] : non_unital_semiring (R × S) := { .. prod.non_unital_non_assoc_semiring, .. prod.semigroup } /-- Product of two `non_assoc_semiring`s is a `non_assoc_semiring`. -/ instance [non_assoc_semiring R] [non_assoc_semiring S] : non_assoc_semiring (R × S) := { .. prod.non_unital_non_assoc_semiring, .. prod.mul_one_class } /-- Product of two semirings is a semiring. -/ instance [semiring R] [semiring S] : semiring (R × S) := { .. prod.add_comm_monoid, .. prod.monoid_with_zero, .. prod.distrib } /-- Product of two commutative semirings is a commutative semiring. -/ instance [comm_semiring R] [comm_semiring S] : comm_semiring (R × S) := { .. prod.semiring, .. prod.comm_monoid } /-- Product of two rings is a ring. -/ instance [ring R] [ring S] : ring (R × S) := { .. prod.add_comm_group, .. prod.semiring } /-- Product of two commutative rings is a commutative ring. -/ instance [comm_ring R] [comm_ring S] : comm_ring (R × S) := { .. prod.ring, .. prod.comm_monoid } end prod namespace ring_hom variables (R S) [non_assoc_semiring R] [non_assoc_semiring S] /-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `R`.-/ def fst : R × S →+* R := { to_fun := prod.fst, .. monoid_hom.fst R S, .. add_monoid_hom.fst R S } /-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `S`.-/ def snd : R × S →+* S := { to_fun := prod.snd, .. monoid_hom.snd R S, .. add_monoid_hom.snd R S } variables {R S} @[simp] lemma coe_fst : ⇑(fst R S) = prod.fst := rfl @[simp] lemma coe_snd : ⇑(snd R S) = prod.snd := rfl section prod variables [non_assoc_semiring T] (f : R →+* S) (g : R →+* T) /-- Combine two ring homomorphisms `f : R →+* S`, `g : R →+* T` into `f.prod g : R →+* S × T` given by `(f.prod g) x = (f x, g x)` -/ protected def prod (f : R →+* S) (g : R →+* T) : R →+* S × T := { to_fun := λ x, (f x, g x), .. monoid_hom.prod (f : R →* S) (g : R →* T), .. add_monoid_hom.prod (f : R →+ S) (g : R →+ T) } @[simp] lemma prod_apply (x) : f.prod g x = (f x, g x) := rfl @[simp] lemma fst_comp_prod : (fst S T).comp (f.prod g) = f := ext $ λ x, rfl @[simp] lemma snd_comp_prod : (snd S T).comp (f.prod g) = g := ext $ λ x, rfl lemma prod_unique (f : R →+* S × T) : ((fst S T).comp f).prod ((snd S T).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables [non_assoc_semiring R'] [non_assoc_semiring S'] [non_assoc_semiring T] variables (f : R →+* R') (g : S →+* S') /-- `prod.map` as a `ring_hom`. -/ def prod_map : R × S →* R' × S' := (f.comp (fst R S)).prod (g.comp (snd R S)) lemma prod_map_def : prod_map f g = (f.comp (fst R S)).prod (g.comp (snd R S)) := rfl @[simp] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl lemma prod_comp_prod_map (f : T →* R) (g : T →* S) (f' : R →* R') (g' : S →* S') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map end ring_hom namespace ring_equiv variables {R S} [non_assoc_semiring R] [non_assoc_semiring S] /-- Swapping components as an equivalence of (semi)rings. -/ def prod_comm : R × S ≃+* S × R := { ..add_equiv.prod_comm, ..mul_equiv.prod_comm } @[simp] lemma coe_prod_comm : ⇑(prod_comm : R × S ≃+* S × R) = prod.swap := rfl @[simp] lemma coe_prod_comm_symm : ⇑((prod_comm : R × S ≃+* S × R).symm) = prod.swap := rfl @[simp] lemma fst_comp_coe_prod_comm : (ring_hom.fst S R).comp ↑(prod_comm : R × S ≃+* S × R) = ring_hom.snd R S := ring_hom.ext $ λ _, rfl @[simp] lemma snd_comp_coe_prod_comm : (ring_hom.snd S R).comp ↑(prod_comm : R × S ≃+* S × R) = ring_hom.fst R S := ring_hom.ext $ λ _, rfl variables (R S) [subsingleton S] /-- A ring `R` is isomorphic to `R × S` when `S` is the zero ring -/ @[simps] def prod_zero_ring : R ≃+* R × S := { to_fun := λ x, (x, 0), inv_fun := prod.fst, map_add' := by simp, map_mul' := by simp, left_inv := λ x, rfl, right_inv := λ x, by cases x; simp } /-- A ring `R` is isomorphic to `S × R` when `S` is the zero ring -/ @[simps] def zero_ring_prod : R ≃+* S × R := { to_fun := λ x, (0, x), inv_fun := prod.snd, map_add' := by simp, map_mul' := by simp, left_inv := λ x, rfl, right_inv := λ x, by cases x; simp } end ring_equiv
5edf6ab5f3d628d02ca9090f74e65f48efb88b1d
3adda22358e3c0fbae44c6c35fdddbebf9358ef4
/src/Q2.lean
1601b58935066bb90d772542313957e3817e628d
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1F-exam-may-2018
1539951b055cea5bac915bdb6fa1969e2f323402
8b5eca2037d4a14d6cfac3da1858b6c4119216d3
refs/heads/master
1,586,895,978,182
1,557,175,794,000
1,557,175,794,000
164,093,611
2
0
null
null
null
null
UTF-8
Lean
false
false
4,920
lean
import data.real.basic import for_mathlib.decimal_expansions import zero_point_seven_one -- "obvious" proof that 0.71 has no 8's in decimal expansion! /- M1F May exam 2018, question 2. -/ universe u local attribute [instance, priority 0] classical.prop_decidable -- Q2(a)(i) def ub (S : set ℝ) (x : ℝ) := ∀ s ∈ S, s ≤ x ---ans -- Q2(a)(ii) -- iba: is bounded above def iba (S : set ℝ) := ∃ x, ub S x ---ans -- Q2(a)(iii) def lub (S : set ℝ) (b : ℝ) := ub S b ∧ ∀ y : ℝ, (ub S y → b ≤ y) ---ans -- Q2(b) theorem lub_duh (S : set ℝ) : (∃ x, lub S x) → S ≠ ∅ ∧ iba S := ---ans begin intro Hexlub, cases Hexlub with x Hlub, split, intro Hemp, rw set.empty_def at Hemp, cases Hlub with Hub Hl, have Hallub : ∀ y : ℝ, ub S y, unfold ub, rw Hemp, change (∀ (y s : ℝ), false → s ≤ y), intros y s Hf, exfalso, exact Hf, have Hneginf : ∀ y : ℝ, x ≤ y, intro y, apply Hl, apply Hallub, have Hcontr := Hneginf (x - 1), revert Hcontr, norm_num, existsi x, exact Hlub.left, end -- Q2(c)(i) preparation def S1 := {x : ℝ | x < 59} lemma between_bounds (x y : ℝ) (H : x < y) : x < (x + y) / 2 ∧ (x + y) / 2 < y := ⟨by linarith, by linarith⟩ -- Q2(c)(i) theorem S1_lub : lub S1 59 := ---ans begin split, intro, change (s < 59 → s ≤ 59), exact le_of_lt, intro y, change ((∀ (s : ℝ), s < 59 → s ≤ y) → 59 ≤ y), intro Hbub, apply le_of_not_gt, intro Hbadub, have Houtofbounds := between_bounds y 59 Hbadub, apply not_le_of_gt Houtofbounds.1 (Hbub ((y + 59) / 2) Houtofbounds.2), end -- Q2(c)(ii) preparations definition S2 : set ℝ := {x | 7/10 < x ∧ x < 9/10 ∧ ∀ n : ℕ, decimal.expansion_nonneg x n ≠ 8} lemma S2_nonempty_and_bounded : (∃ s : ℝ, s ∈ S2) ∧ ∀ (s : ℝ), s ∈ S2 → s ≤ 9/10 := begin split, { -- 0.71 ∈ S use (71 / 100 : ℝ), split, norm_num, split, norm_num, exact no_eights_in_0_point_71 }, rintro s ⟨hs1, hs2, h⟩, exact le_of_lt hs2 end -- Q2(c)(ii) theorem S2_has_lub : ∃ b : ℝ, lub S2 b := begin cases S2_nonempty_and_bounded with Hne Hbd, have H := real.exists_sup S2 Hne ⟨(9/10 : ℝ), Hbd⟩, cases H with b Hb, use b, split, { intros s2 Hs2, exact (Hb b).mp (le_refl _) s2 Hs2, }, { intros y Hy, exact (Hb y).mpr Hy, } end -- Q2(d)(i) theorem ublub_the_first (S : set ℝ) (b : ℝ) (hub : ub S b) (hin : b ∈ S) : lub S b := ---ans begin split, exact hub, intros y huby, exact huby b hin, end -- Q2(d)(ii) theorem adlub_the_second (S T : set ℝ) (b c : ℝ) (hlubb : lub S b) (hlubc : lub T c) ---ans : lub ({x : ℝ | ∃ s t : ℝ, s ∈ S ∧ t ∈ T ∧ x = s + t}) (b + c) := begin split, unfold ub, simp, intros x s hss t htt hxst, rw hxst, apply add_le_add (hlubb.1 s hss) (hlubc.1 t htt), unfold ub, simp, intros x Hx, apply le_of_not_gt, intro Hcontr, let ε := b + c - x, have Hcontr' : ε > 0 := (by linarith : b + c - x > 0), have rwx : x = (b - ε / 2) + (c - ε / 2) := (by linarith : x = (b - (b + c - x) / 2) + (c - (b + c - x) / 2)), have hnbub : ∃ s' ∈ S, b - ε / 2 < s', by_contradiction, have a' : (¬∃ (s' : ℝ), s' ∈ S ∧ b - ε / 2 < s'), intro b, apply a, cases b with σ Hσ, existsi σ, existsi Hσ.1, exact Hσ.2, have a'' : ∀ (x : ℝ), x ∈ S → ¬(b - ε / 2 < x), intros x Hx Hb, rw not_exists at a', apply a' x, exact ⟨Hx, Hb⟩, simp only [not_lt] at a'', rw ←ub at a'', have a''' := hlubb.2 _ a'', linarith, have hnbuc : ∃ t' ∈ T, c - ε / 2 < t', by_contradiction, have a' : (¬∃ (t' : ℝ), t' ∈ T ∧ c - ε / 2 < t'), intro b, apply a, cases b with σ Hσ, existsi σ, existsi Hσ.1, exact Hσ.2, have a'' : ∀ (x : ℝ), x ∈ T → ¬(c - ε / 2 < x), intros x Hx Hc, rw not_exists at a', apply a' x, exact ⟨Hx, Hc⟩, simp only [not_lt] at a'', rw ←ub at a'', have a''' := hlubc.2 _ a'', linarith, cases hnbub with s' hnbub', cases hnbub' with Hs' hnbub'', cases hnbuc with t' hnbuc', cases hnbuc' with Ht' hnbuc'', have Hx' := Hx (s' + t') s' Hs' t' Ht' rfl, have Haha : x < x := lt_of_lt_of_le (by { rw rwx, apply add_lt_add hnbub'' hnbuc'' } : x < s' + t') Hx', linarith, end
5a5a885109eafb876a948b5ba9ad0c418e5382ad
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/analysis/box_integral/divergence_theorem.lean
57c87751d20a0b1e0d35c4e3d67e44ed79dfb3d5
[ "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
16,374
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.basic import analysis.box_integral.partition.additive import analysis.calculus.fderiv /-! # Divergence integral for Henstock-Kurzweil integral In this file we prove the Divergence Theorem for a Henstock-Kurzweil style integral. The theorem says the following. Let `f : ℝⁿ → Eⁿ` be a function differentiable on a closed rectangular box `I` with derivative `f' x : ℝⁿ →L[ℝ] Eⁿ` at `x ∈ I`. Then the divergence `λ x, ∑ k, f' x eₖ k`, where `eₖ = pi.single k 1` is the `k`-th basis vector, is integrable on `I`, and its integral is equal to the sum of integrals of `f` over the faces of `I` taken with appropriate signs. To make the proof work, we had to ban tagged partitions with “long and thin” boxes. More precisely, we use the following generalization of one-dimensional Henstock-Kurzweil integral to functions defined on a box in `ℝⁿ` (it corresponds to the value `⊥` of `box_integral.integration_params` in the definition of `box_integral.has_integral`). We say that `f : ℝⁿ → E` has integral `y : E` over a box `I ⊆ ℝⁿ` if for an arbitrarily small positive `ε` and an arbitrarily large `c`, there exists a function `r : ℝⁿ → (0, ∞)` such that for any tagged partition `π` of `I` such that * `π` is a Henstock partition, i.e., each tag belongs to its box; * `π` is subordinate to `r`; * for every box of `π`, the maximum of the ratios of its sides is less than or equal to `c`, the integral sum of `f` over `π` is `ε`-close to `y`. In case of dimension one, the last condition trivially holds for any `c ≥ 1`, so this definition is equivalent to the standard definition of Henstock-Kurzweil integral. ## Tags Henstock-Kurzweil integral, integral, Stokes theorem, divergence theorem -/ open_locale classical big_operators nnreal ennreal topological_space box_integral open continuous_linear_map (lsmul) filter set finset metric noncomputable theory universes u variables {E : Type u} [normed_group E] [normed_space ℝ E] {n : ℕ} namespace box_integral local notation `ℝⁿ` := fin n → ℝ local notation `ℝⁿ⁺¹` := fin (n + 1) → ℝ local notation `Eⁿ⁺¹` := fin (n + 1) → E variables [complete_space E] (I : box (fin (n + 1))) {i : fin (n + 1)} open measure_theory /-- Auxiliary lemma for the divergence theorem. -/ lemma norm_volume_sub_integral_face_upper_sub_lower_smul_le {f : ℝⁿ⁺¹ → E} {f' : ℝⁿ⁺¹ →L[ℝ] E} (hfc : continuous_on f I.Icc) {x : ℝⁿ⁺¹} (hxI : x ∈ I.Icc) {a : E} {ε : ℝ} (h0 : 0 < ε) (hε : ∀ y ∈ I.Icc, ∥f y - a - f' (y - x)∥ ≤ ε * ∥y - x∥) {c : ℝ≥0} (hc : I.distortion ≤ c) : ∥(∏ j, (I.upper j - I.lower j)) • f' (pi.single i 1) - (integral (I.face i) ⊥ (f ∘ i.insert_nth (I.upper i)) box_additive_map.volume - integral (I.face i) ⊥ (f ∘ i.insert_nth (I.lower i)) box_additive_map.volume)∥ ≤ 2 * ε * c * ∏ j, (I.upper j - I.lower j) := begin /- **Plan of the proof**. The difference of the integrals of the affine function `λ y, a + f' (y - x)` over the faces `x i = I.upper i` and `x i = I.lower i` is equal to the volume of `I` multiplied by `f' (pi.single i 1)`, so it suffices to show that the integral of `f y - a - f' (y - x)` over each of these faces is less than or equal to `ε * c * vol I`. We integrate a function of the norm `≤ ε * diam I.Icc` over a box of volume `∏ j ≠ i, (I.upper j - I.lower j)`. Since `diam I.Icc ≤ c * (I.upper i - I.lower i)`, we get the required estimate. -/ have Hl : I.lower i ∈ Icc (I.lower i) (I.upper i), from left_mem_Icc.2 (I.lower_le_upper i), have Hu : I.upper i ∈ Icc (I.lower i) (I.upper i), from right_mem_Icc.2 (I.lower_le_upper i), have Hi : ∀ x ∈ Icc (I.lower i) (I.upper i), integrable.{0 u u} (I.face i) ⊥ (f ∘ i.insert_nth x) box_additive_map.volume, from λ x hx, integrable_of_continuous_on _ (box.continuous_on_face_Icc hfc hx) volume, /- We start with an estimate: the difference of the values of `f` at the corresponding points of the faces `x i = I.lower i` and `x i = I.upper i` is `(2 * ε * diam I.Icc)`-close to the value of `f'` on `pi.single i (I.upper i - I.lower i) = lᵢ • eᵢ`, where `lᵢ = I.upper i - I.lower i` is the length of `i`-th edge of `I` and `eᵢ = pi.single i 1` is the `i`-th unit vector. -/ have : ∀ y ∈ (I.face i).Icc, ∥f' (pi.single i (I.upper i - I.lower i)) - (f (i.insert_nth (I.upper i) y) - f (i.insert_nth (I.lower i) y))∥ ≤ 2 * ε * diam I.Icc, { intros y hy, set g := λ y, f y - a - f' (y - x) with hg, change ∀ y ∈ I.Icc, ∥g y∥ ≤ ε * ∥y - x∥ at hε, clear_value g, obtain rfl : f = λ y, a + f' (y - x) + g y, by simp [hg], convert_to ∥g (i.insert_nth (I.lower i) y) - g (i.insert_nth (I.upper i) y)∥ ≤ _, { congr' 1, have := fin.insert_nth_sub_same i (I.upper i) (I.lower i) y, simp only [← this, f'.map_sub], abel }, { have : ∀ z ∈ Icc (I.lower i) (I.upper i), i.insert_nth z y ∈ I.Icc, from λ z hz, I.maps_to_insert_nth_face_Icc hz hy, replace hε : ∀ y ∈ I.Icc, ∥g y∥ ≤ ε * diam I.Icc, { intros y hy, refine (hε y hy).trans (mul_le_mul_of_nonneg_left _ h0.le), rw ← dist_eq_norm, exact dist_le_diam_of_mem I.is_compact_Icc.bounded hy hxI }, rw [two_mul, add_mul], exact norm_sub_le_of_le (hε _ (this _ Hl)) (hε _ (this _ Hu)) } }, calc ∥(∏ j, (I.upper j - I.lower j)) • f' (pi.single i 1) - (integral (I.face i) ⊥ (f ∘ i.insert_nth (I.upper i)) box_additive_map.volume - integral (I.face i) ⊥ (f ∘ i.insert_nth (I.lower i)) box_additive_map.volume)∥ = ∥integral.{0 u u} (I.face i) ⊥ (λ (x : fin n → ℝ), f' (pi.single i (I.upper i - I.lower i)) - (f (i.insert_nth (I.upper i) x) - f (i.insert_nth (I.lower i) x))) box_additive_map.volume∥ : begin rw [← integral_sub (Hi _ Hu) (Hi _ Hl), ← box.volume_face_mul i, mul_smul, ← box.volume_apply, ← box_additive_map.to_smul_apply, ← integral_const, ← box_additive_map.volume, ← integral_sub (integrable_const _) ((Hi _ Hu).sub (Hi _ Hl))], simp only [(∘), pi.sub_def, ← f'.map_smul, ← pi.single_smul', smul_eq_mul, mul_one] end ... ≤ (volume (I.face i : set ℝⁿ)).to_real * (2 * ε * c * (I.upper i - I.lower i)) : begin -- The hard part of the estimate was done above, here we just replace `diam I.Icc` -- with `c * (I.upper i - I.lower i)` refine norm_integral_le_of_le_const (λ y hy, (this y hy).trans _) volume, rw mul_assoc (2 * ε), exact mul_le_mul_of_nonneg_left (I.diam_Icc_le_of_distortion_le i hc) (mul_nonneg zero_le_two h0.le) end ... = 2 * ε * c * ∏ j, (I.upper j - I.lower j) : begin rw [← measure.to_box_additive_apply, box.volume_apply, ← I.volume_face_mul i], ac_refl end end /-- If `f : ℝⁿ⁺¹ → E` is differentiable on a closed rectangular box `I` with derivative `f'`, then the partial derivative `λ x, f' x (pi.single i 1)` is Henstock-Kurzweil integrable with integral equal to the difference of integrals of `f` over the faces `x i = I.upper i` and `x i = I.lower i`. More precisely, we use a non-standard generalization of the Henstock-Kurzweil integral and we allow `f` to be non-differentiable (but still continuous) at a countable set of points. TODO: If `n > 0`, then the condition at `x ∈ s` can be replaced by a much weaker estimate but this requires either better integrability theorems, or usage of a filter depending on the countable set `s` (we need to ensure that none of the faces of a partition contain a point from `s`). -/ lemma has_integral_bot_pderiv (f : ℝⁿ⁺¹ → E) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] E) (s : set ℝⁿ⁺¹) (hs : countable s) (Hs : ∀ x ∈ s, continuous_within_at f I.Icc x) (Hd : ∀ x ∈ I.Icc \ s, has_fderiv_within_at f (f' x) I.Icc x) (i : fin (n + 1)) : has_integral.{0 u u} I ⊥ (λ x, f' x (pi.single i 1)) box_additive_map.volume (integral.{0 u u} (I.face i) ⊥ (λ x, f (i.insert_nth (I.upper i) x)) box_additive_map.volume - integral.{0 u u} (I.face i) ⊥ (λ x, f (i.insert_nth (I.lower i) x)) box_additive_map.volume) := begin /- Note that `f` is continuous on `I.Icc`, hence it is integrable on the faces of all boxes `J ≤ I`, thus the difference of integrals over `x i = J.upper i` and `x i = J.lower i` is a box-additive function of `J ≤ I`. -/ have Hc : continuous_on f I.Icc, { intros x hx, by_cases hxs : x ∈ s, exacts [Hs x hxs, (Hd x ⟨hx, hxs⟩).continuous_within_at] }, set fI : ℝ → box (fin n) → E := λ y J, integral.{0 u u} J ⊥ (λ x, f (i.insert_nth y x)) box_additive_map.volume, set fb : Icc (I.lower i) (I.upper i) → fin n →ᵇᵃ[↑(I.face i)] E := λ x, (integrable_of_continuous_on ⊥ (box.continuous_on_face_Icc Hc x.2) volume).to_box_additive, set F : fin (n + 1) →ᵇᵃ[I] E := box_additive_map.upper_sub_lower I i fI fb (λ x hx J, rfl), /- Thus our statement follows from some local estimates. -/ change has_integral I ⊥ (λ x, f' x (pi.single i 1)) _ (F I), refine has_integral_of_le_Henstock_of_forall_is_o bot_le _ _ _ s hs _ _, { /- We use the volume as an upper estimate. -/ exact (volume : measure ℝⁿ⁺¹).to_box_additive.restrict _ le_top }, { exact λ J, ennreal.to_real_nonneg }, { intros c x hx ε ε0, /- Near `x ∈ s` we choose `δ` so that both vectors are small. `volume J • eᵢ` is small because `volume J ≤ (2 * δ) ^ (n + 1)` is small, and the difference of the integrals is small because each of the integrals is close to `volume (J.face i) • f x`. TODO: there should be a shorter and more readable way to formalize this simple proof. -/ have : ∀ᶠ δ in 𝓝[Ioi 0] (0 : ℝ), δ ∈ Ioc (0 : ℝ) (1 / 2) ∧ (∀ y₁ y₂ ∈ closed_ball x δ ∩ I.Icc, ∥f y₁ - f y₂∥ ≤ ε / 2) ∧ ((2 * δ) ^ (n + 1) * ∥f' x (pi.single i 1)∥ ≤ ε / 2), { refine eventually.and _ (eventually.and _ _), { exact Ioc_mem_nhds_within_Ioi ⟨le_rfl, one_half_pos⟩ }, { rcases ((nhds_within_has_basis nhds_basis_closed_ball _).tendsto_iff nhds_basis_closed_ball).1 (Hs x hx.2) _ (half_pos $ half_pos ε0) with ⟨δ₁, δ₁0, hδ₁⟩, filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, δ₁0⟩], rintro δ hδ y₁ y₂ hy₁ hy₂, have : closed_ball x δ ∩ I.Icc ⊆ closed_ball x δ₁ ∩ I.Icc, from inter_subset_inter_left _ (closed_ball_subset_closed_ball hδ.2), rw ← dist_eq_norm, calc dist (f y₁) (f y₂) ≤ dist (f y₁) (f x) + dist (f y₂) (f x) : dist_triangle_right _ _ _ ... ≤ ε / 2 / 2 + ε / 2 / 2 : add_le_add (hδ₁ _ $ this hy₁) (hδ₁ _ $ this hy₂) ... = ε / 2 : add_halves _ }, { have : continuous_within_at (λ δ, (2 * δ) ^ (n + 1) * ∥f' x (pi.single i 1)∥) (Ioi (0 : ℝ)) 0 := ((continuous_within_at_id.const_mul _).pow _).mul_const _, refine this.eventually (ge_mem_nhds _), simpa using half_pos ε0 } }, rcases this.exists with ⟨δ, ⟨hδ0, hδ12⟩, hdfδ, hδ⟩, refine ⟨δ, hδ0, λ J hJI hJδ hxJ hJc, add_halves ε ▸ _⟩, have Hl : J.lower i ∈ Icc (J.lower i) (J.upper i), from left_mem_Icc.2 (J.lower_le_upper i), have Hu : J.upper i ∈ Icc (J.lower i) (J.upper i), from right_mem_Icc.2 (J.lower_le_upper i), have Hi : ∀ x ∈ Icc (J.lower i) (J.upper i), integrable.{0 u u} (J.face i) ⊥ (λ y, f (i.insert_nth x y)) box_additive_map.volume, from λ x hx, integrable_of_continuous_on _ (box.continuous_on_face_Icc (Hc.mono $ box.le_iff_Icc.1 hJI) hx) volume, have hJδ' : J.Icc ⊆ closed_ball x δ ∩ I.Icc, from subset_inter hJδ (box.le_iff_Icc.1 hJI), have Hmaps : ∀ z ∈ Icc (J.lower i) (J.upper i), maps_to (i.insert_nth z) (J.face i).Icc (closed_ball x δ ∩ I.Icc), from λ z hz, (J.maps_to_insert_nth_face_Icc hz).mono subset.rfl hJδ', simp only [dist_eq_norm, F, fI], dsimp, rw [← integral_sub (Hi _ Hu) (Hi _ Hl)], refine (norm_sub_le _ _).trans (add_le_add _ _), { simp_rw [box_additive_map.volume_apply, norm_smul, real.norm_eq_abs, abs_prod], refine (mul_le_mul_of_nonneg_right _ $ norm_nonneg _).trans hδ, have : ∀ j, |J.upper j - J.lower j| ≤ 2 * δ, { intro j, calc dist (J.upper j) (J.lower j) ≤ dist J.upper J.lower : dist_le_pi_dist _ _ _ ... ≤ dist J.upper x + dist J.lower x : dist_triangle_right _ _ _ ... ≤ δ + δ : add_le_add (hJδ J.upper_mem_Icc) (hJδ J.lower_mem_Icc) ... = 2 * δ : (two_mul δ).symm }, calc (∏ j, |J.upper j - J.lower j|) ≤ ∏ j : fin (n + 1), (2 * δ) : prod_le_prod (λ _ _ , abs_nonneg _) (λ j hj, this j) ... = (2 * δ) ^ (n + 1) : by simp }, { refine (norm_integral_le_of_le_const (λ y hy, hdfδ _ _ (Hmaps _ Hu hy) (Hmaps _ Hl hy)) _).trans _, refine (mul_le_mul_of_nonneg_right _ (half_pos ε0).le).trans_eq (one_mul _), rw [box.coe_eq_pi, real.volume_pi_Ioc_to_real (box.lower_le_upper _)], refine prod_le_one (λ _ _, sub_nonneg.2 $ box.lower_le_upper _ _) (λ j hj, _), calc J.upper (i.succ_above j) - J.lower (i.succ_above j) ≤ dist (J.upper (i.succ_above j)) (J.lower (i.succ_above j)) : le_abs_self _ ... ≤ dist J.upper J.lower : dist_le_pi_dist J.upper J.lower (i.succ_above j) ... ≤ dist J.upper x + dist J.lower x : dist_triangle_right _ _ _ ... ≤ δ + δ : add_le_add (hJδ J.upper_mem_Icc) (hJδ J.lower_mem_Icc) ... ≤ 1 / 2 + 1 / 2 : add_le_add hδ12 hδ12 ... = 1 : add_halves 1 } }, { intros c x hx ε ε0, /- At a point `x ∉ s`, we unfold the definition of Fréchet differentiability, then use an estimate we proved earlier in this file. -/ rcases exists_pos_mul_lt ε0 (2 * c) with ⟨ε', ε'0, hlt⟩, rcases (nhds_within_has_basis nhds_basis_closed_ball _).mem_iff.1 ((Hd x hx).def ε'0) with ⟨δ, δ0, Hδ⟩, refine ⟨δ, δ0, λ J hle hJδ hxJ hJc, _⟩, simp only [box_additive_map.volume_apply, box.volume_apply, dist_eq_norm], refine (norm_volume_sub_integral_face_upper_sub_lower_smul_le _ (Hc.mono $ box.le_iff_Icc.1 hle) hxJ ε'0 (λ y hy, Hδ _) (hJc rfl)).trans _, { exact ⟨hJδ hy, box.le_iff_Icc.1 hle hy⟩ }, { rw [mul_right_comm (2 : ℝ), ← box.volume_apply], exact mul_le_mul_of_nonneg_right hlt.le ennreal.to_real_nonneg } } end /-- Divergence theorem for a Henstock-Kurzweil style integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a closed rectangular box `I` with derivative `f'`, then the divergence `∑ i, f' x (pi.single i 1) i` is Henstock-Kurzweil integrable with integral equal to the sum of integrals of `f` over the faces of `I` taken with appropriate signs. More precisely, we use a non-standard generalization of the Henstock-Kurzweil integral and we allow `f` to be non-differentiable (but still continuous) at a countable set of points. -/ lemma has_integral_bot_divergence_of_forall_has_deriv_within_at (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s) (Hs : ∀ x ∈ s, continuous_within_at f I.Icc x) (Hd : ∀ x ∈ I.Icc \ s, has_fderiv_within_at f (f' x) I.Icc x) : has_integral.{0 u u} I ⊥ (λ x, ∑ i, f' x (pi.single i 1) i) box_additive_map.volume (∑ i, (integral.{0 u u} (I.face i) ⊥ (λ x, f (i.insert_nth (I.upper i) x) i) box_additive_map.volume - integral.{0 u u} (I.face i) ⊥ (λ x, f (i.insert_nth (I.lower i) x) i) box_additive_map.volume)) := begin refine has_integral_sum (λ i hi, _), clear hi, simp only [has_fderiv_within_at_pi', continuous_within_at_pi] at Hd Hs, convert has_integral_bot_pderiv I _ _ s hs (λ x hx, Hs x hx i) (λ x hx, Hd x hx i) i end end box_integral
0f075fa96e9c142a5ae6c5d66e8cc870b1d60120
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/init/priority.hlean
b6731949ada54c55032e179694c5ffbc5655b2df
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
293
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.datatypes definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295
a5698a5e0018ed6aa28f790829ee2bbb36288bb7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/polynomial/taylor.lean
5ea229788f0b4d066a2c5d16f02fc5a77a21189c
[ "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,775
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.hasse_deriv import data.polynomial.degree.lemmas /-! # Taylor expansions of polynomials ## Main declarations * `polynomial.taylor`: the Taylor expansion of the polynomial `f` at `r` * `polynomial.taylor_coeff`: the `k`th coefficient of `taylor r f` is `(polynomial.hasse_deriv k f).eval r` * `polynomial.eq_zero_of_hasse_deriv_eq_zero`: the identity principle: a polynomial is 0 iff all its Hasse derivatives are zero -/ noncomputable theory namespace polynomial open_locale polynomial variables {R : Type*} [semiring R] (r : R) (f : R[X]) /-- The Taylor expansion of a polynomial `f` at `r`. -/ def taylor (r : R) : R[X] →ₗ[R] R[X] := { to_fun := λ f, f.comp (X + C r), map_add' := λ f g, add_comp, map_smul' := λ c f, by simp only [smul_eq_C_mul, C_mul_comp, ring_hom.id_apply] } lemma taylor_apply : taylor r f = f.comp (X + C r) := rfl @[simp] lemma taylor_X : taylor r X = X + C r := by simp only [taylor_apply, X_comp] @[simp] lemma taylor_C (x : R) : taylor r (C x) = C x := by simp only [taylor_apply, C_comp] @[simp] lemma taylor_zero' : taylor (0 : R) = linear_map.id := begin ext, simp only [taylor_apply, add_zero, comp_X, _root_.map_zero, linear_map.id_comp, function.comp_app, linear_map.coe_comp] end lemma taylor_zero (f : R[X]) : taylor 0 f = f := by rw [taylor_zero', linear_map.id_apply] @[simp] lemma taylor_one : taylor r (1 : R[X]) = C 1 := by rw [← C_1, taylor_C] @[simp] lemma taylor_monomial (i : ℕ) (k : R) : taylor r (monomial i k) = C k * (X + C r) ^ i := by simp [taylor_apply] /-- The `k`th coefficient of `polynomial.taylor r f` is `(polynomial.hasse_deriv k f).eval r`. -/ lemma taylor_coeff (n : ℕ) : (taylor r f).coeff n = (hasse_deriv n f).eval r := show (lcoeff R n).comp (taylor r) f = (leval r).comp (hasse_deriv n) f, begin congr' 1, clear f, ext i, simp only [leval_apply, mul_one, one_mul, eval_monomial, linear_map.comp_apply, coeff_C_mul, hasse_deriv_monomial, taylor_apply, monomial_comp, C_1, (commute_X (C r)).add_pow i, linear_map.map_sum], simp only [lcoeff_apply, ← C_eq_nat_cast, mul_assoc, ← C_pow, ← C_mul, coeff_mul_C, (nat.cast_commute _ _).eq, coeff_X_pow, boole_mul, finset.sum_ite_eq, finset.mem_range], split_ifs with h, { refl }, push_neg at h, rw [nat.choose_eq_zero_of_lt h, nat.cast_zero, mul_zero], end @[simp] lemma taylor_coeff_zero : (taylor r f).coeff 0 = f.eval r := by rw [taylor_coeff, hasse_deriv_zero, linear_map.id_apply] @[simp] lemma taylor_coeff_one : (taylor r f).coeff 1 = f.derivative.eval r := by rw [taylor_coeff, hasse_deriv_one] @[simp] lemma nat_degree_taylor (p : R[X]) (r : R) : nat_degree (taylor r p) = nat_degree p := begin refine map_nat_degree_eq_nat_degree _ _, nontriviality R, intros n c c0, simp [taylor_monomial, nat_degree_C_mul_eq_of_mul_ne_zero, nat_degree_pow_X_add_C, c0] end @[simp] lemma taylor_mul {R} [comm_semiring R] (r : R) (p q : R[X]) : taylor r (p * q) = taylor r p * taylor r q := by simp only [taylor_apply, mul_comp] /-- `polynomial.taylor` as a `alg_hom` for commutative semirings -/ @[simps apply] def taylor_alg_hom {R} [comm_semiring R] (r : R) : R[X] →ₐ[R] R[X] := alg_hom.of_linear_map (taylor r) (taylor_one r) (taylor_mul r) lemma taylor_taylor {R} [comm_semiring R] (f : R[X]) (r s : R) : taylor r (taylor s f) = taylor (r + s) f := by simp only [taylor_apply, comp_assoc, map_add, add_comp, X_comp, C_comp, C_add, add_assoc] lemma taylor_eval {R} [comm_semiring R] (r : R) (f : R[X]) (s : R) : (taylor r f).eval s = f.eval (s + r) := by simp only [taylor_apply, eval_comp, eval_C, eval_X, eval_add] lemma taylor_eval_sub {R} [comm_ring R] (r : R) (f : R[X]) (s : R) : (taylor r f).eval (s - r) = f.eval s := by rw [taylor_eval, sub_add_cancel] lemma taylor_injective {R} [comm_ring R] (r : R) : function.injective (taylor r) := begin intros f g h, apply_fun taylor (-r) at h, simpa only [taylor_apply, comp_assoc, add_comp, X_comp, C_comp, C_neg, neg_add_cancel_right, comp_X] using h, end lemma eq_zero_of_hasse_deriv_eq_zero {R} [comm_ring R] (f : R[X]) (r : R) (h : ∀ k, (hasse_deriv k f).eval r = 0) : f = 0 := begin apply taylor_injective r, rw linear_map.map_zero, ext k, simp only [taylor_coeff, h, coeff_zero], end /-- Taylor's formula. -/ lemma sum_taylor_eq {R} [comm_ring R] (f : R[X]) (r : R) : (taylor r f).sum (λ i a, C a * (X - C r) ^ i) = f := by rw [←comp_eq_sum_left, sub_eq_add_neg, ←C_neg, ←taylor_apply, taylor_taylor, neg_add_self, taylor_zero] end polynomial
b29719dc0128b0ddf660d828a43e04f73eb70f12
a338c3e75cecad4fb8d091bfe505f7399febfd2b
/src/data/complex/module.lean
70246e4460715c7ab17abdc5ee678de6c4d0a6f9
[ "Apache-2.0" ]
permissive
bacaimano/mathlib
88eb7911a9054874fba2a2b74ccd0627c90188af
f2edc5a3529d95699b43514d6feb7eb11608723f
refs/heads/master
1,686,410,075,833
1,625,497,070,000
1,625,497,070,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,247
lean
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser -/ import data.complex.basic import algebra.algebra.ordered import data.matrix.notation import field_theory.tower import linear_algebra.finite_dimensional /-! # Complex number as a vector space over `ℝ` This file contains the following instances: * Any `•`-structure (`has_scalar`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on `ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ` algebra. * any complex vector space is a real vector space; * any finite dimensional complex vector space is a finite dimensional real vector space; * the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex vector space. It also defines bundled versions of four standard maps (respectively, the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate): * `complex.re_lm` (`ℝ`-linear map); * `complex.im_lm` (`ℝ`-linear map); * `complex.of_real_am` (`ℝ`-algebra (homo)morphism); * `complex.conj_ae` (`ℝ`-algebra equivalence). It also provides a universal property of the complex numbers `complex.lift`, which constructs a `ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`. -/ noncomputable theory namespace complex variables {R : Type*} {S : Type*} section variables [has_scalar R ℝ] /- The useless `0` multiplication in `smul` is to make sure that `restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/ instance : has_scalar R ℂ := { smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ } lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)] lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)] @[simp] lemma smul_coe {x : ℝ} {z : ℂ} : x • z = x * z := by ext; simp [smul_re, smul_im] end instance [has_scalar R ℝ] [has_scalar S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ := { smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] } instance [has_scalar R S] [has_scalar R ℝ] [has_scalar S ℝ] [is_scalar_tower R S ℝ] : is_scalar_tower R S ℂ := { smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] } instance [monoid R] [mul_action R ℝ] : mul_action R ℂ := { one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul], mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] } instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ := { smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add], smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] } instance [semiring R] [module R ℝ] : module R ℂ := { add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul], zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] } instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ := { smul := (•), smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def], commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes], ..complex.of_real.comp (algebra_map R ℝ) } /-- Note that when applied the RHS is further simplified by `complex.of_real_eq_coe`. -/ @[simp] lemma coe_algebra_map : ⇑(algebra_map ℝ ℂ) = complex.of_real := rfl section variables {A : Type*} [semiring A] [algebra ℝ A] /-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from `alg_hom.commutes`. -/ @[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) : f x = algebra_map ℝ A x := f.commutes x /-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/ @[ext] lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g := begin ext ⟨x, y⟩, simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h] end end section open_locale complex_order lemma complex_ordered_module : ordered_module ℝ ℂ := { smul_lt_smul_of_pos := λ z w x h₁ h₂, begin obtain ⟨y, l, rfl⟩ := lt_def.mp h₁, refine lt_def.mpr ⟨x * y, _, _⟩, exact mul_pos h₂ l, ext; simp [mul_add], end, lt_of_smul_lt_smul_of_pos := λ z w x h₁ h₂, begin obtain ⟨y, l, e⟩ := lt_def.mp h₁, by_cases h : x = 0, { subst h, exfalso, apply lt_irrefl 0 h₂, }, { refine lt_def.mpr ⟨y / x, div_pos l h₂, _⟩, replace e := congr_arg (λ z, (x⁻¹ : ℂ) * z) e, simp only [mul_add, ←mul_assoc, h, one_mul, of_real_eq_zero, smul_coe, ne.def, not_false_iff, inv_mul_cancel] at e, convert e, simp only [div_eq_iff_mul_eq, h, of_real_eq_zero, of_real_div, ne.def, not_false_iff], norm_cast, simp [mul_comm _ y, mul_assoc, h], }, end } localized "attribute [instance] complex_ordered_module" in complex_order end open submodule finite_dimensional /-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/ def basis_one_I : basis (fin 2) ℝ ℂ := basis.of_equiv_fun { to_fun := λ z, ![z.re, z.im], inv_fun := λ c, c 0 + c 1 • I, left_inv := λ z, by simp, right_inv := λ c, by { ext i, fin_cases i; simp }, map_add' := λ z z', by simp, map_smul' := λ c z, by simp } @[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl @[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] := funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j, by fin_cases i; fin_cases j; simp only [coe_basis_one_I_repr, finsupp.single_eq_same, finsupp.single_eq_of_ne, matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons, nat.one_ne_zero, fin.one_eq_zero_iff, fin.zero_eq_one_iff, ne.def, not_false_iff, one_re, one_im, I_re, I_im] instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I @[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 := by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin] @[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 := by simp [← finrank_eq_dim, finrank_real_complex] lemma {u} dim_real_complex' : cardinal.lift.{0 u} (module.rank ℝ ℂ) = 2 := by simp [← finrank_eq_dim, finrank_real_complex, bit0] /-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the circle. -/ lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩ end complex /- Register as an instance (with low priority) the fact that a complex vector space is also a real vector space. -/ @[priority 900] instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E := restrict_scalars.module ℝ ℂ E instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] : is_scalar_tower ℝ ℂ E := restrict_scalars.is_scalar_tower ℝ ℂ E @[priority 100] instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] [finite_dimensional ℂ E] : finite_dimensional ℝ E := finite_dimensional.trans ℝ ℂ E lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] : module.rank ℝ E = 2 * module.rank ℂ E := cardinal.lift_inj.1 $ by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] } lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] : finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E := by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex] namespace complex /-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_lm : ℂ →ₗ[ℝ] ℝ := { to_fun := λx, x.re, map_add' := add_re, map_smul' := by simp, } @[simp] lemma re_lm_coe : ⇑re_lm = re := rfl /-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/ def im_lm : ℂ →ₗ[ℝ] ℝ := { to_fun := λx, x.im, map_add' := add_im, map_smul' := by simp, } @[simp] lemma im_lm_coe : ⇑im_lm = im := rfl /-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ @[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl /-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/ def conj_ae : ℂ ≃ₐ[ℝ] ℂ := { inv_fun := conj, left_inv := conj_conj, right_inv := conj_conj, commutes' := conj_of_real, .. conj } @[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl section lift variables {A : Type*} [ring A] [algebra ℝ A] /-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`. See `complex.lift` for this as an equiv. -/ def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A := alg_hom.of_linear_map ((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm) (show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1, by rw [ring_hom.map_one, zero_smul, add_zero]) (λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I' = (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'), begin rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm], congr' 1, -- equate "real" and "imaginary" parts { rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg, ←ring_hom.map_mul, ←ring_hom.map_sub], }, { rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂, ←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] } end) @[simp] lemma lift_aux_apply (I' : A) (hI') (z : ℂ) : lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp /-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element of `A` which squares to `-1`. This can be used to embed the complex numbers in the `quaternion`s. This isomorphism is named to match the very similar `zsqrtd.lift`. -/ @[simps {simp_rhs := tt}] noncomputable def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) := { to_fun := λ I', lift_aux I' I'.prop, inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩, left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop, right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, } /- When applied to `complex.I` itself, `lift` is the identity. -/ @[simp] lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ := alg_hom_ext $ lift_aux_apply_I _ _ /- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/ @[simp] lemma lift_aux_neg_I : lift_aux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conj_ae := alg_hom_ext $ (lift_aux_apply_I _ _).trans conj_I.symm end lift end complex
1c7f186e43fc3e2827178b5eb8cbe6c50d7a6a4a
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/group_power/order.lean
c2fe4946e3e03783458c050394bfa5c7c3190b15
[ "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
12,635
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.order.ring import algebra.group_power.basic /-! # Lemmas about the interaction of power operations with order Note that some lemmas are in `algebra/group_power/lemmas.lean` as they import files which depend on this file. -/ variables {A G M R : Type*} section preorder variables [monoid M] [preorder M] [covariant_class M M (*) (≤)] @[to_additive nsmul_le_nsmul_of_le_right, mono] lemma pow_le_pow_of_le_left' [covariant_class M M (function.swap (*)) (≤)] {a b : M} (hab : a ≤ b) : ∀ i : ℕ, a ^ i ≤ b ^ i | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ], exact mul_le_mul' hab (pow_le_pow_of_le_left' k) } attribute [mono] nsmul_le_nsmul_of_le_right @[to_additive nsmul_nonneg] theorem one_le_pow_of_one_le' {a : M} (H : 1 ≤ a) : ∀ n : ℕ, 1 ≤ a ^ n | 0 := by simp | (k + 1) := by { rw pow_succ, exact one_le_mul H (one_le_pow_of_one_le' k) } @[to_additive nsmul_nonpos] theorem pow_le_one' {a : M} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1 := @one_le_pow_of_one_le' (order_dual M) _ _ _ _ H n @[to_additive nsmul_le_nsmul] theorem pow_le_pow' {a : M} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n ≤ a ^ n * a ^ k : le_mul_of_one_le_right' (one_le_pow_of_one_le' ha _) ... = a ^ m : by rw [← hk, pow_add] @[to_additive nsmul_le_nsmul_of_nonpos] theorem pow_le_pow_of_le_one' {a : M} {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n := @pow_le_pow' (order_dual M) _ _ _ _ _ _ ha h @[to_additive nsmul_pos] theorem one_lt_pow' {a : M} (ha : 1 < a) {k : ℕ} (hk : k ≠ 0) : 1 < a ^ k := begin rcases nat.exists_eq_succ_of_ne_zero hk with ⟨l, rfl⟩, clear hk, induction l with l IH, { simpa using ha }, { rw pow_succ, exact one_lt_mul' ha IH } end @[to_additive nsmul_neg] theorem pow_lt_one' {a : M} (ha : a < 1) {k : ℕ} (hk : k ≠ 0) : a ^ k < 1 := @one_lt_pow' (order_dual M) _ _ _ _ ha k hk @[to_additive nsmul_lt_nsmul] theorem pow_lt_pow' [covariant_class M M (*) (<)] {a : M} {n m : ℕ} (ha : 1 < a) (h : n < m) : a ^ n < a ^ m := begin rcases nat.le.dest h with ⟨k, rfl⟩, clear h, rw [pow_add, pow_succ', mul_assoc, ← pow_succ], exact lt_mul_of_one_lt_right' _ (one_lt_pow' ha k.succ_ne_zero) end end preorder section linear_order variables [monoid M] [linear_order M] [covariant_class M M (*) (≤)] @[to_additive nsmul_nonneg_iff] lemma one_le_pow_iff {x : M} {n : ℕ} (hn : n ≠ 0) : 1 ≤ x ^ n ↔ 1 ≤ x := ⟨le_imp_le_of_lt_imp_lt $ λ h, pow_lt_one' h hn, λ h, one_le_pow_of_one_le' h n⟩ @[to_additive nsmul_nonpos_iff] lemma pow_le_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n ≤ 1 ↔ x ≤ 1 := @one_le_pow_iff (order_dual M) _ _ _ _ _ hn @[to_additive nsmul_pos_iff] lemma one_lt_pow_iff {x : M} {n : ℕ} (hn : n ≠ 0) : 1 < x ^ n ↔ 1 < x := lt_iff_lt_of_le_iff_le (pow_le_one_iff hn) @[to_additive nsmul_neg_iff] lemma pow_lt_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n < 1 ↔ x < 1 := lt_iff_lt_of_le_iff_le (one_le_pow_iff hn) @[to_additive nsmul_eq_zero_iff] lemma pow_eq_one_iff {x : M} {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := by simp only [le_antisymm_iff, pow_le_one_iff hn, one_le_pow_iff hn] end linear_order section group variables [group G] [preorder G] [covariant_class G G (*) (≤)] @[to_additive gsmul_nonneg] theorem one_le_gpow {x : G} (H : 1 ≤ x) {n : ℤ} (hn : 0 ≤ n) : 1 ≤ x ^ n := begin lift n to ℕ using hn, rw gpow_coe_nat, apply one_le_pow_of_one_le' H, end end group namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) (n : ℕ) : 0 < a ^ n := pos_iff_ne_zero.2 $ pow_ne_zero _ H.ne' end canonically_ordered_comm_semiring section ordered_semiring variable [ordered_semiring R] @[simp] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := by { nontriviality, rw pow_zero, exact zero_lt_one } | (n+1) := by { rw pow_succ, exact mul_pos H (pow_pos _) } @[simp] theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := by { rw pow_zero, exact zero_le_one} | (n+1) := by { rw pow_succ, exact mul_nonneg H (pow_nonneg _) } theorem pow_add_pow_le {x y : R} {n : ℕ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hn : n ≠ 0) : x ^ n + y ^ n ≤ (x + y) ^ n := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨k, rfl⟩, induction k with k ih, { simp only [pow_one] }, let n := k.succ, have h1 := add_nonneg (mul_nonneg hx (pow_nonneg hy n)) (mul_nonneg hy (pow_nonneg hx n)), have h2 := add_nonneg hx hy, calc x^n.succ + y^n.succ ≤ x*x^n + y*y^n + (x*y^n + y*x^n) : by { rw [pow_succ _ n, pow_succ _ n], exact le_add_of_nonneg_right h1 } ... = (x+y) * (x^n + y^n) : by rw [add_mul, mul_add, mul_add, add_comm (y*x^n), ← add_assoc, ← add_assoc, add_assoc (x*x^n) (x*y^n), add_comm (x*y^n) (y*y^n), ← add_assoc] ... ≤ (x+y)^n.succ : by { rw [pow_succ _ n], exact mul_le_mul_of_nonneg_left (ih (nat.succ_ne_zero k)) h2 } end theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ← tsub_add_cancel_of_le (nat.succ_le_of_lt Hnpos), induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end lemma pow_lt_one {a : R} (h₀ : 0 ≤ a) (h₁ : a < 1) {n : ℕ} (hn : n ≠ 0) : a ^ n < 1 := (one_pow n).subst (pow_lt_pow_of_lt_left h₁ h₀ (nat.pos_of_ne_zero hn)) theorem strict_mono_on_pow {n : ℕ} (hn : 0 < n) : strict_mono_on (λ x : R, x ^ n) (set.Ici 0) := λ x hx y hy h, pow_lt_pow_of_lt_left h hx hn theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := by rw [pow_zero] | (n+1) := by { rw pow_succ, simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) } lemma pow_mono {a : R} (h : 1 ≤ a) : monotone (λ n : ℕ, a ^ n) := monotone_nat_of_le_succ $ λ n, by { rw pow_succ, exact le_mul_of_one_le_left (pow_nonneg (zero_le_one.trans h) _) h } theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := pow_mono ha h lemma strict_mono_pow {a : R} (h : 1 < a) : strict_mono (λ n : ℕ, a ^ n) := have 0 < a := zero_le_one.trans_lt h, strict_mono_nat_of_lt_succ $ λ n, by simpa only [one_mul, pow_succ] using mul_lt_mul h (le_refl (a ^ n)) (pow_pos this _) this.le lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := strict_mono_pow h h2 lemma pow_lt_pow_iff {a : R} {n m : ℕ} (h : 1 < a) : a ^ n < a ^ m ↔ n < m := (strict_mono_pow h).lt_iff_lt @[mono] lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ], exact mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) } lemma one_lt_pow {a : R} (ha : 1 < a) : ∀ {n : ℕ}, n ≠ 0 → 1 < a ^ n | 0 h := (h rfl).elim | 1 h := (pow_one a).symm.subst ha | (n + 2) h := begin nontriviality R, rw [←one_mul (1 : R), pow_succ], exact mul_lt_mul ha (one_lt_pow (nat.succ_ne_zero _)).le zero_lt_one (zero_lt_one.trans ha).le, end lemma pow_le_one {a : R} : ∀ (n : ℕ) (h₀ : 0 ≤ a) (h₁ : a ≤ 1), a ^ n ≤ 1 | 0 h₀ h₁ := (pow_zero a).le | (n + 1) h₀ h₁ := (pow_succ' a n).le.trans (mul_le_one (pow_le_one n h₀ h₁) h₀ h₁) end ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] lemma pow_le_one_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : a ^ n ≤ 1 ↔ a ≤ 1 := begin refine ⟨_, pow_le_one n ha⟩, rw [←not_lt, ←not_lt], exact mt (λ h, one_lt_pow h hn), end lemma one_le_pow_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : 1 ≤ a ^ n ↔ 1 ≤ a := begin refine ⟨_, λ h, one_le_pow_of_one_le h n⟩, rw [←not_lt, ←not_lt], exact mt (λ h, pow_lt_one ha h hn), end lemma one_lt_pow_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : 1 < a ^ n ↔ 1 < a := lt_iff_lt_of_le_iff_le (pow_le_one_iff_of_nonneg ha hn) lemma pow_lt_one_iff_of_nonneg {a : R} (ha : 0 ≤ a) {n : ℕ} (hn : n ≠ 0) : a ^ n < 1 ↔ a < 1 := lt_iff_lt_of_le_iff_le (one_le_pow_iff_of_nonneg ha hn) lemma sq_le_one_iff {a : R} (ha : 0 ≤ a) : a^2 ≤ 1 ↔ a ≤ 1 := pow_le_one_iff_of_nonneg ha (nat.succ_ne_zero _) lemma sq_lt_one_iff {a : R} (ha : 0 ≤ a) : a^2 < 1 ↔ a < 1 := pow_lt_one_iff_of_nonneg ha (nat.succ_ne_zero _) lemma one_le_sq_iff {a : R} (ha : 0 ≤ a) : 1 ≤ a^2 ↔ 1 ≤ a := one_le_pow_iff_of_nonneg ha (nat.succ_ne_zero _) lemma one_lt_sq_iff {a : R} (ha : 0 ≤ a) : 1 < a^2 ↔ 1 < a := one_lt_pow_iff_of_nonneg ha (nat.succ_ne_zero _) @[simp] theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) : x ^ n = y ^ n ↔ x = y := (@strict_mono_on_pow R _ _ Hnpos).inj_on.eq_iff Hxpos Hypos lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h lemma le_of_pow_le_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b := le_of_not_lt $ λ h1, not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h @[simp] lemma sq_eq_sq {a b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ 2 = b ^ 2 ↔ a = b := pow_left_inj ha hb dec_trivial end linear_ordered_semiring section linear_ordered_ring variable [linear_ordered_ring R] lemma pow_abs (a : R) (n : ℕ) : |a| ^ n = |a ^ n| := ((abs_hom.to_monoid_hom : R →* R).map_pow a n).symm lemma abs_neg_one_pow (n : ℕ) : |(-1 : R) ^ n| = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] theorem pow_bit0_nonneg (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n := by { rw pow_bit0, exact mul_self_nonneg _ } theorem sq_nonneg (a : R) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 alias sq_nonneg ← pow_two_nonneg theorem pow_bit0_pos {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n := (pow_bit0_nonneg a n).lt_of_ne (pow_ne_zero _ h).symm theorem sq_pos_of_ne_zero (a : R) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 alias sq_pos_of_ne_zero ← pow_two_pos_of_ne_zero variables {x y : R} theorem sq_abs (x : R) : |x| ^ 2 = x ^ 2 := by simpa only [sq] using abs_mul_abs_self x theorem abs_sq (x : R) : |x ^ 2| = x ^ 2 := by simpa only [sq] using abs_mul_self x theorem sq_lt_sq (h : |x| < y) : x ^ 2 < y ^ 2 := by simpa only [sq_abs] using pow_lt_pow_of_lt_left h (abs_nonneg x) (1:ℕ).succ_pos theorem sq_lt_sq' (h1 : -y < x) (h2 : x < y) : x ^ 2 < y ^ 2 := sq_lt_sq (abs_lt.mpr ⟨h1, h2⟩) theorem sq_le_sq (h : |x| ≤ |y|) : x ^ 2 ≤ y ^ 2 := by simpa only [sq_abs] using pow_le_pow_of_le_left (abs_nonneg x) h 2 theorem sq_le_sq' (h1 : -y ≤ x) (h2 : x ≤ y) : x ^ 2 ≤ y ^ 2 := sq_le_sq (le_trans (abs_le.mpr ⟨h1, h2⟩) (le_abs_self _)) theorem abs_lt_abs_of_sq_lt_sq (h : x^2 < y^2) : |x| < |y| := lt_of_pow_lt_pow 2 (abs_nonneg y) $ by rwa [← sq_abs x, ← sq_abs y] at h theorem abs_lt_of_sq_lt_sq (h : x^2 < y^2) (hy : 0 ≤ y) : |x| < y := begin rw [← abs_of_nonneg hy], exact abs_lt_abs_of_sq_lt_sq h, end theorem abs_lt_of_sq_lt_sq' (h : x^2 < y^2) (hy : 0 ≤ y) : -y < x ∧ x < y := abs_lt.mp $ abs_lt_of_sq_lt_sq h hy theorem abs_le_abs_of_sq_le_sq (h : x^2 ≤ y^2) : |x| ≤ |y| := le_of_pow_le_pow 2 (abs_nonneg y) (1:ℕ).succ_pos $ by rwa [← sq_abs x, ← sq_abs y] at h theorem abs_le_of_sq_le_sq (h : x^2 ≤ y^2) (hy : 0 ≤ y) : |x| ≤ y := begin rw [← abs_of_nonneg hy], exact abs_le_abs_of_sq_le_sq h, end theorem abs_le_of_sq_le_sq' (h : x^2 ≤ y^2) (hy : 0 ≤ y) : -y ≤ x ∧ x ≤ y := abs_le.mp $ abs_le_of_sq_le_sq h hy end linear_ordered_ring section linear_ordered_comm_ring variables [linear_ordered_comm_ring R] /-- Arithmetic mean-geometric mean (AM-GM) inequality for linearly ordered commutative rings. -/ lemma two_mul_le_add_sq (a b : R) : 2 * a * b ≤ a ^ 2 + b ^ 2 := sub_nonneg.mp ((sub_add_eq_add_sub _ _ _).subst ((sub_sq a b).subst (sq_nonneg _))) alias two_mul_le_add_sq ← two_mul_le_add_pow_two end linear_ordered_comm_ring
45c5671a641ac46006209a3cabe998f63f7b9dd5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/perm/basic.lean
74bebd24fce77249ebc157cc5e55e82cd8b161b3
[ "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
14,920
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 algebra.group.pi import algebra.group_power /-! # The group of permutations (self-equivalences) of a type `α` This file defines the `group` structure on `equiv.perm α`. -/ universes u v namespace equiv variables {α : Type u} {β : Type v} namespace perm instance perm_group : group (perm α) := { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv := equiv.symm, mul_assoc := λ f g h, (trans_assoc _ _ _).symm, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := trans_symm } theorem mul_apply (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ theorem one_apply (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self (f : perm α) (x) : f⁻¹ (f x) = x := f.symm_apply_apply x @[simp] lemma apply_inv_self (f : perm α) (x) : f (f⁻¹ x) = x := f.apply_symm_apply x lemma one_def : (1 : perm α) = equiv.refl α := rfl lemma mul_def (f g : perm α) : f * g = g.trans f := rfl lemma inv_def (f : perm α) : f⁻¹ = f.symm := rfl @[simp] lemma coe_mul (f g : perm α) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : perm α) = id := rfl lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := f.eq_symm_apply lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := f.symm_apply_eq lemma gpow_apply_comm {α : Type*} (σ : equiv.perm α) (m n : ℤ) {x : α} : (σ ^ m) ((σ ^ n) x) = (σ ^ n) ((σ ^ m) x) := by rw [←equiv.perm.mul_apply, ←equiv.perm.mul_apply, gpow_mul_comm] /-! Lemmas about mixing `perm` with `equiv`. Because we have multiple ways to express `equiv.refl`, `equiv.symm`, and `equiv.trans`, we want simp lemmas for every combination. The assumption made here is that if you're using the group structure, you want to preserve it after simp. -/ @[simp] lemma trans_one {α : Sort*} {β : Type*} (e : α ≃ β) : e.trans (1 : perm β) = e := equiv.trans_refl e @[simp] lemma mul_refl (e : perm α) : e * equiv.refl α = e := equiv.trans_refl e @[simp] lemma one_symm : (1 : perm α).symm = 1 := equiv.refl_symm @[simp] lemma refl_inv : (equiv.refl α : perm α)⁻¹ = 1 := equiv.refl_symm @[simp] lemma one_trans {α : Type*} {β : Sort*} (e : α ≃ β) : (1 : perm α).trans e = e := equiv.refl_trans e @[simp] lemma refl_mul (e : perm α) : equiv.refl α * e = e := equiv.refl_trans e @[simp] lemma inv_trans (e : perm α) : e⁻¹.trans e = 1 := equiv.symm_trans e @[simp] lemma mul_symm (e : perm α) : e * e.symm = 1 := equiv.symm_trans e @[simp] lemma trans_inv (e : perm α) : e.trans e⁻¹ = 1 := equiv.trans_symm e @[simp] lemma symm_mul (e : perm α) : e.symm * e = 1 := equiv.trans_symm e /-! Lemmas about `equiv.perm.sum_congr` re-expressed via the group structure. -/ @[simp] lemma sum_congr_mul {α β : Type*} (e : perm α) (f : perm β) (g : perm α) (h : perm β) : sum_congr e f * sum_congr g h = sum_congr (e * g) (f * h) := sum_congr_trans g h e f @[simp] lemma sum_congr_inv {α β : Type*} (e : perm α) (f : perm β) : (sum_congr e f)⁻¹ = sum_congr e⁻¹ f⁻¹ := sum_congr_symm e f @[simp] lemma sum_congr_one {α β : Type*} : sum_congr (1 : perm α) (1 : perm β) = 1 := sum_congr_refl /-- `equiv.perm.sum_congr` as a `monoid_hom`, with its two arguments bundled into a single `prod`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between `α` and `β`. -/ @[simps] def sum_congr_hom (α β : Type*) : perm α × perm β →* perm (α ⊕ β) := { to_fun := λ a, sum_congr a.1 a.2, map_one' := sum_congr_one, map_mul' := λ a b, (sum_congr_mul _ _ _ _).symm} lemma sum_congr_hom_injective {α β : Type*} : function.injective (sum_congr_hom α β) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i, { simpa using equiv.congr_fun h (sum.inl i), }, { simpa using equiv.congr_fun h (sum.inr i), }, end @[simp] lemma sum_congr_swap_one {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : α) : sum_congr (equiv.swap i j) (1 : perm β) = equiv.swap (sum.inl i) (sum.inl j) := sum_congr_swap_refl i j @[simp] lemma sum_congr_one_swap {α β : Type*} [decidable_eq α] [decidable_eq β] (i j : β) : sum_congr (1 : perm α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := sum_congr_refl_swap i j /-! Lemmas about `equiv.perm.sigma_congr_right` re-expressed via the group structure. -/ @[simp] lemma sigma_congr_right_mul {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : sigma_congr_right F * sigma_congr_right G = sigma_congr_right (F * G) := sigma_congr_right_trans G F @[simp] lemma sigma_congr_right_inv {α : Type*} {β : α → Type*} (F : Π a, perm (β a)) : (sigma_congr_right F)⁻¹ = sigma_congr_right (λ a, (F a)⁻¹) := sigma_congr_right_symm F @[simp] lemma sigma_congr_right_one {α : Type*} {β : α → Type*} : (sigma_congr_right (1 : Π a, equiv.perm $ β a)) = 1 := sigma_congr_right_refl /-- `equiv.perm.sigma_congr_right` as a `monoid_hom`. This is particularly useful for its `monoid_hom.range` projection, which is the subgroup of permutations which do not exchange elements between fibers. -/ @[simps] def sigma_congr_right_hom {α : Type*} (β : α → Type*) : (Π a, perm (β a)) →* perm (Σ a, β a) := { to_fun := sigma_congr_right, map_one' := sigma_congr_right_one, map_mul' := λ a b, (sigma_congr_right_mul _ _).symm } lemma sigma_congr_right_hom_injective {α : Type*} {β : α → Type*} : function.injective (sigma_congr_right_hom β) := begin intros x y h, ext a b, simpa using equiv.congr_fun h ⟨a, b⟩, end /-- `equiv.perm.subtype_congr` as a `monoid_hom`. -/ @[simps] def subtype_congr_hom (p : α → Prop) [decidable_pred p] : (perm {a // p a}) × (perm {a // ¬ p a}) →* perm α := { to_fun := λ pair, perm.subtype_congr pair.fst pair.snd, map_one' := perm.subtype_congr.refl, map_mul' := λ _ _, (perm.subtype_congr.trans _ _ _ _).symm } lemma subtype_congr_hom_injective (p : α → Prop) [decidable_pred p] : function.injective (subtype_congr_hom p) := begin rintros ⟨⟩ ⟨⟩ h, rw prod.mk.inj_iff, split; ext i; simpa using equiv.congr_fun h i end /-- If `e` is also a permutation, we can write `perm_congr` completely in terms of the group structure. -/ @[simp] lemma perm_congr_eq_mul (e p : perm α) : e.perm_congr p = e * p * e⁻¹ := rfl section extend_domain /-! Lemmas about `equiv.perm.extend_domain` re-expressed via the group structure. -/ variables (e : perm α) {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) @[simp] lemma extend_domain_one : extend_domain 1 f = 1 := extend_domain_refl f @[simp] lemma extend_domain_inv : (e.extend_domain f)⁻¹ = e⁻¹.extend_domain f := rfl @[simp] lemma extend_domain_mul (e e' : perm α) : (e.extend_domain f) * (e'.extend_domain f) = (e * e').extend_domain f := extend_domain_trans _ _ _ /-- `extend_domain` as a group homomorphism -/ @[simps] def extend_domain_hom : perm α →* perm β := { to_fun := λ e, extend_domain e f, map_one' := extend_domain_one f, map_mul' := λ e e', (extend_domain_mul f e e').symm } lemma extend_domain_hom_injective : function.injective (extend_domain_hom f) := ((extend_domain_hom f).injective_iff).mpr (λ e he, ext (λ x, f.injective (subtype.ext ((extend_domain_apply_image e f x).symm.trans (ext_iff.mp he (f x)))))) end extend_domain /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_apply (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) (x : {x // p x}) : subtype_perm f h x = ⟨f x, (h _).1 x.2⟩ := rfl @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp only [h, h₂, coe_fn_mk, perm.mul_apply, dif_pos, subtype.coe_eta] }, { simp only [h, coe_fn_mk, perm.mul_apply, dif_neg, not_false_iff] } end } lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp only [hx, coe_fn_mk, dif_pos, monoid_hom.coe_mk, subtype.coe_mk]}, { haveI := classical.prop_decidable, simp only [hx, not_not.mp (mt (h₂ x) hx), coe_fn_mk, dif_neg, not_false_iff, monoid_hom.coe_mk] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma of_subtype_apply_coe {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : subtype p) : of_subtype f ↑x = ↑(f x) := begin change dite _ _ _ = _, rw [dif_pos, subtype.coe_eta], exact x.2, end lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by simpa only [of_subtype, h, coe_fn_mk, dif_pos, true_iff, monoid_hom.coe_mk] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by { dsimp [subtype_perm, of_subtype], simp only [show p x, from hx, dif_pos, subtype.coe_eta] } instance perm_unique {n : Type*} [unique n] : unique (equiv.perm n) := { default := 1, uniq := λ σ, equiv.ext (λ i, subsingleton.elim _ _) } @[simp] lemma default_perm {n : Type*} : default (equiv.perm n) = 1 := rfl variables (e : perm α) (ι : α ↪ β) open_locale classical /-- Noncomputable version of `equiv.perm.via_fintype_embedding` that does not assume `fintype` -/ noncomputable def via_embedding : perm β := extend_domain e (of_injective ι.1 ι.2) lemma via_embedding_apply (x : α) : e.via_embedding ι (ι x) = ι (e x) := extend_domain_apply_image e (of_injective ι.1 ι.2) x lemma via_embedding_apply_of_not_mem (x : β) (hx : x ∉ _root_.set.range ι) : e.via_embedding ι x = x := extend_domain_apply_not_subtype e (of_injective ι.1 ι.2) hx /-- `via_embedding` as a group homomorphism -/ noncomputable def via_embedding_hom : perm α →* perm β:= extend_domain_hom (of_injective ι.1 ι.2) lemma via_embedding_hom_apply : via_embedding_hom ι e = via_embedding e ι := rfl lemma via_embedding_hom_injective : function.injective (via_embedding_hom ι) := extend_domain_hom_injective (of_injective ι.1 ι.2) end perm section swap variables [decidable_eq α] @[simp] lemma swap_inv (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma swap_mul_self (i j : α) : swap i j * swap i j = 1 := swap_swap i j lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp only [perm.mul_apply, swap_apply_def], split_ifs; simp only [perm.apply_inv_self, *, perm.eq_inv_iff_eq, eq_self_iff_true, not_true] at * end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, perm.inv_apply_self, perm.inv_apply_self] lemma swap_apply_apply (f : perm α) (x y : α) : swap (f x) (f y) = f * swap x y * f⁻¹ := by rw [mul_swap_eq_swap_mul, mul_inv_cancel_right] /-- Left-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc, swap_mul_self, one_mul] /-- Right-multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma mul_swap_mul_self (i j : α) (σ : perm α) : (σ * equiv.swap i j) * equiv.swap i j = σ := by rw [mul_assoc, swap_mul_self, mul_one] /-- A stronger version of `mul_right_injective` -/ @[simp] lemma swap_mul_involutive (i j : α) : function.involutive ((*) (equiv.swap i j)) := swap_mul_self_mul i j /-- A stronger version of `mul_left_injective` -/ @[simp] lemma mul_swap_involutive (i j : α) : function.involutive (* (equiv.swap i j)) := mul_swap_mul_self i j @[simp] lemma swap_eq_one_iff {i j : α} : swap i j = (1 : perm α) ↔ i = j := swap_eq_refl_iff lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma mul_swap_eq_iff {i j : α} {σ : perm α} : σ * swap i j = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_left_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, mul_one])⟩ lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by { simp only [swap_apply_def, perm.mul_apply], split_ifs; cc } end swap end equiv
61953d18dbab87cbfd73eb44294819ae4c60b7fd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/dual_quaternion.lean
2937d89336bf2f241d1b79aa2994de149bacba55
[ "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
4,265
lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.dual_number import algebra.quaternion /-! # Dual quaternions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Similar to the way that rotations in 3D space can be represented by quaternions of unit length, rigid motions in 3D space can be represented by dual quaternions of unit length. ## Main results * `quaternion.dual_number_equiv`: quaternions over dual numbers or dual numbers over quaternions are equivalent constructions. ## References * <https://en.wikipedia.org/wiki/Dual_quaternion> -/ variables {R : Type*} [comm_ring R] namespace quaternion /-- The dual quaternions can be equivalently represented as a quaternion with dual coefficients, or as a dual number with quaternion coefficients. See also `matrix.dual_number_equiv` for a similar result. -/ def dual_number_equiv : quaternion (dual_number R) ≃ₐ[R] dual_number (quaternion R) := { to_fun := λ q, (⟨q.re.fst, q.im_i.fst, q.im_j.fst, q.im_k.fst⟩, ⟨q.re.snd, q.im_i.snd, q.im_j.snd, q.im_k.snd⟩), inv_fun := λ d, ⟨(d.fst.re, d.snd.re), (d.fst.im_i, d.snd.im_i), (d.fst.im_j, d.snd.im_j), (d.fst.im_k, d.snd.im_k)⟩, left_inv := λ ⟨⟨r, rε⟩, ⟨i, iε⟩, ⟨j, jε⟩, ⟨k, kε⟩⟩, rfl, right_inv := λ ⟨⟨r, i, j, k⟩, ⟨rε, iε, jε, kε⟩⟩, rfl, map_mul' := begin rintros ⟨⟨xr, xrε⟩, ⟨xi, xiε⟩, ⟨xj, xjε⟩, ⟨xk, xkε⟩⟩, rintros ⟨⟨yr, yrε⟩, ⟨yi, yiε⟩, ⟨yj, yjε⟩, ⟨yk, ykε⟩⟩, ext : 1, { refl }, { dsimp, congr' 1; ring }, end, map_add' := begin rintros ⟨⟨xr, xrε⟩, ⟨xi, xiε⟩, ⟨xj, xjε⟩, ⟨xk, xkε⟩⟩, rintros ⟨⟨yr, yrε⟩, ⟨yi, yiε⟩, ⟨yj, yjε⟩, ⟨yk, ykε⟩⟩, refl end, commutes' := λ r, rfl } /-! Lemmas characterizing `quaternion.dual_number_equiv`. -/ -- `simps` can't work on `dual_number` because it's not a structure @[simp] lemma re_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.re = q.re.fst := rfl @[simp] lemma im_i_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.im_i = q.im_i.fst := rfl @[simp] lemma im_j_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.im_j = q.im_j.fst := rfl @[simp] lemma im_k_fst_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).fst.im_k = q.im_k.fst := rfl @[simp] lemma re_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.re = q.re.snd := rfl @[simp] lemma im_i_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.im_i = q.im_i.snd := rfl @[simp] lemma im_j_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.im_j = q.im_j.snd := rfl @[simp] lemma im_k_snd_dual_number_equiv (q : quaternion (dual_number R)) : (dual_number_equiv q).snd.im_k = q.im_k.snd := rfl @[simp] lemma fst_re_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).re.fst = d.fst.re := rfl @[simp] lemma fst_im_i_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_i.fst = d.fst.im_i := rfl @[simp] lemma fst_im_j_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_j.fst = d.fst.im_j := rfl @[simp] lemma fst_im_k_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_k.fst = d.fst.im_k := rfl @[simp] lemma snd_re_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).re.snd = d.snd.re := rfl @[simp] lemma snd_im_i_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_i.snd = d.snd.im_i := rfl @[simp] lemma snd_im_j_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_j.snd = d.snd.im_j := rfl @[simp] lemma snd_im_k_dual_number_equiv_symm (d : dual_number (quaternion R)) : (dual_number_equiv.symm d).im_k.snd = d.snd.im_k := rfl end quaternion
b3529110d8bb5d59b44cb3cd19ecabe0cf9974a8
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/init/path.hlean
bece16eb69f169119d25bbe0530cfeb895d05465
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
26,172
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {x y z t : A} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec' [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on' [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := eq.rec (λp', p') q p definition inverse [symm] [unfold 4] (p : x = y) : y = x := eq.rec (refl x) p infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold_full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a right unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := eq.rec_on p idp -- Concatenation is associative. definition con.assoc' (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := eq.rec_on r (eq.rec_on q idp) definition con.assoc (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := eq.rec_on r (eq.rec_on q idp) -- The left inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := eq.rec_on p idp -- The right inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := eq.rec_on p idp /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := eq.rec_on q (eq.rec_on p idp) definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := eq.rec_on q (eq.rec_on p idp) definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := eq.rec_on q (eq.rec_on p idp) definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := eq.rec_on q (take p, eq.rec_on p idp) p -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := eq.rec_on q (eq.rec_on p idp) definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := eq.rec_on q (eq.rec_on p idp) -- universe metavariables definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := eq.rec_on p (take q, eq.rec_on q idp) q definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := eq.rec_on p (eq.rec_on q idp) -- Inverse is an involution. definition inv_inv (p : x = y) : p⁻¹⁻¹ = p := eq.rec_on p idp -- auxiliary definition used by 'cases' tactic definition elim_inv_inv {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := eq.rec_on r (take p h, !idp_con ⬝ h ⬝ !idp_con) p definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := eq.rec_on p (take q h, h) q definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := eq.rec_on r (take q h, !idp_con ⬝ h ⬝ !idp_con) q definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := eq.rec_on p (take r h, h) r definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := eq.rec_on r (take p h, !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹) p definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := eq.rec_on p (take q h, h) q definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := eq.rec_on r (take q h, !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹) q definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := eq.rec_on p (take r h, h) r definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := eq.rec_on q (take p h, h) p definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := eq.rec_on q (take p h, !idp_con⁻¹ ⬝ h) p definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := eq.rec_on q (take p h, h) p definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := eq.rec_on q (take p h, !idp_con⁻¹ ⬝ h) p definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := eq.rec_on p (take q h, h ⬝ !idp_con) q definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := eq.rec_on p (take q h, h) q definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := eq.rec_on p (take q h, h) q definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := eq.rec_on p (take q h, h ⬝ !idp_con) q definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r;apply con.right_inv definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r;apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q;exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r;exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r;exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p;exact r /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := eq.rec_on p u -- This idiom makes the operation right associative. infixr ` ▸ ` := transport _ definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition cast_def [reducible] [unfold_full] {A B : Type} (p : A = B) (a : A) : cast p a = p ▸ a := idp definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := eq.rec_on p idp abbreviation ap01 [parsing_only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] [unfold_full] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.symm [symm] [reducible] [unfold_full] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] [unfold_full] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x definition homotopy_of_eq {f g : Πx, P x} (H1 : f = g) : f ~ g := H1 ▸ homotopy.refl f definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, eq.rec_on H idp --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := eq.rec_on H idp --apd10 is also ap evaluation definition apd10_eq_ap_eval {f g : Πx, P x} (H : f = g) (a : A) : apd10 H a = ap (λs : Πx, P x, s a) H := eq.rec_on H idp definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := eq.rec_on H (eq.rec_on p idp) definition apd [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := eq.rec_on p idp /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := eq.rec_on p (take v, id) v definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := eq.rec_on p (take u, id) u definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := eq.rec_on p (take v, id) v definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := eq.rec_on p (take u, id) u /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp [unfold_full] (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con [unfold 8] (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := eq.rec_on q idp definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := eq.rec_on q (take p, eq.rec_on p idp) p definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := eq.rec_on q (eq.rec_on p (take r, con.assoc _ _ _)) r -- Functions commute with path inverses. definition ap_inv' [unfold 6] (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := eq.rec_on p idp definition ap_inv [unfold 6] (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := eq.rec_on p idp -- [ap] itself is functorial in the first argument. definition ap_id [unfold 4] (p : x = y) : ap id p = p := eq.rec_on p idp definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := eq.rec_on p idp -- Sometimes we don't have the actual function [compose]. definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := eq.rec_on p idp -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := eq.rec_on p idp -- Naturality of [ap]. -- see also natural_square in cubical.square definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := eq.rec_on q !idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := eq.rec_on q !idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := eq.rec_on q !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := eq.rec_on q !idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := eq.rec_on q idp -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := eq.rec_on s (eq.rec_on q (calc (ap f idp) ⬝ (p x ⬝ idp) = idp ⬝ p x : idp ... = p x : !idp_con ... = (p x) ⬝ (ap g idp ⬝ idp) : idp)) -- This also works: -- eq.rec_on s (eq.rec_on q (!idp_con ▸ idp)) definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := eq.rec_on q idp definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := eq.rec_on s (eq.rec_on q (!idp_con ▸ idp)) definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := begin apply (eq.rec_on s), apply (eq.rec_on q), apply (idp_con (p x) ▸ idp) end /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := eq.rec_on h (take h', eq.rec_on h' idp) h' definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := eq.rec_on h idp definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= eq.rec_on p idp /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := eq.rec_on q idp definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition con_tr_lemma {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := eq.rec_on r (eq.rec_on q (eq.rec_on p idp)) -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := eq.rec_on p idp /- some properties for apd -/ definition apd_idp (x : A) (f : Πx, P x) : apd f idp = idp :> (f x = f x) := idp definition apd_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apd f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apd f p) ⬝ apd f q := by cases p;cases q;apply idp definition apd_inv (f : Πx, P x) {x y : A} (p : x = y) : apd f p⁻¹ = (eq_inv_tr_of_tr_eq (apd f p))⁻¹ := by cases p;apply idp -- Dependent transport in a doubly dependent type. definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := eq.rec_on p z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p ` ▸D `:65 x:64 := transportD _ p _ x -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p ` ▸2 `:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := eq.rec_on r idp definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := eq.rec_on r1 (eq.rec_on r2 idp) definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := eq.rec_on r idp definition transportD2 [unfold 7] (B C : A → Type) (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := eq.rec_on p w notation p ` ▸D2 `:65 x:64 := transportD2 _ _ _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := eq.rec_on r !idp_con⁻¹ definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = (p ▸ (f x z)) := eq.rec_on p idp /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := eq.rec_on p idp definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := eq.rec_on r !idp_con⁻¹ -- Transporting in a pulled back fibration. definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := eq.rec_on p idp definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := eq.rec_on p idp definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : apd10 (ap (λh : B → C, h ∘ f) p) = λa, apd10 p (f a) := eq.rec_on p idp definition apd10_ap_precompose_dependent {C : B → Type} (f : A → B) {g g' : Πb : B, C b} (p : g = g') : apd10 (ap (λ(h : (Πb : B, C b))(a : A), h (f a)) p) = λa, apd10 p (f a) := eq.rec_on p idp definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') : apd10 (ap (λh : A → B, f ∘ h) p) = λa, ap f (apd10 p a) := eq.rec_on p idp -- A special case of [tr_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := eq.rec_on p idp definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := eq.rec_on p idp /- The behavior of [ap] and [apd] -/ -- In a constant fibration, [apd] reduces to [ap], modulo [transport_const]. definition apd_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apd f p = tr_constant p (f x) ⬝ ap f p := eq.rec_on p idp /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := eq.rec_on h (eq.rec_on h' idp) -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := eq.rec_on h idp infixl ` ◾ `:75 := concat2 postfix [parsing_only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right [unfold 7] {p q : x = y} (h : p = q) (r : y = z) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} {p : x = y} {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} {r : y = z} : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right s r⁻¹ ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp {p q : x = y} (h : p = q) : whisker_right h idp = h := eq.rec_on h (eq.rec_on p idp) definition whisker_right_idp_left [unfold_full] (p : x = y) (q : y = z) : whisker_right idp q = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp_right [unfold_full] (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp {p q : x = y} (h : p = q) : (idp_con p) ⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := eq.rec_on h (eq.rec_on p idp) definition con2_idp [unfold_full] {p q : x = y} (h : p = q) : h ◾ idp = whisker_right h idp :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 [unfold_full] {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : (a ◾ c) ⬝ (b ◾ d) = (a ⬝ b) ◾ (c ⬝ d) := eq.rec_on d (eq.rec_on c (eq.rec_on b (eq.rec_on a idp))) definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right a q) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right a q') := eq.rec_on b (eq.rec_on a !idp_con⁻¹) -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right (con.assoc' p q r) s = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right (con_idp p) q = whisker_left p (idp_con q) := eq.rec_on q (eq.rec_on p idp) definition eckmann_hilton {x:A} (p q : idp = idp :> x = x) : p ⬝ q = q ⬝ p := (!whisker_right_idp ◾ !whisker_left_idp)⁻¹ ⬝ whisker_left _ !idp_con ⬝ !whisker_right_con_whisker_left ⬝ whisker_right !idp_con⁻¹ _ ⬝ (!whisker_left_idp ◾ !whisker_right_idp) -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := eq.rec_on r (eq.rec_on r' idp) definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := eq.rec_on r (eq.rec_on s (eq.rec_on q (eq.rec_on p idp))) definition apd02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apd f p = transport2 P r (f x) ⬝ apd f q := eq.rec_on r !idp_con⁻¹ -- And now for a lemma whose statement is much longer than its proof. definition apd02_con {P : A → Type} (f : Π x:A, P x) {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) : apd02 f (r1 ⬝ r2) = apd02 f r1 ⬝ whisker_left (transport2 P r1 (f x)) (apd02 f r2) ⬝ con.assoc' _ _ _ ⬝ (whisker_right (tr2_con r1 r2 (f x))⁻¹ (apd f p3)) := eq.rec_on r2 (eq.rec_on r1 (eq.rec_on p1 idp)) end eq
1d311ec4b05b52b3b72de9d8907397c87b6dec6a
d642a6b1261b2cbe691e53561ac777b924751b63
/src/algebra/group/hom.lean
18a9c1a4c91eb95174a866a61ff99961795de79b
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
14,370
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes, Johannes Hölzl, Yury Kudryashov Homomorphisms of multiplicative and additive (semi)groups and monoids. -/ import algebra.group.to_additive algebra.group.basic /-! # monoid and group homomorphisms This file defines the basic structures for monoid and group homomorphisms, both unbundled (e.g. `is_monoid_hom f`) and bundled (e.g. `monoid_hom M N`, a.k.a. `M →* N`). The unbundled ones are deprecated and the plan is to slowly remove them from mathlib. ## main definitions monoid_hom, is_monoid_hom (deprecated), is_group_hom (deprecated) ## Notations →* for bundled monoid homs (also use for group homs) →+ for bundled add_monoid homs (also use for add_group homs) ## implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `group_hom` -- the idea is that `monoid_hom` is used. The constructor for `monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `monoid_hom.mk'` will construct group homs (i.e. monoid homs between groups) given only a proof that multiplication is preserved, Throughout the `monoid_hom` section implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags is_group_hom, is_monoid_hom, monoid_hom -/ universes u v variables {α : Type u} {β : Type v} /-- Predicate for maps which preserve an addition. -/ class is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) /-- Predicate for maps which preserve a multiplication. -/ @[to_additive] class is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop := (map_mul : ∀ x y, f (x * y) = f x * f y) namespace is_mul_hom variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ] /-- The identity map preserves multiplication. -/ @[to_additive "The identity map preserves addition"] instance id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl} /-- The composition of maps which preserve multiplication, also preserves multiplication. -/ @[to_additive "The composition of addition preserving maps also preserves addition"] instance comp (f : α → β) (g : β → γ) [is_mul_hom f] [hg : is_mul_hom g] : is_mul_hom (g ∘ f) := { map_mul := λ x y, by simp only [function.comp, map_mul f, map_mul g] } /-- A product of maps which preserve multiplication, preserves multiplication when the target is commutative. -/ @[instance, to_additive] lemma mul {α β} [semigroup α] [comm_semigroup β] (f g : α → β) [is_mul_hom f] [is_mul_hom g] : is_mul_hom (λa, f a * g a) := { map_mul := assume a b, by simp only [map_mul f, map_mul g, mul_comm, mul_assoc, mul_left_comm] } /-- The inverse of a map which preserves multiplication, preserves multiplication when the target is commutative. -/ @[instance, to_additive] lemma inv {α β} [has_mul α] [comm_group β] (f : α → β) [is_mul_hom f] : is_mul_hom (λa, (f a)⁻¹) := { map_mul := assume a b, (map_mul f a b).symm ▸ mul_inv _ _ } end is_mul_hom /-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/ class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) extends is_add_hom f : Prop := (map_zero : f 0 = 0) /-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/ @[to_additive is_add_monoid_hom] class is_monoid_hom [monoid α] [monoid β] (f : α → β) extends is_mul_hom f : Prop := (map_one : f 1 = 1) namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] /-- A monoid homomorphism preserves multiplication. -/ @[to_additive] lemma map_mul (x y) : f (x * y) = f x * f y := is_mul_hom.map_mul f x y end is_monoid_hom /-- A map to a group preserving multiplication is a monoid homomorphism. -/ @[to_additive] theorem is_monoid_hom.of_mul [monoid α] [group β] (f : α → β) [is_mul_hom f] : is_monoid_hom f := { map_one := mul_self_iff_eq_one.1 $ by rw [← is_mul_hom.map_mul f, one_mul] } namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] /-- The identity map is a monoid homomorphism. -/ @[to_additive] instance id : is_monoid_hom (@id α) := { map_one := rfl } /-- The composite of two monoid homomorphisms is a monoid homomorphism. -/ @[to_additive] instance comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] : is_monoid_hom (g ∘ f) := { map_one := show g _ = 1, by rw [map_one f, map_one g] } end is_monoid_hom namespace is_add_monoid_hom /-- Left multiplication in a ring is an additive monoid morphism. -/ instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, x * y) := { map_zero := mul_zero x, map_add := λ y z, mul_add x y z } /-- Right multiplication in a ring is an additive monoid morphism. -/ instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, y * x) := { map_zero := zero_mul x, map_add := λ y z, add_mul y z x } end is_add_monoid_hom /-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/ class is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop /-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/ @[to_additive is_add_group_hom] class is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop /-- Construct `is_group_hom` from its only hypothesis. The default constructor tries to get `is_mul_hom` from class instances, and this makes some proofs fail. -/ @[to_additive] lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) : is_group_hom f := { map_mul := hf } namespace is_group_hom variables [group α] [group β] (f : α → β) [is_group_hom f] open is_mul_hom (map_mul) /-- A group homomorphism is a monoid homomorphism. -/ @[to_additive to_is_add_monoid_hom] instance to_is_monoid_hom : is_monoid_hom f := is_monoid_hom.of_mul f /-- A group homomorphism sends 1 to 1. -/ @[to_additive] lemma map_one : f 1 = 1 := is_monoid_hom.map_one f /-- A group homomorphism sends inverses to inverses. -/ @[to_additive] theorem map_inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← map_mul f, inv_mul_self, map_one f] /-- The identity is a group homomorphism. -/ @[to_additive] instance id : is_group_hom (@id α) := { } /-- The composition of two group homomomorphisms is a group homomorphism. -/ @[to_additive] instance comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) := { } /-- A group homomorphism is injective iff its kernel is trivial. -/ @[to_additive] lemma injective_iff (f : α → β) [is_group_hom f] : function.injective f ↔ (∀ a, f a = 1 → a = 1) := ⟨λ h _, by rw ← is_group_hom.map_one f; exact @h _ _, λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← map_inv f, ← map_mul f] at hxy; simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩ /-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/ @[instance, to_additive] lemma mul {α β} [group α] [comm_group β] (f g : α → β) [is_group_hom f] [is_group_hom g] : is_group_hom (λa, f a * g a) := { } /-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/ @[instance, to_additive] lemma inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] : is_group_hom (λa, (f a)⁻¹) := { } end is_group_hom /-- Inversion is a group homomorphism if the group is commutative. -/ @[instance, to_additive is_add_group_hom] lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) := { map_mul := mul_inv } namespace is_add_group_hom variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] /-- Additive group homomorphisms commute with subtraction. -/ lemma map_sub (a b) : f (a - b) = f a - f b := calc f (a + -b) = f a + f (-b) : is_add_hom.map_add f _ _ ... = f a + -f b : by rw [map_neg f] end is_add_group_hom /-- The difference of two additive group homomorphisms is an additive group homomorphism if the target is commutative. -/ @[instance] lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β] (f g : α → β) [is_add_group_hom f] [is_add_group_hom g] : is_add_group_hom (λa, f a - g a) := is_add_group_hom.add f (λa, - g a) /-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/ structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N] := (to_fun : M → N) (map_zero' : to_fun 0 = 0) (map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y) infixr ` →+ `:25 := add_monoid_hom /-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/ @[to_additive add_monoid_hom] structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] := (to_fun : M → N) (map_one' : to_fun 1 = 1) (map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y) infixr ` →* `:25 := monoid_hom @[to_additive] instance {M : Type*} {N : Type*} {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) := ⟨_, monoid_hom.to_fun⟩ namespace monoid_hom variables {M : Type*} {N : Type*} {P : Type*} [mM : monoid M] [mN : monoid N] {mP : monoid P} variables {G : Type*} {H : Type*} [group G] [comm_group H] include mM mN /-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/ @[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."] def of (f : M → N) [h : is_monoid_hom f] : M →* N := { to_fun := f, map_one' := h.2, map_mul' := h.1.1 } variables {mM mN mP} @[simp, to_additive] lemma coe_of (f : M → N) [is_monoid_hom f] : ⇑ (monoid_hom.of f) = f := rfl @[to_additive] lemma coe_inj ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g := by cases f; cases g; cases h; refl @[ext, to_additive] lemma ext ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) @[to_additive] lemma ext_iff {f g : M →* N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ /-- If f is a monoid homomorphism then f 1 = 1. -/ @[simp, to_additive] lemma map_one (f : M →* N) : f 1 = 1 := f.map_one' /-- If f is a monoid homomorphism then f (a * b) = f a * f b. -/ @[simp, to_additive] lemma map_mul (f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b @[to_additive is_add_monoid_hom] instance (f : M →* N) : is_monoid_hom (f : M → N) := { map_mul := f.map_mul, map_one := f.map_one } omit mN mM @[to_additive is_add_group_hom] instance (f : G →* H) : is_group_hom (f : G → H) := { map_mul := f.map_mul } /-- The identity map from a monoid to itself. -/ @[to_additive] def id (M : Type*) [monoid M] : M →* M := { to_fun := id, map_one' := rfl, map_mul' := λ _ _, rfl } include mM mN mP /-- Composition of monoid morphisms is a monoid morphism. -/ @[to_additive] def comp (hnp : N →* P) (hmn : M →* N) : M →* P := { to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp } omit mP variables [mM] [mN] @[to_additive] protected def one : M →* N := { to_fun := λ _, 1, map_one' := rfl, map_mul' := λ _ _, (one_mul 1).symm } @[to_additive] instance : has_one (M →* N) := ⟨monoid_hom.one⟩ omit mM mN /-- The product of two monoid morphisms is a monoid morphism if the target is commutative. -/ @[to_additive] protected def mul {M N} {mM : monoid M} [comm_monoid N] (f g : M →* N) : M →* N := { to_fun := λ m, f m * g m, map_one' := show f 1 * g 1 = 1, by simp, map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y), rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end } @[to_additive] instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) := ⟨monoid_hom.mul⟩ /-- (M →* N) is a comm_monoid if N is commutative. -/ @[to_additive add_comm_monoid] instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) := { mul := (*), mul_assoc := by intros; ext; apply mul_assoc, one := 1, one_mul := by intros; ext; apply one_mul, mul_one := by intros; ext; apply mul_one, mul_comm := by intros; ext; apply mul_comm } /-- Group homomorphisms preserve inverse. -/ @[simp, to_additive] theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ := eq_inv_of_mul_eq_one $ by rw [←f.map_mul, inv_mul_self, f.map_one] /-- Group homomorphisms preserve division. -/ @[simp, to_additive] theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) : f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv] include mM /-- Makes a group homomomorphism from a proof that the map preserves multiplication. -/ @[to_additive] def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G := { to_fun := f, map_mul' := map_mul, map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] } omit mM /-- The inverse of a monoid homomorphism is a monoid homomorphism if the target is a commutative group.-/ @[to_additive] protected def inv {M G} {mM : monoid M} [comm_group G] (f : M →* G) : M →* G := mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul] @[to_additive] instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) := ⟨monoid_hom.inv⟩ /-- (M →* G) is a comm_group if G is a comm_group -/ @[to_additive add_comm_group] instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) := { inv := has_inv.inv, mul_left_inv := by intros; ext; apply mul_left_inv, ..monoid_hom.comm_monoid } end monoid_hom /-- Additive group homomorphisms preserve subtraction. -/ @[simp] theorem add_monoid_hom.map_sub {G H} [add_group G] [add_group H] (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) := f.map_add_neg g h
055c907723e14842c1d9a9445636786cdfdde841
e61a235b8468b03aee0120bf26ec615c045005d2
/tmp/eqns/prototype.lean
0a8096328e42a70fc40dbabf8370b0edfab295bf
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,618
lean
prelude import Init.Lean.Meta.Check import Init.Lean.Meta.Tactic.Cases import Init.Lean.Meta.GeneralizeTelescope namespace Lean namespace Meta namespace DepElim inductive Pattern | inaccessible (ref : Syntax) (e : Expr) | var (ref : Syntax) (fvarId : FVarId) | ctor (ref : Syntax) (ctorName : Name) (fields : List Pattern) | val (ref : Syntax) (e : Expr) | arrayLit (ref : Syntax) (xs : List Pattern) namespace Pattern instance : Inhabited Pattern := ⟨Pattern.arrayLit Syntax.missing []⟩ partial def toMessageData : Pattern → MessageData | inaccessible _ e => ".(" ++ e ++ ")" | var _ fvarId => mkFVar fvarId | ctor _ ctorName [] => ctorName | ctor _ ctorName pats => "(" ++ ctorName ++ pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil ++ ")" | val _ e => "val!(" ++ e ++ ")" | arrayLit _ pats => "#[" ++ MessageData.joinSep (pats.map toMessageData) ", " ++ "]" end Pattern structure AltLHS := (fvarDecls : List LocalDecl) -- Free variables used in the patterns. (patterns : List Pattern) -- We use `List Pattern` since we have nary match-expressions. structure MinorsRange := (firstMinorPos : Nat) (numMinors : Nat) abbrev AltToMinorsMap := PersistentHashMap Nat MinorsRange structure Alt := (idx : Nat) -- for generating error messages (fvarDecls : List LocalDecl) (patterns : List Pattern) namespace Alt instance : Inhabited Alt := ⟨⟨0, [], []⟩⟩ partial def toMessageData (alt : Alt) : MetaM MessageData := do lctx ← getLCtx; localInsts ← getLocalInstances; let lctx := alt.fvarDecls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) lctx; withLocalContext lctx localInsts $ do let msg : MessageData := "⟦" ++ MessageData.joinSep (alt.patterns.map Pattern.toMessageData) ", " ++ "⟧"; addContext msg end Alt structure Problem := (goal : Expr) (vars : List Expr) (alts : List Alt) namespace Problem instance : Inhabited Problem := ⟨⟨arbitrary _, [], []⟩⟩ def toMessageData (p : Problem) : MetaM MessageData := do alts ← p.alts.mapM Alt.toMessageData; pure $ "vars " ++ p.vars.toArray ++ Format.line ++ MessageData.joinSep alts Format.line end Problem structure ElimResult := (numMinors : Nat) -- It is the number of alternatives (Reason: support for overlapping equations) (numEqs : Nat) -- It is the number of minors (Reason: users may want equations that hold definitionally) (elim : Expr) -- The eliminator. It is not just `Expr.const elimName` because the type of the major premises may contain free variables. (altMap : AltToMinorsMap) -- each alternative may be "expanded" into multiple minor premise private def checkNumPatterns (majors : List Expr) (lhss : List AltLHS) : MetaM Unit := let num := majors.length; when (lhss.any (fun lhs => lhs.patterns.length != num)) $ throw $ Exception.other "incorrect number of patterns" private def mkElimSort (inProp : Bool) : MetaM Expr := if inProp then pure $ mkSort $ levelZero else do vId ← mkFreshId; pure $ mkSort $ mkLevelParam vId private def withMotive {α} (majors : Array Expr) (sortv : Expr) (k : Expr → MetaM α) : MetaM α := do type ← mkForall majors sortv; trace! `Meta.debug type; withLocalDecl `motive type BinderInfo.default k private def mkAlts (lhss : List AltLHS) : List Alt := let alts : List Alt := lhss.foldl (fun result lhs => { idx := result.length, fvarDecls := lhs.fvarDecls, patterns := lhs.patterns } :: result) []; alts.reverse private def process : Problem → MetaM Unit | p => withIncRecDepth $ do traceM `Meta.debug p.toMessageData; pure () def mkElim (elimName : Name) (majors : List Expr) (lhss : List AltLHS) (inProp : Bool := false) : MetaM ElimResult := do checkNumPatterns majors lhss; generalizeTelescope majors.toArray `_d $ fun majors => do sortv ← mkElimSort inProp; withMotive majors sortv $ fun motive => do let target := mkAppN motive majors; goal ← mkFreshExprMVar target; let alts := mkAlts lhss; let problem := { Problem . goal := goal, vars := majors.toList, alts := alts }; process problem; pure { numMinors := 0, numEqs := 0, elim := arbitrary _, altMap := {} } -- TODO end DepElim end Meta end Lean open Lean open Lean.Meta open Lean.Meta.DepElim /- Infrastructure for testing -/ universes u v def inaccessible {α : Sort u} (a : α) : α := a def val {α : Sort u} (a : α) : α := a /- Convert expression using auxiliary hints `inaccessible` and `val` into a pattern -/ partial def mkPattern : Expr → MetaM Pattern | e => if e.isAppOfArity `val 2 then pure $ Pattern.val Syntax.missing e.appArg! else if e.isAppOfArity `inaccessible 2 then pure $ Pattern.inaccessible Syntax.missing e.appArg! else if e.isFVar then pure $ Pattern.var Syntax.missing e.fvarId! else match e.arrayLit? with | some es => do pats ← es.mapM mkPattern; pure $ Pattern.arrayLit Syntax.missing pats | none => do cval? ← constructorApp? e; match cval? with | none => throw $ Exception.other "unexpected pattern" | some cval => do let args := e.getAppArgs; let fields := args.extract cval.nparams args.size; pats ← fields.toList.mapM mkPattern; pure $ Pattern.ctor Syntax.missing cval.name pats partial def decodePats : Expr → MetaM (List Pattern) | e => match e.app2? `Pat with | some (_, pat) => do pat ← mkPattern pat; pure [pat] | none => match e.prod? with | none => throw $ Exception.other "unexpected pattern" | some (pat, pats) => do pat ← decodePats pat; pats ← decodePats pats; pure (pat ++ pats) partial def decodeAltLHS (e : Expr) : MetaM AltLHS := forallTelescopeReducing e $ fun args body => do decls ← args.toList.mapM (fun arg => getLocalDecl arg.fvarId!); pats ← decodePats body; pure { fvarDecls := decls, patterns := pats } partial def decodeAltLHSs : Expr → MetaM (List AltLHS) | e => match e.app2? `LHS with | some (_, lhs) => do lhs ← decodeAltLHS lhs; pure [lhs] | none => match e.prod? with | none => throw $ Exception.other "unexpected LHS" | some (lhs, lhss) => do lhs ← decodeAltLHSs lhs; lhss ← decodeAltLHSs lhss; pure (lhs ++ lhss) def withDepElimFrom {α} (declName : Name) (numPats : Nat) (k : List FVarId → List AltLHS → MetaM α) : MetaM α := do cinfo ← getConstInfo declName; forallTelescopeReducing cinfo.type $ fun args body => if args.size < numPats then throw $ Exception.other "insufficient number of parameters" else do let xs := (args.extract (args.size - numPats) args.size).toList.map $ Expr.fvarId!; alts ← decodeAltLHSs body; k xs alts inductive Pat {α : Sort u} (a : α) : Type u | mk {} : Pat inductive LHS {α : Sort u} (a : α) : Type u | mk {} : LHS instance LHS.inhabited {α} (a : α) : Inhabited (LHS a) := ⟨LHS.mk⟩ def ex1 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List α)) × LHS (forall (a : α) (b : α), Pat [a] × Pat [b]) × LHS (forall (a₁ a₂ : α) (as : List α) (b₁ b₂ : β) (bs : List β), Pat (a₁::a₂::as) × Pat (b₁::b₂::bs)) × LHS (forall (as : List α) (bs : List β), Pat as × Pat bs) := arbitrary _ @[init] def register : IO Unit := registerTraceClass `Meta.mkElim set_option trace.Meta.debug true def tst1 : MetaM Unit := withDepElimFrom `ex1 2 $ fun majors alts => do let majors := majors.map mkFVar; trace! `Meta.debug majors.toArray; mkElim `test majors alts; pure () #eval tst1
5a962067d24a6ad60dba9815f6f473be605df58a
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0711.lean
783879a928803743f7632663e25765eb30f80b70
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
177
lean
variables (p q r : Prop) example (hp : p) : p ∧ q ↔ q := by simp * example (hp : p) : p ∨ q := by simp * example (hp : p) (hq : q) : p ∧ (q ∨ r) := by simp *
bfaaf9c79008f770eb78c0b11911a66ca8c7c548
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/galois_connection.lean
e38dd6af59b1f1c8b4929f81da0172cd7e79c576
[ "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
33,662
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.complete_lattice import order.synonym /-! # Galois connections, insertions and coinsertions Galois connections are order theoretic adjoints, i.e. a pair of functions `u` and `l`, such that `∀ a b, l a ≤ b ↔ a ≤ u b`. ## Main definitions * `galois_connection`: A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory, but do not depend on the category theory library in mathlib. * `galois_insertion`: A Galois insertion is a Galois connection where `l ∘ u = id` * `galois_coinsertion`: A Galois coinsertion is a Galois connection where `u ∘ l = id` ## Implementation details Galois insertions can be used to lift order structures from one type to another. For example if `α` is a complete lattice, and `l : α → β`, and `u : β → α` form a Galois insertion, then `β` is also a complete lattice. `l` is the lower adjoint and `u` is the upper adjoint. An example of a Galois insertion is in group theory. If `G` is a group, then there is a Galois insertion between the set of subsets of `G`, `set G`, and the set of subgroups of `G`, `subgroup G`. The lower adjoint is `subgroup.closure`, taking the `subgroup` generated by a `set`, and the upper adjoint is the coercion from `subgroup G` to `set G`, taking the underlying set of a subgroup. Naively lifting a lattice structure along this Galois insertion would mean that the definition of `inf` on subgroups would be `subgroup.closure (↑S ∩ ↑T)`. This is an undesirable definition because the intersection of subgroups is already a subgroup, so there is no need to take the closure. For this reason a `choice` function is added as a field to the `galois_insertion` structure. It has type `Π S : set G, ↑(closure S) ≤ S → subgroup G`. When `↑(closure S) ≤ S`, then `S` is already a subgroup, so this function can be defined using `subgroup.mk` and not `closure`. This means the infimum of subgroups will be defined to be the intersection of sets, paired with a proof that intersection of subgroups is a subgroup, rather than the closure of the intersection. -/ open function order_dual set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {κ : ι → Sort*} {a a₁ a₂ : α} {b b₁ b₂ : β} /-- A Galois connection is a pair of functions `l` and `u` satisfying `l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory, but do not depend on the category theory library in mathlib. -/ def galois_connection [preorder α] [preorder β] (l : α → β) (u : β → α) := ∀ a b, l a ≤ b ↔ a ≤ u b /-- Makes a Galois connection from an order-preserving bijection. -/ theorem order_iso.to_galois_connection [preorder α] [preorder β] (oi : α ≃o β) : galois_connection oi oi.symm := λ b g, oi.rel_symm_apply.symm namespace galois_connection section variables [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) lemma monotone_intro (hu : monotone u) (hl : monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ a, l (u a) ≤ a) : galois_connection l u := λ a b, ⟨λ h, (hul _).trans (hu h), λ h, (hl h).trans (hlu _)⟩ include gc protected lemma dual {l : α → β} {u : β → α} (gc : galois_connection l u) : galois_connection (order_dual.to_dual ∘ u ∘ order_dual.of_dual) (order_dual.to_dual ∘ l ∘ order_dual.of_dual) := λ a b, (gc b a).symm lemma le_iff_le {a : α} {b : β} : l a ≤ b ↔ a ≤ u b := gc _ _ lemma l_le {a : α} {b : β} : a ≤ u b → l a ≤ b := (gc _ _).mpr lemma le_u {a : α} {b : β} : l a ≤ b → a ≤ u b := (gc _ _).mp lemma le_u_l (a) : a ≤ u (l a) := gc.le_u $ le_rfl lemma l_u_le (a) : l (u a) ≤ a := gc.l_le $ le_rfl lemma monotone_u : monotone u := λ a b H, gc.le_u ((gc.l_u_le a).trans H) lemma monotone_l : monotone l := gc.dual.monotone_u.dual lemma upper_bounds_l_image (s : set α) : upper_bounds (l '' s) = u ⁻¹' upper_bounds s := set.ext $ λ b, by simp [upper_bounds, gc _ _] lemma lower_bounds_u_image (s : set β) : lower_bounds (u '' s) = l ⁻¹' lower_bounds s := gc.dual.upper_bounds_l_image s lemma bdd_above_l_image {s : set α} : bdd_above (l '' s) ↔ bdd_above s := ⟨λ ⟨x, hx⟩, ⟨u x, by rwa [gc.upper_bounds_l_image] at hx⟩, gc.monotone_l.map_bdd_above⟩ lemma bdd_below_u_image {s : set β} : bdd_below (u '' s) ↔ bdd_below s := gc.dual.bdd_above_l_image lemma is_lub_l_image {s : set α} {a : α} (h : is_lub s a) : is_lub (l '' s) (l a) := ⟨gc.monotone_l.mem_upper_bounds_image h.left, λ b hb, gc.l_le $ h.right $ by rwa [gc.upper_bounds_l_image] at hb⟩ lemma is_glb_u_image {s : set β} {b : β} (h : is_glb s b) : is_glb (u '' s) (u b) := gc.dual.is_lub_l_image h lemma is_least_l {a : α} : is_least {b | a ≤ u b} (l a) := ⟨gc.le_u_l _, λ b hb, gc.l_le hb⟩ lemma is_greatest_u {b : β} : is_greatest {a | l a ≤ b} (u b) := gc.dual.is_least_l lemma is_glb_l {a : α} : is_glb {b | a ≤ u b} (l a) := gc.is_least_l.is_glb lemma is_lub_u {b : β} : is_lub { a | l a ≤ b } (u b) := gc.is_greatest_u.is_lub /-- If `(l, u)` is a Galois connection, then the relation `x ≤ u (l y)` is a transitive relation. If `l` is a closure operator (`submodule.span`, `subgroup.closure`, ...) and `u` is the coercion to `set`, this reads as "if `U` is in the closure of `V` and `V` is in the closure of `W` then `U` is in the closure of `W`". -/ lemma le_u_l_trans {x y z : α} (hxy : x ≤ u (l y)) (hyz : y ≤ u (l z)) : x ≤ u (l z) := hxy.trans (gc.monotone_u $ gc.l_le hyz) lemma l_u_le_trans {x y z : β} (hxy : l (u x) ≤ y) (hyz : l (u y) ≤ z) : l (u x) ≤ z := (gc.monotone_l $ gc.le_u hxy).trans hyz end section partial_order variables [partial_order α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_l_u_eq_u (b : β) : u (l (u b)) = u b := (gc.monotone_u (gc.l_u_le _)).antisymm (gc.le_u_l _) lemma u_l_u_eq_u' : u ∘ l ∘ u = u := funext gc.u_l_u_eq_u lemma u_unique {l' : α → β} {u' : β → α} (gc' : galois_connection l' u') (hl : ∀ a, l a = l' a) {b : β} : u b = u' b := le_antisymm (gc'.le_u $ hl (u b) ▸ gc.l_u_le _) (gc.le_u $ (hl (u' b)).symm ▸ gc'.l_u_le _) /-- If there exists a `b` such that `a = u a`, then `b = l a` is one such element. -/ lemma exists_eq_u (a : α) : (∃ b : β, a = u b) ↔ a = u (l a) := ⟨λ ⟨S, hS⟩, hS.symm ▸ (gc.u_l_u_eq_u _).symm, λ HI, ⟨_, HI⟩ ⟩ lemma u_eq {z : α} {y : β} : u y = z ↔ ∀ x, x ≤ z ↔ l x ≤ y := begin split, { rintros rfl x, exact (gc x y).symm }, { intros H, exact ((H $ u y).mpr (gc.l_u_le y)).antisymm ((gc _ _).mp $ (H z).mp le_rfl) } end end partial_order section partial_order variables [preorder α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_u_l_eq_l (a : α) : l (u (l a)) = l a := (gc.l_u_le _).antisymm (gc.monotone_l (gc.le_u_l _)) lemma l_u_l_eq_l' : l ∘ u ∘ l = l := funext gc.l_u_l_eq_l lemma l_unique {l' : α → β} {u' : β → α} (gc' : galois_connection l' u') (hu : ∀ b, u b = u' b) {a : α} : l a = l' a := le_antisymm (gc.l_le $ (hu (l' a)).symm ▸ gc'.le_u_l _) (gc'.l_le $ hu (l a) ▸ gc.le_u_l _) /-- If there exists an `a` such that `b = l a`, then `a = u b` is one such element. -/ lemma exists_eq_l (b : β) : (∃ a : α, b = l a) ↔ b = l (u b) := ⟨λ ⟨S, hS⟩, hS.symm ▸ (gc.l_u_l_eq_l _).symm, λ HI, ⟨_, HI⟩ ⟩ lemma l_eq {x : α} {z : β} : l x = z ↔ ∀ y, z ≤ y ↔ x ≤ u y := begin split, { rintros rfl y, exact gc x y }, { intros H, exact ((gc _ _).mpr $ (H z).mp le_rfl).antisymm ((H $ l x).mpr (gc.le_u_l x)) } end end partial_order section order_top variables [partial_order α] [preorder β] [order_top α] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_top : u ⊤ = ⊤ := top_unique $ gc.le_u le_top end order_top section order_bot variables [preorder α] [partial_order β] [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_bot : l ⊥ = ⊥ := gc.dual.u_top end order_bot section semilattice_sup variables [semilattice_sup α] [semilattice_sup β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_sup : l (a₁ ⊔ a₂) = l a₁ ⊔ l a₂ := (gc.is_lub_l_image is_lub_pair).unique $ by simp only [image_pair, is_lub_pair] end semilattice_sup section semilattice_inf variables [semilattice_inf α] [semilattice_inf β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma u_inf : u (b₁ ⊓ b₂) = u b₁ ⊓ u b₂ := gc.dual.l_sup end semilattice_inf section complete_lattice variables [complete_lattice α] [complete_lattice β] {l : α → β} {u : β → α} (gc : galois_connection l u) include gc lemma l_supr {f : ι → α} : l (supr f) = ⨆ i, l (f i) := eq.symm $ is_lub.supr_eq $ show is_lub (range (l ∘ f)) (l (supr f)), by rw [range_comp, ← Sup_range]; exact gc.is_lub_l_image (is_lub_Sup _) lemma l_supr₂ {f : Π i, κ i → α} : l (⨆ i j, f i j) = ⨆ i j, l (f i j) := by simp_rw gc.l_supr lemma u_infi {f : ι → β} : u (infi f) = ⨅ i, u (f i) := gc.dual.l_supr lemma u_infi₂ {f : Π i, κ i → β} : u (⨅ i j, f i j) = ⨅ i j, u (f i j) := gc.dual.l_supr₂ lemma l_Sup {s : set α} : l (Sup s) = ⨆ a ∈ s, l a := by simp only [Sup_eq_supr, gc.l_supr] lemma u_Inf {s : set β} : u (Inf s) = ⨅ a ∈ s, u a := gc.dual.l_Sup end complete_lattice section linear_order variables [linear_order α] [linear_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) lemma lt_iff_lt {a : α} {b : β} : b < l a ↔ u b < a := lt_iff_lt_of_le_iff_le (gc a b) end linear_order /- Constructing Galois connections -/ section constructions protected lemma id [pα : preorder α] : @galois_connection α α pα pα id id := λ a b, iff.intro (λ x, x) (λ x, x) protected lemma compose [preorder α] [preorder β] [preorder γ] {l1 : α → β} {u1 : β → α} {l2 : β → γ} {u2 : γ → β} (gc1 : galois_connection l1 u1) (gc2 : galois_connection l2 u2) : galois_connection (l2 ∘ l1) (u1 ∘ u2) := by intros a b; rw [gc2, gc1] protected lemma dfun {ι : Type u} {α : ι → Type v} {β : ι → Type w} [∀ i, preorder (α i)] [∀ i, preorder (β i)] (l : Πi, α i → β i) (u : Πi, β i → α i) (gc : ∀ i, galois_connection (l i) (u i)) : galois_connection (λ (a : Π i, α i) i, l i (a i)) (λ b i, u i (b i)) := λ a b, forall_congr $ λ i, gc i (a i) (b i) end constructions lemma l_comm_of_u_comm {X : Type*} [preorder X] {Y : Type*} [preorder Y] {Z : Type*} [preorder Z] {W : Type*} [partial_order W] {lYX : X → Y} {uXY : Y → X} (hXY : galois_connection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : galois_connection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : galois_connection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : galois_connection lZX uXZ) (h : ∀ w, uXZ (uZW w) = uXY (uYW w)) {x : X} : lWZ (lZX x) = lWY (lYX x) := (hXZ.compose hZW).l_unique (hXY.compose hWY) h lemma u_comm_of_l_comm {X : Type*} [partial_order X] {Y : Type*} [preorder Y] {Z : Type*} [preorder Z] {W : Type*} [preorder W] {lYX : X → Y} {uXY : Y → X} (hXY : galois_connection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : galois_connection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : galois_connection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : galois_connection lZX uXZ) (h : ∀ x, lWZ (lZX x) = lWY (lYX x)) {w : W} : uXZ (uZW w) = uXY (uYW w) := (hXZ.compose hZW).u_unique (hXY.compose hWY) h lemma l_comm_iff_u_comm {X : Type*} [partial_order X] {Y : Type*} [preorder Y] {Z : Type*} [preorder Z] {W : Type*} [partial_order W] {lYX : X → Y} {uXY : Y → X} (hXY : galois_connection lYX uXY) {lWZ : Z → W} {uZW : W → Z} (hZW : galois_connection lWZ uZW) {lWY : Y → W} {uYW : W → Y} (hWY : galois_connection lWY uYW) {lZX : X → Z} {uXZ : Z → X} (hXZ : galois_connection lZX uXZ) : (∀ w : W, uXZ (uZW w) = uXY (uYW w)) ↔ ∀ x : X, lWZ (lZX x) = lWY (lYX x) := ⟨hXY.l_comm_of_u_comm hZW hWY hXZ, hXY.u_comm_of_l_comm hZW hWY hXZ⟩ end galois_connection section variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] {f : α → β → γ} {s : set α} {t : set β} {l u : α → β → γ} {l₁ u₁ : β → γ → α} {l₂ u₂ : α → γ → β} lemma Sup_image2_eq_Sup_Sup (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) : Sup (image2 l s t) = l (Sup s) (Sup t) := by simp_rw [Sup_image2, ←(h₂ _).l_Sup, ←(h₁ _).l_Sup] lemma Sup_image2_eq_Sup_Inf (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : Sup (image2 l s t) = l (Sup s) (Inf t) := @Sup_image2_eq_Sup_Sup _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma Sup_image2_eq_Inf_Sup (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) : Sup (image2 l s t) = l (Inf s) (Sup t) := @Sup_image2_eq_Sup_Sup αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma Sup_image2_eq_Inf_Inf (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : Sup (image2 l s t) = l (Inf s) (Inf t) := @Sup_image2_eq_Sup_Sup αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma Inf_image2_eq_Inf_Inf (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : Inf (image2 u s t) = u (Inf s) (Inf t) := by simp_rw [Inf_image2, ←(h₂ _).u_Inf, ←(h₁ _).u_Inf] lemma Inf_image2_eq_Inf_Sup (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : Inf (image2 u s t) = u (Inf s) (Sup t) := @Inf_image2_eq_Inf_Inf _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma Inf_image2_eq_Sup_Inf (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : Inf (image2 u s t) = u (Sup s) (Inf t) := @Inf_image2_eq_Inf_Inf αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma Inf_image2_eq_Sup_Sup (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : Inf (image2 u s t) = u (Sup s) (Sup t) := @Inf_image2_eq_Inf_Inf αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ end namespace order_iso variables [preorder α] [preorder β] @[simp] lemma bdd_above_image (e : α ≃o β) {s : set α} : bdd_above (e '' s) ↔ bdd_above s := e.to_galois_connection.bdd_above_l_image @[simp] lemma bdd_below_image (e : α ≃o β) {s : set α} : bdd_below (e '' s) ↔ bdd_below s := e.dual.bdd_above_image @[simp] lemma bdd_above_preimage (e : α ≃o β) {s : set β} : bdd_above (e ⁻¹' s) ↔ bdd_above s := by rw [← e.bdd_above_image, e.image_preimage] @[simp] lemma bdd_below_preimage (e : α ≃o β) {s : set β} : bdd_below (e ⁻¹' s) ↔ bdd_below s := by rw [← e.bdd_below_image, e.image_preimage] end order_iso namespace nat lemma galois_connection_mul_div {k : ℕ} (h : 0 < k) : galois_connection (λ n, n * k) (λ n, n / k) := λ x y, (le_div_iff_mul_le h).symm end nat /-- A Galois insertion is a Galois connection where `l ∘ u = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. Dual to `galois_coinsertion` -/ @[nolint has_nonempty_instance] structure galois_insertion {α β : Type*} [preorder α] [preorder β] (l : α → β) (u : β → α) := (choice : Πx : α, u (l x) ≤ x → β) (gc : galois_connection l u) (le_l_u : ∀ x, x ≤ l (u x)) (choice_eq : ∀ a h, choice a h = l a) /-- A constructor for a Galois insertion with the trivial `choice` function. -/ def galois_insertion.monotone_intro {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} (hu : monotone u) (hl : monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ b, l (u b) = b) : galois_insertion l u := { choice := λ x _, l x, gc := galois_connection.monotone_intro hu hl hul (λ b, le_of_eq (hlu b)), le_l_u := λ b, le_of_eq $ (hlu b).symm, choice_eq := λ _ _, rfl } /-- Makes a Galois insertion from an order-preserving bijection. -/ protected def order_iso.to_galois_insertion [preorder α] [preorder β] (oi : α ≃o β) : galois_insertion oi oi.symm := { choice := λ b h, oi b, gc := oi.to_galois_connection, le_l_u := λ g, le_of_eq (oi.right_inv g).symm, choice_eq := λ b h, rfl } /-- Make a `galois_insertion l u` from a `galois_connection l u` such that `∀ b, b ≤ l (u b)` -/ def galois_connection.to_galois_insertion {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) (h : ∀ b, b ≤ l (u b)) : galois_insertion l u := { choice := λ x _, l x, gc := gc, le_l_u := h, choice_eq := λ _ _, rfl } /-- Lift the bottom along a Galois connection -/ def galois_connection.lift_order_bot {α β : Type*} [preorder α] [order_bot α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u) : order_bot β := { bot := l ⊥, bot_le := λ b, gc.l_le $ bot_le } namespace galois_insertion variables {l : α → β} {u : β → α} lemma l_u_eq [preorder α] [partial_order β] (gi : galois_insertion l u) (b : β) : l (u b) = b := (gi.gc.l_u_le _).antisymm (gi.le_l_u _) lemma left_inverse_l_u [preorder α] [partial_order β] (gi : galois_insertion l u) : left_inverse l u := gi.l_u_eq lemma l_surjective [preorder α] [partial_order β] (gi : galois_insertion l u) : surjective l := gi.left_inverse_l_u.surjective lemma u_injective [preorder α] [partial_order β] (gi : galois_insertion l u) : injective u := gi.left_inverse_l_u.injective lemma l_sup_u [semilattice_sup α] [semilattice_sup β] (gi : galois_insertion l u) (a b : β) : l (u a ⊔ u b) = a ⊔ b := calc l (u a ⊔ u b) = l (u a) ⊔ l (u b) : gi.gc.l_sup ... = a ⊔ b : by simp only [gi.l_u_eq] lemma l_supr_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} (f : ι → β) : l (⨆ i, u (f i)) = ⨆ i, (f i) := calc l (⨆ (i : ι), u (f i)) = ⨆ (i : ι), l (u (f i)) : gi.gc.l_supr ... = ⨆ (i : ι), f i : congr_arg _ $ funext $ λ i, gi.l_u_eq (f i) lemma l_bsupr_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), β) : l (⨆ i hi, u (f i hi)) = ⨆ i hi, f i hi := by simp only [supr_subtype', gi.l_supr_u] lemma l_Sup_u_image [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) (s : set β) : l (Sup (u '' s)) = Sup s := by rw [Sup_image, gi.l_bsupr_u, Sup_eq_supr] lemma l_inf_u [semilattice_inf α] [semilattice_inf β] (gi : galois_insertion l u) (a b : β) : l (u a ⊓ u b) = a ⊓ b := calc l (u a ⊓ u b) = l (u (a ⊓ b)) : congr_arg l gi.gc.u_inf.symm ... = a ⊓ b : by simp only [gi.l_u_eq] lemma l_infi_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} (f : ι → β) : l (⨅ i, u (f i)) = ⨅ i, f i := calc l (⨅ (i : ι), u (f i)) = l (u (⨅ (i : ι), (f i))) : congr_arg l gi.gc.u_infi.symm ... = ⨅ (i : ι), f i : gi.l_u_eq _ lemma l_binfi_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), β) : l (⨅ i hi, u (f i hi)) = ⨅ i hi, f i hi := by simp only [infi_subtype', gi.l_infi_u] lemma l_Inf_u_image [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) (s : set β) : l (Inf (u '' s)) = Inf s := by rw [Inf_image, gi.l_binfi_u, Inf_eq_infi] lemma l_infi_of_ul_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} (f : ι → α) (hf : ∀ i, u (l (f i)) = f i) : l (⨅ i, f i) = ⨅ i, l (f i) := calc l (⨅ i, (f i)) = l ⨅ (i : ι), (u (l (f i))) : by simp [hf] ... = ⨅ i, l (f i) : gi.l_infi_u _ lemma l_binfi_of_ul_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), α) (hf : ∀ i hi, u (l (f i hi)) = f i hi) : l (⨅ i hi, f i hi) = ⨅ i hi, l (f i hi) := by { rw [infi_subtype', infi_subtype'], exact gi.l_infi_of_ul_eq_self _ (λ _, hf _ _) } lemma u_le_u_iff [preorder α] [preorder β] (gi : galois_insertion l u) {a b} : u a ≤ u b ↔ a ≤ b := ⟨λ h, (gi.le_l_u _).trans (gi.gc.l_le h), λ h, gi.gc.monotone_u h⟩ lemma strict_mono_u [preorder α] [preorder β] (gi : galois_insertion l u) : strict_mono u := strict_mono_of_le_iff_le $ λ _ _, gi.u_le_u_iff.symm lemma is_lub_of_u_image [preorder α] [preorder β] (gi : galois_insertion l u) {s : set β} {a : α} (hs : is_lub (u '' s) a) : is_lub s (l a) := ⟨λ x hx, (gi.le_l_u x).trans $ gi.gc.monotone_l $ hs.1 $ mem_image_of_mem _ hx, λ x hx, gi.gc.l_le $ hs.2 $ gi.gc.monotone_u.mem_upper_bounds_image hx⟩ lemma is_glb_of_u_image [preorder α] [preorder β] (gi : galois_insertion l u) {s : set β} {a : α} (hs : is_glb (u '' s) a) : is_glb s (l a) := ⟨λ x hx, gi.gc.l_le $ hs.1 $ mem_image_of_mem _ hx, λ x hx, (gi.le_l_u x).trans $ gi.gc.monotone_l $ hs.2 $ gi.gc.monotone_u.mem_lower_bounds_image hx⟩ section lift variables [partial_order β] /-- Lift the suprema along a Galois insertion -/ @[reducible] -- See note [reducible non instances] def lift_semilattice_sup [semilattice_sup α] (gi : galois_insertion l u) : semilattice_sup β := { sup := λ a b, l (u a ⊔ u b), le_sup_left := λ a b, (gi.le_l_u a).trans $ gi.gc.monotone_l $ le_sup_left, le_sup_right := λ a b, (gi.le_l_u b).trans $ gi.gc.monotone_l $ le_sup_right, sup_le := λ a b c hac hbc, gi.gc.l_le $ sup_le (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc), .. ‹partial_order β› } /-- Lift the infima along a Galois insertion -/ @[reducible] -- See note [reducible non instances] def lift_semilattice_inf [semilattice_inf α] (gi : galois_insertion l u) : semilattice_inf β := { inf := λ a b, gi.choice (u a ⊓ u b) $ (le_inf (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_left) (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_right)), inf_le_left := by simp only [gi.choice_eq]; exact λ a b, gi.gc.l_le inf_le_left, inf_le_right := by simp only [gi.choice_eq]; exact λ a b, gi.gc.l_le inf_le_right, le_inf := by simp only [gi.choice_eq]; exact λ a b c hac hbc, (gi.le_l_u a).trans $ gi.gc.monotone_l $ le_inf (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc), .. ‹partial_order β› } /-- Lift the suprema and infima along a Galois insertion -/ @[reducible] -- See note [reducible non instances] def lift_lattice [lattice α] (gi : galois_insertion l u) : lattice β := { .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf } /-- Lift the top along a Galois insertion -/ @[reducible] -- See note [reducible non instances] def lift_order_top [preorder α] [order_top α] (gi : galois_insertion l u) : order_top β := { top := gi.choice ⊤ $ le_top, le_top := by simp only [gi.choice_eq]; exact λ b, (gi.le_l_u b).trans (gi.gc.monotone_l le_top) } /-- Lift the top, bottom, suprema, and infima along a Galois insertion -/ @[reducible] -- See note [reducible non instances] def lift_bounded_order [preorder α] [bounded_order α] (gi : galois_insertion l u) : bounded_order β := { .. gi.lift_order_top, .. gi.gc.lift_order_bot } /-- Lift all suprema and infima along a Galois insertion -/ @[reducible] -- See note [reducible non instances] def lift_complete_lattice [complete_lattice α] (gi : galois_insertion l u) : complete_lattice β := { Sup := λ s, l (Sup (u '' s)), Sup_le := λ s, (gi.is_lub_of_u_image (is_lub_Sup _)).2, le_Sup := λ s, (gi.is_lub_of_u_image (is_lub_Sup _)).1, Inf := λ s, gi.choice (Inf (u '' s)) $ (is_glb_Inf _).2 $ gi.gc.monotone_u.mem_lower_bounds_image (gi.is_glb_of_u_image $ is_glb_Inf _).1, Inf_le := λ s, by { rw gi.choice_eq, exact (gi.is_glb_of_u_image (is_glb_Inf _)).1 }, le_Inf := λ s, by { rw gi.choice_eq, exact (gi.is_glb_of_u_image (is_glb_Inf _)).2 }, .. gi.lift_bounded_order, .. gi.lift_lattice } end lift end galois_insertion /-- A Galois coinsertion is a Galois connection where `u ∘ l = id`. It also contains a constructive choice function, to give better definitional equalities when lifting order structures. Dual to `galois_insertion` -/ @[nolint has_nonempty_instance] structure galois_coinsertion [preorder α] [preorder β] (l : α → β) (u : β → α) := (choice : Πx : β, x ≤ l (u x) → α) (gc : galois_connection l u) (u_l_le : ∀ x, u (l x) ≤ x) (choice_eq : ∀ a h, choice a h = u a) /-- Make a `galois_insertion` between `αᵒᵈ` and `βᵒᵈ` from a `galois_coinsertion` between `α` and `β`. -/ def galois_coinsertion.dual [preorder α] [preorder β] {l : α → β} {u : β → α} : galois_coinsertion l u → galois_insertion (to_dual ∘ u ∘ of_dual) (to_dual ∘ l ∘ of_dual) := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `galois_coinsertion` between `αᵒᵈ` and `βᵒᵈ` from a `galois_insertion` between `α` and `β`. -/ def galois_insertion.dual [preorder α] [preorder β] {l : α → β} {u : β → α} : galois_insertion l u → galois_coinsertion (to_dual ∘ u ∘ of_dual) (to_dual ∘ l ∘ of_dual) := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `galois_insertion` between `α` and `β` from a `galois_coinsertion` between `αᵒᵈ` and `βᵒᵈ`. -/ def galois_coinsertion.of_dual [preorder α] [preorder β] {l : αᵒᵈ → βᵒᵈ} {u : βᵒᵈ → αᵒᵈ} : galois_coinsertion l u → galois_insertion (of_dual ∘ u ∘ to_dual) (of_dual ∘ l ∘ to_dual) := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Make a `galois_coinsertion` between `α` and `β` from a `galois_insertion` between `αᵒᵈ` and `βᵒᵈ`. -/ def galois_insertion.of_dual [preorder α] [preorder β] {l : αᵒᵈ → βᵒᵈ} {u : βᵒᵈ → αᵒᵈ} : galois_insertion l u → galois_coinsertion (of_dual ∘ u ∘ to_dual) (of_dual ∘ l ∘ to_dual) := λ x, ⟨x.1, x.2.dual, x.3, x.4⟩ /-- Makes a Galois coinsertion from an order-preserving bijection. -/ protected def order_iso.to_galois_coinsertion [preorder α] [preorder β] (oi : α ≃o β) : galois_coinsertion oi oi.symm := { choice := λ b h, oi.symm b, gc := oi.to_galois_connection, u_l_le := λ g, le_of_eq (oi.left_inv g), choice_eq := λ b h, rfl } /-- A constructor for a Galois coinsertion with the trivial `choice` function. -/ def galois_coinsertion.monotone_intro [preorder α] [preorder β] {l : α → β} {u : β → α} (hu : monotone u) (hl : monotone l) (hlu : ∀ b, l (u b) ≤ b) (hul : ∀ a, u (l a) = a) : galois_coinsertion l u := (galois_insertion.monotone_intro hl.dual hu.dual hlu hul).of_dual /-- Make a `galois_coinsertion l u` from a `galois_connection l u` such that `∀ b, b ≤ l (u b)` -/ def galois_connection.to_galois_coinsertion {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) (h : ∀ a, u (l a) ≤ a) : galois_coinsertion l u := { choice := λ x _, u x, gc := gc, u_l_le := h, choice_eq := λ _ _, rfl } /-- Lift the top along a Galois connection -/ def galois_connection.lift_order_top {α β : Type*} [partial_order α] [preorder β] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u) : order_top α := { top := u ⊤, le_top := λ b, gc.le_u $ le_top } namespace galois_coinsertion variables {l : α → β} {u : β → α} lemma u_l_eq [partial_order α] [preorder β] (gi : galois_coinsertion l u) (a : α) : u (l a) = a := gi.dual.l_u_eq a lemma u_l_left_inverse [partial_order α] [preorder β] (gi : galois_coinsertion l u) : left_inverse u l := gi.u_l_eq lemma u_surjective [partial_order α] [preorder β] (gi : galois_coinsertion l u) : surjective u := gi.dual.l_surjective lemma l_injective [partial_order α] [preorder β] (gi : galois_coinsertion l u) : injective l := gi.dual.u_injective lemma u_inf_l [semilattice_inf α] [semilattice_inf β] (gi : galois_coinsertion l u) (a b : α) : u (l a ⊓ l b) = a ⊓ b := gi.dual.l_sup_u a b lemma u_infi_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} (f : ι → α) : u (⨅ i, l (f i)) = ⨅ i, (f i) := gi.dual.l_supr_u _ lemma u_Inf_l_image [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) (s : set α) : u (Inf (l '' s)) = Inf s := gi.dual.l_Sup_u_image _ lemma u_sup_l [semilattice_sup α] [semilattice_sup β] (gi : galois_coinsertion l u) (a b : α) : u (l a ⊔ l b) = a ⊔ b := gi.dual.l_inf_u _ _ lemma u_supr_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} (f : ι → α) : u (⨆ i, l (f i)) = ⨆ i, (f i) := gi.dual.l_infi_u _ lemma u_bsupr_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), α) : u (⨆ i hi, l (f i hi)) = ⨆ i hi, f i hi := gi.dual.l_binfi_u _ lemma u_Sup_l_image [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) (s : set α) : u (Sup (l '' s)) = Sup s := gi.dual.l_Inf_u_image _ lemma u_supr_of_lu_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} (f : ι → β) (hf : ∀ i, l (u (f i)) = f i) : u (⨆ i, (f i)) = ⨆ i, u (f i) := gi.dual.l_infi_of_ul_eq_self _ hf lemma u_bsupr_of_lu_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u) {ι : Sort x} {p : ι → Prop} (f : Π i (hi : p i), β) (hf : ∀ i hi, l (u (f i hi)) = f i hi) : u (⨆ i hi, f i hi) = ⨆ i hi, u (f i hi) := gi.dual.l_binfi_of_ul_eq_self _ hf lemma l_le_l_iff [preorder α] [preorder β] (gi : galois_coinsertion l u) {a b} : l a ≤ l b ↔ a ≤ b := gi.dual.u_le_u_iff lemma strict_mono_l [preorder α] [preorder β] (gi : galois_coinsertion l u) : strict_mono l := λ a b h, gi.dual.strict_mono_u h lemma is_glb_of_l_image [preorder α] [preorder β] (gi : galois_coinsertion l u) {s : set α} {a : β} (hs : is_glb (l '' s) a) : is_glb s (u a) := gi.dual.is_lub_of_u_image hs lemma is_lub_of_l_image [preorder α] [preorder β] (gi : galois_coinsertion l u) {s : set α} {a : β} (hs : is_lub (l '' s) a) : is_lub s (u a) := gi.dual.is_glb_of_u_image hs section lift variables [partial_order α] /-- Lift the infima along a Galois coinsertion -/ @[reducible] -- See note [reducible non instances] def lift_semilattice_inf [semilattice_inf β] (gi : galois_coinsertion l u) : semilattice_inf α := { inf := λ a b, u (l a ⊓ l b), .. ‹partial_order α›, .. @order_dual.semilattice_inf _ gi.dual.lift_semilattice_sup } /-- Lift the suprema along a Galois coinsertion -/ @[reducible] -- See note [reducible non instances] def lift_semilattice_sup [semilattice_sup β] (gi : galois_coinsertion l u) : semilattice_sup α := { sup := λ a b, gi.choice (l a ⊔ l b) $ (sup_le (gi.gc.monotone_l $ gi.gc.le_u $ le_sup_left) (gi.gc.monotone_l $ gi.gc.le_u $ le_sup_right)), .. ‹partial_order α›, .. @order_dual.semilattice_sup _ gi.dual.lift_semilattice_inf } /-- Lift the suprema and infima along a Galois coinsertion -/ @[reducible] -- See note [reducible non instances] def lift_lattice [lattice β] (gi : galois_coinsertion l u) : lattice α := { .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf } /-- Lift the bot along a Galois coinsertion -/ @[reducible] -- See note [reducible non instances] def lift_order_bot [preorder β] [order_bot β] (gi : galois_coinsertion l u) : order_bot α := { bot := gi.choice ⊥ $ bot_le, .. @order_dual.order_bot _ _ gi.dual.lift_order_top } /-- Lift the top, bottom, suprema, and infima along a Galois coinsertion -/ @[reducible] -- See note [reducible non instances] def lift_bounded_order [preorder β] [bounded_order β] (gi : galois_coinsertion l u) : bounded_order α := { .. gi.lift_order_bot, .. gi.gc.lift_order_top } /-- Lift all suprema and infima along a Galois coinsertion -/ @[reducible] -- See note [reducible non instances] def lift_complete_lattice [complete_lattice β] (gi : galois_coinsertion l u) : complete_lattice α := { Inf := λ s, u (Inf (l '' s)), Sup := λ s, gi.choice (Sup (l '' s)) _, .. @order_dual.complete_lattice _ gi.dual.lift_complete_lattice } end lift end galois_coinsertion /-- If `α` is a partial order with bottom element (e.g., `ℕ`, `ℝ≥0`), then `λ o : with_bot α, o.get_or_else ⊥` and coercion form a Galois insertion. -/ def with_bot.gi_get_or_else_bot [preorder α] [order_bot α] : galois_insertion (λ o : with_bot α, o.get_or_else ⊥) coe := { gc := λ a b, with_bot.get_or_else_bot_le_iff, le_l_u := λ a, le_rfl, choice := λ o ho, _, choice_eq := λ _ _, rfl }
7b28cbc115395e62930f7979d4a801fdafd51972
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/e2.lean
d1075ffb8f23247f870c75a5aa8298377cbf3362
[ "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
47
lean
prelude definition Prop := Type.{0} check Prop
359b9f217901626bda14bedff6601543ec96efdc
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/graded_monoid.lean
e9eda4abd2892e7e141149d5dc0b8c1dec022313
[ "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
14,009
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.group.inj_surj import algebra.group_power.basic import data.set_like.basic import data.sigma.basic import group_theory.group_action.defs /-! # Additively-graded multiplicative structures This module provides a set of heterogeneous typeclasses for defining a multiplicative structure over the sigma type `graded_monoid A` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an additively-graded monoid. The typeclasses are: * `graded_monoid.ghas_one A` * `graded_monoid.ghas_mul A` * `graded_monoid.gmonoid A` * `graded_monoid.gcomm_monoid A` With the `sigma_graded` locale open, these respectively imbue: * `has_one (graded_monoid A)` * `has_mul (graded_monoid A)` * `monoid (graded_monoid A)` * `comm_monoid (graded_monoid A)` the base type `A 0` with: * `graded_monoid.grade_zero.has_one` * `graded_monoid.grade_zero.has_mul` * `graded_monoid.grade_zero.monoid` * `graded_monoid.grade_zero.comm_monoid` and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication: * (nothing) * `graded_monoid.grade_zero.has_scalar (A 0)` * `graded_monoid.grade_zero.mul_action (A 0)` * (nothing) For now, these typeclasses are primarily used in the construction of `direct_sum.ring` and the rest of that file. ## Internally graded monoids In addition to the above typeclasses, in the most frequent case when `A` is an indexed collection of `set_like` subobjects (such as `add_submonoid`s, `add_subgroup`s, or `submodule`s), this file provides the `Prop` typeclasses: * `set_like.has_graded_one A` (which provides the obvious `graded_monoid.ghas_one A` instance) * `set_like.has_graded_mul A` (which provides the obvious `graded_monoid.ghas_mul A` instance) * `set_like.graded_monoid A` (which provides the obvious `graded_monoid.gmonoid A` and `graded_monoid.gcomm_monoid A` instances) Strictly this last class is unecessary as it has no fields not present in its parents, but it is included for convenience. Note that there is no need for `graded_ring` or similar, as all the information it would contain is already supplied by `graded_monoid` when `A` is a collection of additively-closed set_like objects such as `submodules`. These constructions are explored in `algebra.direct_sum.internal`. ## tags graded monoid -/ set_option old_structure_cmd true variables {ι : Type*} /-- A type alias of sigma types for graded monoids. -/ def graded_monoid (A : ι → Type*) := sigma A namespace graded_monoid instance {A : ι → Type*} [inhabited ι] [inhabited (A (default ι))]: inhabited (graded_monoid A) := sigma.inhabited /-- Construct an element of a graded monoid. -/ def mk {A : ι → Type*} : Π i, A i → graded_monoid A := sigma.mk /-! ### Typeclasses -/ section defs variables (A : ι → Type*) /-- A graded version of `has_one`, which must be of grade 0. -/ class ghas_one [has_zero ι] := (one : A 0) /-- `ghas_one` implies `has_one (graded_monoid A)` -/ instance ghas_one.to_has_one [has_zero ι] [ghas_one A] : has_one (graded_monoid A) := ⟨⟨_, ghas_one.one⟩⟩ /-- A graded version of `has_mul`. Multiplication combines grades additively, like `add_monoid_algebra`. -/ class ghas_mul [has_add ι] := (mul {i j} : A i → A j → A (i + j)) /-- `ghas_mul` implies `has_mul (graded_monoid A)`. -/ instance ghas_mul.to_has_mul [has_add ι] [ghas_mul A] : has_mul (graded_monoid A) := ⟨λ (x y : graded_monoid A), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩ lemma mk_mul_mk [has_add ι] [ghas_mul A] {i j} (a : A i) (b : A j) : mk i a * mk j b = mk (i + j) (ghas_mul.mul a b) := rfl namespace gmonoid variables {A} [add_monoid ι] [ghas_mul A] [ghas_one A] /-- A default implementation of power on a graded monoid, like `npow_rec`. `gmonoid.gnpow` should be used instead. -/ def gnpow_rec : Π (n : ℕ) {i}, A i → A (n • i) | 0 i a := cast (congr_arg A (zero_nsmul i).symm) ghas_one.one | (n + 1) i a := cast (congr_arg A (succ_nsmul i n).symm) (ghas_mul.mul a $ gnpow_rec _ a) @[simp] lemma gnpow_rec_zero (a : graded_monoid A) : graded_monoid.mk _ (gnpow_rec 0 a.snd) = 1 := sigma.ext (zero_nsmul _) (heq_of_cast_eq _ rfl).symm /-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_zero'` when the default `graded_monoid.gmonoid.gnpow_rec` is used. -/ meta def apply_gnpow_rec_zero_tac : tactic unit := `[apply direct_sum.gmonoid.gnpow_rec_zero] @[simp] lemma gnpow_rec_succ (n : ℕ) (a : graded_monoid A) : (graded_monoid.mk _ $ gnpow_rec n.succ a.snd) = a * ⟨_, gnpow_rec n a.snd⟩ := sigma.ext (succ_nsmul _ _) (heq_of_cast_eq _ rfl).symm /-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_succ'` when the default `graded_monoid.gmonoid.gnpow_rec` is used. -/ meta def apply_gnpow_rec_succ_tac : tactic unit := `[apply direct_sum.gmonoid.gnpow_rec_succ] end gmonoid /-- A graded version of `monoid`. Like `monoid.npow`, this has an optional `gmonoid.gnpow` field to allow definitional control of natural powers of a graded monoid. -/ class gmonoid [add_monoid ι] extends ghas_mul A, ghas_one A := (one_mul (a : graded_monoid A) : 1 * a = a) (mul_one (a : graded_monoid A) : a * 1 = a) (mul_assoc (a b c : graded_monoid A) : a * b * c = a * (b * c)) (gnpow : Π (n : ℕ) {i}, A i → A (n • i) := gmonoid.gnpow_rec) (gnpow_zero' : Π (a : graded_monoid A), graded_monoid.mk _ (gnpow 0 a.snd) = 1 . gmonoid.apply_gnpow_rec_zero_tac) (gnpow_succ' : Π (n : ℕ) (a : graded_monoid A), (graded_monoid.mk _ $ gnpow n.succ a.snd) = a * ⟨_, gnpow n a.snd⟩ . gmonoid.apply_gnpow_rec_succ_tac) /-- `gmonoid` implies a `monoid (graded_monoid A)`. -/ instance gmonoid.to_monoid [add_monoid ι] [gmonoid A] : monoid (graded_monoid A) := { one := (1), mul := (*), npow := λ n a, graded_monoid.mk _ (gmonoid.gnpow n a.snd), npow_zero' := λ a, gmonoid.gnpow_zero' a, npow_succ' := λ n a, gmonoid.gnpow_succ' n a, one_mul := gmonoid.one_mul, mul_one := gmonoid.mul_one, mul_assoc := gmonoid.mul_assoc } lemma mk_pow [add_monoid ι] [gmonoid A] {i} (a : A i) (n : ℕ) : mk i a ^ n = mk (n • i) (gmonoid.gnpow _ a) := begin induction n with n, { rw [pow_zero], exact (gmonoid.gnpow_zero' ⟨_, a⟩).symm, }, { rw [pow_succ, n_ih, mk_mul_mk], exact (gmonoid.gnpow_succ' n ⟨_, a⟩).symm, }, end /-- A graded version of `comm_monoid`. -/ class gcomm_monoid [add_comm_monoid ι] extends gmonoid A := (mul_comm (a : graded_monoid A) (b : graded_monoid A) : a * b = b * a) /-- `gcomm_monoid` implies a `comm_monoid (graded_monoid A)`, although this is only used as an instance locally to define notation in `gmonoid` and similar typeclasses. -/ instance gcomm_monoid.to_comm_monoid [add_comm_monoid ι] [gcomm_monoid A] : comm_monoid (graded_monoid A) := { mul_comm := gcomm_monoid.mul_comm, ..gmonoid.to_monoid A } end defs /-! ### Instances for `A 0` The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various types of multiplicative structure. -/ section grade_zero variables (A : ι → Type*) section one variables [has_zero ι] [ghas_one A] /-- `1 : A 0` is the value provided in `ghas_one.one`. -/ @[nolint unused_arguments] instance grade_zero.has_one : has_one (A 0) := ⟨ghas_one.one⟩ end one section mul variables [add_monoid ι] [ghas_mul A] /-- `(•) : A 0 → A i → A i` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + i)` into `A i`. -/ instance grade_zero.has_scalar (i : ι) : has_scalar (A 0) (A i) := { smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) } /-- `(*) : A 0 → A 0 → A 0` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + 0)` into `A 0`. -/ instance grade_zero.has_mul : has_mul (A 0) := { mul := (•) } variables {A} @[simp] lemma mk_zero_smul {i} (a : A 0) (b : A i) : mk _ (a • b) = mk _ a * mk _ b := sigma.ext (zero_add _).symm $ eq_rec_heq _ _ @[simp] lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl end mul section monoid variables [add_monoid ι] [gmonoid A] /-- The `monoid` structure derived from `gmonoid A`. -/ instance grade_zero.monoid : monoid (A 0) := function.injective.monoid (mk 0) sigma_mk_injective rfl mk_zero_smul end monoid section monoid variables [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_monoid` structure derived from `gcomm_monoid A`. -/ instance grade_zero.comm_monoid : comm_monoid (A 0) := function.injective.comm_monoid (mk 0) sigma_mk_injective rfl mk_zero_smul end monoid section mul_action variables [add_monoid ι] [gmonoid A] /-- `graded_monoid.mk 0` is a `monoid_hom`, using the `graded_monoid.grade_zero.monoid` structure. -/ def mk_zero_monoid_hom : A 0 →* (graded_monoid A) := { to_fun := mk 0, map_one' := rfl, map_mul' := mk_zero_smul } /-- Each grade `A i` derives a `A 0`-action structure from `gmonoid A`. -/ instance grade_zero.mul_action {i} : mul_action (A 0) (A i) := begin letI := mul_action.comp_hom (graded_monoid A) (mk_zero_monoid_hom A), exact function.injective.mul_action (mk i) sigma_mk_injective mk_zero_smul, end end mul_action end grade_zero end graded_monoid /-! ### Concrete instances -/ section variables (ι) {R : Type*} @[simps one] instance has_one.ghas_one [has_zero ι] [has_one R] : graded_monoid.ghas_one (λ i : ι, R) := { one := 1 } @[simps mul] instance has_mul.ghas_mul [has_add ι] [has_mul R] : graded_monoid.ghas_mul (λ i : ι, R) := { mul := λ i j, (*) } /-- If all grades are the same type and themselves form a monoid, then there is a trivial grading structure. -/ @[simps gnpow] instance monoid.gmonoid [add_monoid ι] [monoid R] : graded_monoid.gmonoid (λ i : ι, R) := { one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)), mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)), mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)), gnpow := λ n i a, a ^ n, gnpow_zero' := λ a, sigma.ext (zero_nsmul _) (heq_of_eq (monoid.npow_zero' _)), gnpow_succ' := λ n ⟨i, a⟩, sigma.ext (succ_nsmul _ _) (heq_of_eq (monoid.npow_succ' _ _)), ..has_one.ghas_one ι, ..has_mul.ghas_mul ι } /-- If all grades are the same type and themselves form a commutative monoid, then there is a trivial grading structure. -/ instance comm_monoid.gcomm_monoid [add_comm_monoid ι] [comm_monoid R] : graded_monoid.gcomm_monoid (λ i : ι, R) := { mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)), ..monoid.gmonoid ι } end /-! ### Shorthands for creating instance of the above typeclasses for collections of subobjects -/ section subobjects variables {R : Type*} /-- A version of `graded_monoid.ghas_one` for internally graded objects. -/ class set_like.has_graded_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S) : Prop := (one_mem : (1 : R) ∈ A 0) instance set_like.ghas_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S) [set_like.has_graded_one A] : graded_monoid.ghas_one (λ i, A i) := { one := ⟨1, set_like.has_graded_one.one_mem⟩ } @[simp] lemma set_like.coe_ghas_one {S : Type*} [set_like S R] [has_one R] [has_zero ι] (A : ι → S) [set_like.has_graded_one A] : ↑(@graded_monoid.ghas_one.one _ (λ i, A i) _ _) = (1 : R) := rfl /-- A version of `graded_monoid.ghas_one` for internally graded objects. -/ class set_like.has_graded_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S) : Prop := (mul_mem : ∀ ⦃i j⦄ {gi gj}, gi ∈ A i → gj ∈ A j → gi * gj ∈ A (i + j)) instance set_like.ghas_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S) [set_like.has_graded_mul A] : graded_monoid.ghas_mul (λ i, A i) := { mul := λ i j a b, ⟨(a * b : R), set_like.has_graded_mul.mul_mem a.prop b.prop⟩ } @[simp] lemma set_like.coe_ghas_mul {S : Type*} [set_like S R] [has_mul R] [has_add ι] (A : ι → S) [set_like.has_graded_mul A] {i j : ι} (x : A i) (y : A j) : ↑(@graded_monoid.ghas_mul.mul _ (λ i, A i) _ _ _ _ x y) = (x * y : R) := rfl /-- A version of `graded_monoid.gmonoid` for internally graded objects. -/ class set_like.graded_monoid {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S) extends set_like.has_graded_one A, set_like.has_graded_mul A : Prop /-- Build a `gmonoid` instance for a collection of subobjects. -/ instance set_like.gmonoid {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S) [set_like.graded_monoid A] : graded_monoid.gmonoid (λ i, A i) := { one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _), mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _), mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩, sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _), gnpow := λ n i a, ⟨a ^ n, begin induction n, { rw [pow_zero, zero_nsmul], exact set_like.has_graded_one.one_mem }, { rw [pow_succ', succ_nsmul'], exact set_like.has_graded_mul.mul_mem n_ih a.prop }, end⟩, gnpow_zero' := λ n, sigma.subtype_ext (zero_nsmul _) (pow_zero _), gnpow_succ' := λ n a, sigma.subtype_ext (succ_nsmul _ _) (pow_succ _ _), ..set_like.ghas_one A, ..set_like.ghas_mul A } @[simp] lemma set_like.coe_gpow {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (A : ι → S) [set_like.graded_monoid A] {i : ι} (x : A i) (n : ℕ) : ↑(@graded_monoid.gmonoid.gnpow _ (λ i, A i) _ _ n _ x) = (x ^ n : R) := rfl /-- Build a `gcomm_monoid` instance for a collection of subobjects. -/ instance set_like.gcomm_monoid {S : Type*} [set_like S R] [comm_monoid R] [add_comm_monoid ι] (A : ι → S) [set_like.graded_monoid A] : graded_monoid.gcomm_monoid (λ i, A i) := { mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _), ..set_like.gmonoid A} end subobjects
61fa1275518b0b7eb1f23edfe7511964edf8887f
3aad12fe82645d2d3173fbedc2e5c2ba945a4d75
/src/data/pfun/nursery.lean
7d858de558b90091a742c613fd9f98b0be7e7c6c
[]
no_license
seanpm2001/LeanProver-Community_MathLIB-Nursery
4f88d539cb18d73a94af983092896b851e6640b5
0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec
refs/heads/master
1,688,730,786,645
1,572,070,026,000
1,572,070,026,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,120
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import data.pfun namespace roption variables {α : Type*} {β : Type*} {γ : Type*} open function lemma assert_if_neg {p : Prop} (x : p → roption α) (h : ¬ p) : assert p x = roption.none := by { dsimp [assert,roption.none], have : (∃ (h : p), (x h).dom) ↔ false, { split ; intros h' ; repeat { cases h' with h' }, exact h h' }, congr, repeat { rw this <|> apply hfunext }, intros h h', cases h', } lemma assert_if_pos {p : Prop} (x : p → roption α) (h : p) : assert p x = x h := by { dsimp [assert], have : (∃ (h : p), (x h).dom) ↔ (x h).dom, { split ; intros h' ; cases h' <|> split ; assumption, }, cases hx : x h, congr, rw [this,hx], apply hfunext, rw [this,hx], intros, simp [hx] } @[simp] lemma roption.none_bind {α β : Type*} (f : α → roption β) : roption.none >>= f = roption.none := by simp [roption.none,has_bind.bind,roption.bind,assert_if_neg] end roption
7a8a3f34ddeb0e47894c59e85fe5a51b760d6840
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/subalgebra.lean
b994a6914b853d96fd09504392e3687c59a9210e
[ "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
23,371
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import ring_theory.noetherian /-! # Lie subalgebras This file defines Lie subalgebras of a Lie algebra and provides basic related definitions and results. ## Main definitions * `lie_subalgebra` * `lie_subalgebra.incl` * `lie_subalgebra.map` * `lie_hom.range` * `lie_equiv.of_injective` * `lie_equiv.of_eq` * `lie_equiv.of_subalgebra` * `lie_equiv.of_subalgebras` ## Tags lie algebra, lie subalgebra -/ universes u v w w₁ w₂ section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem' : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) attribute [nolint doc_blame] lie_subalgebra.to_submodule /-- The zero algebra is a subalgebra of any Lie algebra. -/ instance : has_zero (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie], exact submodule.zero_mem (0 : submodule R L), }, ..(0 : submodule R L) }⟩ instance : inhabited (lie_subalgebra R L) := ⟨0⟩ instance : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ namespace lie_subalgebra instance : set_like (lie_subalgebra R L) L := { coe := λ L', L', coe_injective' := λ L' L'' h, by { rcases L' with ⟨⟨⟩⟩, rcases L'' with ⟨⟨⟩⟩, congr' } } instance : add_subgroup_class (lie_subalgebra R L) L := { add_mem := λ L' _ _, L'.add_mem', zero_mem := λ L', L'.zero_mem', neg_mem := λ L' x hx, show -x ∈ (L' : submodule R L), from neg_mem hx } /-- A Lie subalgebra forms a new Lie ring. -/ instance (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem' x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, leibniz_lie := by { intros, apply set_coe.ext, apply leibniz_lie, } } section variables {R₁ : Type*} [semiring R₁] /-- A Lie subalgebra inherits module structures from `L`. -/ instance [has_smul R₁ R] [module R₁ L] [is_scalar_tower R₁ R L] (L' : lie_subalgebra R L) : module R₁ L' := L'.to_submodule.module' instance [has_smul R₁ R] [has_smul R₁ᵐᵒᵖ R] [module R₁ L] [module R₁ᵐᵒᵖ L] [is_scalar_tower R₁ R L] [is_scalar_tower R₁ᵐᵒᵖ R L] [is_central_scalar R₁ L] (L' : lie_subalgebra R L) : is_central_scalar R₁ L' := L'.to_submodule.is_central_scalar instance [has_smul R₁ R] [module R₁ L] [is_scalar_tower R₁ R L] (L' : lie_subalgebra R L) : is_scalar_tower R₁ R L' := L'.to_submodule.is_scalar_tower instance (L' : lie_subalgebra R L) [is_noetherian R L] : is_noetherian R L' := is_noetherian_submodule' ↑L' end /-- A Lie subalgebra forms a new Lie algebra. -/ instance (L' : lie_subalgebra R L) : lie_algebra R L' := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } variables {R L} (L' : lie_subalgebra R L) @[simp] protected lemma zero_mem : (0 : L) ∈ L' := zero_mem L' protected lemma add_mem {x y : L} : x ∈ L' → y ∈ L' → (x + y : L) ∈ L' := add_mem protected lemma sub_mem {x y : L} : x ∈ L' → y ∈ L' → (x - y : L) ∈ L' := sub_mem lemma smul_mem (t : R) {x : L} (h : x ∈ L') : t • x ∈ L' := (L' : submodule R L).smul_mem t h lemma lie_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (⁅x, y⁆ : L) ∈ L' := L'.lie_mem' hx hy @[simp] lemma mem_carrier {x : L} : x ∈ L'.carrier ↔ x ∈ (L' : set L) := iff.rfl @[simp] lemma mem_mk_iff (S : set L) (h₁ h₂ h₃ h₄) {x : L} : x ∈ (⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) ↔ x ∈ S := iff.rfl @[simp] lemma mem_coe_submodule {x : L} : x ∈ (L' : submodule R L) ↔ x ∈ L' := iff.rfl lemma mem_coe {x : L} : x ∈ (L' : set L) ↔ x ∈ L' := iff.rfl @[simp, norm_cast] lemma coe_bracket (x y : L') : (↑⁅x, y⁆ : L) = ⁅(↑x : L), ↑y⁆ := rfl lemma ext_iff (x y : L') : x = y ↔ (x : L) = y := subtype.ext_iff lemma coe_zero_iff_zero (x : L') : (x : L) = 0 ↔ x = 0 := (ext_iff L' x 0).symm @[ext] lemma ext (L₁' L₂' : lie_subalgebra R L) (h : ∀ x, x ∈ L₁' ↔ x ∈ L₂') : L₁' = L₂' := set_like.ext h lemma ext_iff' (L₁' L₂' : lie_subalgebra R L) : L₁' = L₂' ↔ ∀ x, x ∈ L₁' ↔ x ∈ L₂' := set_like.ext_iff @[simp] lemma mk_coe (S : set L) (h₁ h₂ h₃ h₄) : ((⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) : set L) = S := rfl @[simp] lemma coe_to_submodule_mk (p : submodule R L) (h) : (({lie_mem' := h, ..p} : lie_subalgebra R L) : submodule R L) = p := by { cases p, refl, } lemma coe_injective : function.injective (coe : lie_subalgebra R L → set L) := set_like.coe_injective @[norm_cast] theorem coe_set_eq (L₁' L₂' : lie_subalgebra R L) : (L₁' : set L) = L₂' ↔ L₁' = L₂' := set_like.coe_set_eq lemma to_submodule_injective : function.injective (coe : lie_subalgebra R L → submodule R L) := λ L₁' L₂' h, by { rw set_like.ext'_iff at h, rw ← coe_set_eq, exact h, } @[simp] lemma coe_to_submodule_eq_iff (L₁' L₂' : lie_subalgebra R L) : (L₁' : submodule R L) = (L₂' : submodule R L) ↔ L₁' = L₂' := to_submodule_injective.eq_iff @[norm_cast] lemma coe_to_submodule : ((L' : submodule R L) : set L) = L' := rfl section lie_module variables {M : Type w} [add_comm_group M] [lie_ring_module L M] variables {N : Type w₁} [add_comm_group N] [lie_ring_module L N] [module R N] [lie_module R L N] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie ring module `M` of `L`, we may regard `M` as a Lie ring module of `L'` by restriction. -/ instance : lie_ring_module L' M := { bracket := λ x m, ⁅(x : L), m⁆, add_lie := λ x y m, add_lie x y m, lie_add := λ x y m, lie_add x y m, leibniz_lie := λ x y m, leibniz_lie x y m, } @[simp] lemma coe_bracket_of_module (x : L') (m : M) : ⁅x, m⁆ = ⁅(x : L), m⁆ := rfl variables [module R M] [lie_module R L M] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie module `M` of `L`, we may regard `M` as a Lie module of `L'` by restriction. -/ instance : lie_module R L' M := { smul_lie := λ t x m, by simp only [coe_bracket_of_module, smul_lie, submodule.coe_smul_of_tower], lie_smul := λ t x m, by simp only [coe_bracket_of_module, lie_smul], } /-- An `L`-equivariant map of Lie modules `M → N` is `L'`-equivariant for any Lie subalgebra `L' ⊆ L`. -/ def _root_.lie_module_hom.restrict_lie (f : M →ₗ⁅R,L⁆ N) (L' : lie_subalgebra R L) : M →ₗ⁅R,L'⁆ N := { map_lie' := λ x m, f.map_lie ↑x m, .. (f : M →ₗ[R] N)} @[simp] lemma _root_.lie_module_hom.coe_restrict_lie (f : M →ₗ⁅R,L⁆ N) : ⇑(f.restrict_lie L') = f := rfl end lie_module /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie algebras. -/ def incl : L' →ₗ⁅R⁆ L := { map_lie' := λ x y, by { simp only [linear_map.to_fun_eq_coe, submodule.subtype_apply], refl, }, .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl : ⇑L'.incl = coe := rfl /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie modules. -/ def incl' : L' →ₗ⁅R,L'⁆ L := { map_lie' := λ x y, by simp only [coe_bracket_of_module, linear_map.to_fun_eq_coe, submodule.subtype_apply, coe_bracket], .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl' : ⇑L'.incl' = coe := rfl end lie_subalgebra variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂] variables (f : L →ₗ⁅R⁆ L₂) namespace lie_hom /-- The range of a morphism of Lie algebras is a Lie subalgebra. -/ def range : lie_subalgebra R L₂ := { lie_mem' := λ x y, show x ∈ f.to_linear_map.range → y ∈ f.to_linear_map.range → ⁅x, y⁆ ∈ f.to_linear_map.range, by { repeat { rw linear_map.mem_range }, rintros ⟨x', hx⟩ ⟨y', hy⟩, refine ⟨⁅x', y'⁆, _⟩, rw [←hx, ←hy], change f ⁅x', y'⁆ = ⁅f x', f y'⁆, rw map_lie, }, ..(f : L →ₗ[R] L₂).range } @[simp] lemma range_coe : (f.range : set L₂) = set.range f := linear_map.range_coe ↑f @[simp] lemma mem_range (x : L₂) : x ∈ f.range ↔ ∃ (y : L), f y = x := linear_map.mem_range lemma mem_range_self (x : L) : f x ∈ f.range := linear_map.mem_range_self f x /-- We can restrict a morphism to a (surjective) map to its range. -/ def range_restrict : L →ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply subtype.ext, exact f.map_lie x y, }, ..(f : L →ₗ[R] L₂).range_restrict, } @[simp] lemma range_restrict_apply (x : L) : f.range_restrict x = ⟨f x, f.mem_range_self x⟩ := rfl lemma surjective_range_restrict : function.surjective (f.range_restrict) := begin rintros ⟨y, hy⟩, erw mem_range at hy, obtain ⟨x, rfl⟩ := hy, use x, simp only [subtype.mk_eq_mk, range_restrict_apply], end /-- A Lie algebra is equivalent to its range under an injective Lie algebra morphism. -/ noncomputable def equiv_range_of_injective (h : function.injective f) : L ≃ₗ⁅R⁆ f.range := lie_equiv.of_bijective f.range_restrict (λ x y hxy, begin simp only [subtype.mk_eq_mk, range_restrict_apply] at hxy, exact h hxy, end) f.surjective_range_restrict @[simp] lemma equiv_range_of_injective_apply (h : function.injective f) (x : L) : f.equiv_range_of_injective h x = ⟨f x, mem_range_self f x⟩ := rfl end lie_hom lemma submodule.exists_lie_subalgebra_coe_eq_iff (p : submodule R L) : (∃ (K : lie_subalgebra R L), ↑K = p) ↔ ∀ (x y : L), x ∈ p → y ∈ p → ⁅x, y⁆ ∈ p := begin split, { rintros ⟨K, rfl⟩ _ _, exact K.lie_mem', }, { intros h, use { lie_mem' := h, ..p }, exact lie_subalgebra.coe_to_submodule_mk p _, }, end namespace lie_subalgebra variables (K K' : lie_subalgebra R L) (K₂ : lie_subalgebra R L₂) @[simp] lemma incl_range : K.incl.range = K := by { rw ← coe_to_submodule_eq_iff, exact (K : submodule R L).range_subtype, } /-- The image of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the codomain. -/ def map : lie_subalgebra R L₂ := { lie_mem' := λ x y hx hy, by { erw submodule.mem_map at hx, rcases hx with ⟨x', hx', hx⟩, rw ←hx, erw submodule.mem_map at hy, rcases hy with ⟨y', hy', hy⟩, rw ←hy, erw submodule.mem_map, exact ⟨⁅x', y'⁆, K.lie_mem hx' hy', f.map_lie x' y'⟩, }, ..((K : submodule R L).map (f : L →ₗ[R] L₂)) } @[simp] lemma mem_map (x : L₂) : x ∈ K.map f ↔ ∃ (y : L), y ∈ K ∧ f y = x := submodule.mem_map -- TODO Rename and state for homs instead of equivs. @[simp] lemma mem_map_submodule (e : L ≃ₗ⁅R⁆ L₂) (x : L₂) : x ∈ K.map (e : L →ₗ⁅R⁆ L₂) ↔ x ∈ (K : submodule R L).map (e : L →ₗ[R] L₂) := iff.rfl /-- The preimage of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the domain. -/ def comap : lie_subalgebra R L := { lie_mem' := λ x y hx hy, by { suffices : ⁅f x, f y⁆ ∈ K₂, by { simp [this], }, exact K₂.lie_mem hx hy, }, ..((K₂ : submodule R L₂).comap (f : L →ₗ[R] L₂)), } section lattice_structure open set instance : partial_order (lie_subalgebra R L) := { le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq. ..partial_order.lift (coe : lie_subalgebra R L → set L) coe_injective } lemma le_def : K ≤ K' ↔ (K : set L) ⊆ K' := iff.rfl @[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (K : submodule R L) ≤ K' ↔ K ≤ K' := iff.rfl instance : has_bot (lie_subalgebra R L) := ⟨0⟩ @[simp] lemma bot_coe : ((⊥ : lie_subalgebra R L) : set L) = {0} := rfl @[simp] lemma bot_coe_submodule : ((⊥ : lie_subalgebra R L) : submodule R L) = ⊥ := rfl @[simp] lemma mem_bot (x : L) : x ∈ (⊥ : lie_subalgebra R L) ↔ x = 0 := mem_singleton_iff instance : has_top (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, mem_univ ⁅x, y⁆, ..(⊤ : submodule R L) }⟩ @[simp] lemma top_coe : ((⊤ : lie_subalgebra R L) : set L) = univ := rfl @[simp] lemma top_coe_submodule : ((⊤ : lie_subalgebra R L) : submodule R L) = ⊤ := rfl @[simp] lemma mem_top (x : L) : x ∈ (⊤ : lie_subalgebra R L) := mem_univ x lemma _root_.lie_hom.range_eq_map : f.range = map f ⊤ := by { ext, simp } instance : has_inf (lie_subalgebra R L) := ⟨λ K K', { lie_mem' := λ x y hx hy, mem_inter (K.lie_mem hx.1 hy.1) (K'.lie_mem hx.2 hy.2), ..(K ⊓ K' : submodule R L) }⟩ instance : has_Inf (lie_subalgebra R L) := ⟨λ S, { lie_mem' := λ x y hx hy, by { simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib] at *, intros K hK, exact K.lie_mem (hx K hK) (hy K hK), }, ..Inf {(s : submodule R L) | s ∈ S} }⟩ @[simp] theorem inf_coe : (↑(K ⊓ K') : set L) = K ∩ K' := rfl @[simp] lemma Inf_coe_to_submodule (S : set (lie_subalgebra R L)) : (↑(Inf S) : submodule R L) = Inf {(s : submodule R L) | s ∈ S} := rfl @[simp] lemma Inf_coe (S : set (lie_subalgebra R L)) : (↑(Inf S) : set L) = ⋂ s ∈ S, (s : set L) := begin rw [← coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe], ext x, simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib], end lemma Inf_glb (S : set (lie_subalgebra R L)) : is_glb S (Inf S) := begin have h : ∀ (K K' : lie_subalgebra R L), (K : set L) ≤ K' ↔ K ≤ K', { intros, exact iff.rfl, }, apply is_glb.of_image h, simp only [Inf_coe], exact is_glb_binfi end /-- The set of Lie subalgebras of a Lie algebra form a complete lattice. We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions than we would otherwise obtain from `complete_lattice_of_Inf`. -/ instance : complete_lattice (lie_subalgebra R L) := { bot := ⊥, bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', }, top := ⊤, le_top := λ _ _ _, trivial, inf := (⊓), le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩, inf_le_left := λ _ _ _, and.left, inf_le_right := λ _ _ _, and.right, ..complete_lattice_of_Inf _ Inf_glb } instance : add_comm_monoid (lie_subalgebra R L) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm, } instance : canonically_ordered_add_monoid (lie_subalgebra R L) := { add_le_add_left := λ a b, sup_le_sup_left, exists_add_of_le := λ a b h, ⟨b, (sup_eq_right.2 h).symm⟩, le_self_add := λ a b, le_sup_left, ..lie_subalgebra.add_comm_monoid, ..lie_subalgebra.complete_lattice } @[simp] lemma add_eq_sup : K + K' = K ⊔ K' := rfl @[norm_cast, simp] lemma inf_coe_to_submodule : (↑(K ⊓ K') : submodule R L) = (K : submodule R L) ⊓ (K' : submodule R L) := rfl @[simp] lemma mem_inf (x : L) : x ∈ K ⊓ K' ↔ x ∈ K ∧ x ∈ K' := by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule, submodule.mem_inf] lemma eq_bot_iff : K = ⊥ ↔ ∀ (x : L), x ∈ K → x = 0 := by { rw eq_bot_iff, exact iff.rfl, } instance subsingleton_of_bot : subsingleton (lie_subalgebra R ↥(⊥ : lie_subalgebra R L)) := begin apply subsingleton_of_bot_eq_top, ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw lie_subalgebra.mem_bot at hx, subst hx, simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, mem_bot], end lemma subsingleton_bot : subsingleton ↥(⊥ : lie_subalgebra R L) := show subsingleton ((⊥ : lie_subalgebra R L) : set L), by simp variables (R L) lemma well_founded_of_noetherian [is_noetherian R L] : well_founded ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) := let f : ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) →r ((>) : submodule R L → submodule R L → Prop) := { to_fun := coe, map_rel' := λ N N' h, h, } in rel_hom_class.well_founded f (is_noetherian_iff_well_founded.mp infer_instance) variables {R L K K' f} section nested_subalgebras variables (h : K ≤ K') /-- Given two nested Lie subalgebras `K ⊆ K'`, the inclusion `K ↪ K'` is a morphism of Lie algebras. -/ def hom_of_le : K →ₗ⁅R⁆ K' := { map_lie' := λ x y, rfl, ..submodule.of_le h } @[simp] lemma coe_hom_of_le (x : K) : (hom_of_le h x : L) = x := rfl lemma hom_of_le_apply (x : K) : hom_of_le h x = ⟨x.1, h x.2⟩ := rfl lemma hom_of_le_injective : function.injective (hom_of_le h) := λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe, subtype.val_eq_coe] /-- Given two nested Lie subalgebras `K ⊆ K'`, we can view `K` as a Lie subalgebra of `K'`, regarded as Lie algebra in its own right. -/ def of_le : lie_subalgebra R K' := (hom_of_le h).range @[simp] lemma mem_of_le (x : K') : x ∈ of_le h ↔ (x : L) ∈ K := begin simp only [of_le, hom_of_le_apply, lie_hom.mem_range], split, { rintros ⟨y, rfl⟩, exact y.property, }, { intros h, use ⟨(x : L), h⟩, simp, }, end lemma of_le_eq_comap_incl : of_le h = K.comap K'.incl := by { ext, rw mem_of_le, refl, } @[simp] lemma coe_of_le : (of_le h : submodule R K') = (submodule.of_le h).range := rfl /-- Given nested Lie subalgebras `K ⊆ K'`, there is a natural equivalence from `K` to its image in `K'`. -/ noncomputable def equiv_of_le : K ≃ₗ⁅R⁆ of_le h := (hom_of_le h).equiv_range_of_injective (hom_of_le_injective h) @[simp] lemma equiv_of_le_apply (x : K) : equiv_of_le h x = ⟨hom_of_le h x, (hom_of_le h).mem_range_self x⟩ := rfl end nested_subalgebras lemma map_le_iff_le_comap {K : lie_subalgebra R L} {K' : lie_subalgebra R L₂} : map f K ≤ K' ↔ K ≤ comap f K' := set.image_subset_iff lemma gc_map_comap : galois_connection (map f) (comap f) := λ K K', map_le_iff_le_comap end lattice_structure section lie_span variables (R L) (s : set L) /-- The Lie subalgebra of a Lie algebra `L` generated by a subset `s ⊆ L`. -/ def lie_span : lie_subalgebra R L := Inf {N | s ⊆ N} variables {R L s} lemma mem_lie_span {x : L} : x ∈ lie_span R L s ↔ ∀ K : lie_subalgebra R L, s ⊆ K → x ∈ K := by { change x ∈ (lie_span R L s : set L) ↔ _, erw Inf_coe, exact set.mem_Inter₂, } lemma subset_lie_span : s ⊆ lie_span R L s := by { intros m hm, erw mem_lie_span, intros K hK, exact hK hm, } lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s := by { rw submodule.span_le, apply subset_lie_span, } lemma lie_span_le {K} : lie_span R L s ≤ K ↔ s ⊆ K := begin split, { exact set.subset.trans subset_lie_span, }, { intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, }, end lemma lie_span_mono {t : set L} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t := by { rw lie_span_le, exact set.subset.trans h subset_lie_span, } lemma lie_span_eq : lie_span R L (K : set L) = K := le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span lemma coe_lie_span_submodule_eq_iff {p : submodule R L} : (lie_span R L (p : set L) : submodule R L) = p ↔ ∃ (K : lie_subalgebra R L), ↑K = p := begin rw p.exists_lie_subalgebra_coe_eq_iff, split; intros h, { intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), }, { rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], }, end variables (R L) /-- `lie_span` forms a Galois insertion with the coercion from `lie_subalgebra` to `set`. -/ protected def gi : galois_insertion (lie_span R L : set L → lie_subalgebra R L) coe := { choice := λ s _, lie_span R L s, gc := λ s t, lie_span_le, le_l_u := λ s, subset_lie_span, choice_eq := λ s h, rfl } @[simp] lemma span_empty : lie_span R L (∅ : set L) = ⊥ := (lie_subalgebra.gi R L).gc.l_bot @[simp] lemma span_univ : lie_span R L (set.univ : set L) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span variables {L} lemma span_union (s t : set L) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t := (lie_subalgebra.gi R L).gc.l_sup lemma span_Union {ι} (s : ι → set L) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) := (lie_subalgebra.gi R L).gc.l_supr end lie_span end lie_subalgebra end lie_subalgebra namespace lie_equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] /-- An injective Lie algebra morphism is an equivalence onto its range. -/ noncomputable def of_injective (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) : L₁ ≃ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply set_coe.ext, simpa }, .. linear_equiv.of_injective (f : L₁ →ₗ[R] L₂) $ by rwa [lie_hom.coe_to_linear_map] } @[simp] lemma of_injective_apply (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) (x : L₁) : ↑(of_injective f h x) = f x := rfl variables (L₁' L₁'' : lie_subalgebra R L₁) (L₂' : lie_subalgebra R L₂) /-- Lie subalgebras that are equal as sets are equivalent as Lie algebras. -/ def of_eq (h : (L₁' : set L₁) = L₁'') : L₁' ≃ₗ⁅R⁆ L₁'' := { map_lie' := λ x y, by { apply set_coe.ext, simp, }, ..(linear_equiv.of_eq ↑L₁' ↑L₁'' (by {ext x, change x ∈ (L₁' : set L₁) ↔ x ∈ (L₁'' : set L₁), rw h, } )) } @[simp] lemma of_eq_apply (L L' : lie_subalgebra R L₁) (h : (L : set L₁) = L') (x : L) : (↑(of_eq L L' h x) : L₁) = x := rfl variables (e : L₁ ≃ₗ⁅R⁆ L₂) /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def lie_subalgebra_map : L₁'' ≃ₗ⁅R⁆ (L₁''.map e : lie_subalgebra R L₂) := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, } ..(linear_equiv.submodule_map (e : L₁ ≃ₗ[R] L₂) ↑L₁'') } @[simp] lemma lie_subalgebra_map_apply (x : L₁'') : ↑(e.lie_subalgebra_map _ x) = e x := rfl /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebras (h : L₁'.map ↑e = L₂') : L₁' ≃ₗ⁅R⁆ L₂' := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, }, ..(linear_equiv.of_submodules (e : L₁ ≃ₗ[R] L₂) ↑L₁' ↑L₂' (by { rw ←h, refl, })) } @[simp] lemma of_subalgebras_apply (h : L₁'.map ↑e = L₂') (x : L₁') : ↑(e.of_subalgebras _ _ h x) = e x := rfl @[simp] lemma of_subalgebras_symm_apply (h : L₁'.map ↑e = L₂') (x : L₂') : ↑((e.of_subalgebras _ _ h).symm x) = e.symm x := rfl end lie_equiv
3303db4335e7a602177cb23ebc2c8b1b06a7532b
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/perm/cycle_type.lean
cfbe9e16a14bc6fd1389d1b937b97d0dc5f58aca
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
27,247
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.gcd_monoid.multiset import combinatorics.partition import group_theory.perm.cycles import ring_theory.int.basic import tactic.linarith /-! # Cycle Types In this file we define the cycle type of a permutation. ## Main definitions - `σ.cycle_type` where `σ` is a permutation of a `fintype` - `σ.partition` where `σ` is a permutation of a `fintype` ## Main results - `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card` - `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ` - `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same cycle type. * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of a finite group `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. -/ namespace equiv.perm open equiv list multiset variables {α : Type*} [fintype α] section cycle_type variables [decidable_eq α] /-- The cycle type of a permutation -/ def cycle_type (σ : perm α) : multiset ℕ := σ.cycle_factors_finset.1.map (finset.card ∘ support) lemma cycle_type_def (σ : perm α) : σ.cycle_type = σ.cycle_factors_finset.1.map (finset.card ∘ support) := rfl lemma cycle_type_eq' {σ : perm α} (s : finset (perm α)) (h1 : ∀ f : perm α, f ∈ s → f.is_cycle) (h2 : ∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b) (h0 : s.noncomm_prod id (λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a) (set.pairwise.mono' (λ _ _, disjoint.commute) h2 ha hb)) = σ) : σ.cycle_type = s.1.map (finset.card ∘ support) := begin rw cycle_type_def, congr, rw cycle_factors_finset_eq_finset, exact ⟨h1, h2, h0⟩ end lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ) (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) : σ.cycle_type = l.map (finset.card ∘ support) := begin have hl : l.nodup := nodup_of_pairwise_disjoint_cycles h1 h2, rw cycle_type_eq' l.to_finset, { simp [list.dedup_eq_self.mpr hl] }, { simpa using h1 }, { simpa [hl] using h0 }, { simpa [list.dedup_eq_self.mpr hl] using h2.forall disjoint.symmetric } end lemma cycle_type_one : (1 : perm α).cycle_type = 0 := cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 := by simp [cycle_type_def, cycle_factors_finset_eq_empty_iff] lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 := by rw [card_eq_zero, cycle_type_eq_zero] lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n := begin simp only [cycle_type_def, ←finset.mem_def, function.comp_app, multiset.mem_map, mem_cycle_factors_finset_iff] at h, obtain ⟨_, ⟨hc, -⟩, rfl⟩ := h, exact hc.two_le_card_support end lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n := two_le_of_mem_cycle_type h lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] := cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ) (pairwise_singleton disjoint σ) lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle := begin rw card_eq_one, simp_rw [cycle_type_def, multiset.map_eq_singleton, ←finset.singleton_val, finset.val_inj, cycle_factors_finset_eq_singleton_iff], split, { rintro ⟨_, _, ⟨h, -⟩, -⟩, exact h }, { intro h, use [σ.support.card, σ], simp [h] } end lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) : (σ * τ).cycle_type = σ.cycle_type + τ.cycle_type := begin rw [cycle_type_def, cycle_type_def, cycle_type_def, h.cycle_factors_finset_mul_eq_union, ←multiset.map_add, finset.union_val, multiset.add_eq_union_iff_disjoint.mpr _], rw [←finset.disjoint_val], exact h.disjoint_cycle_factors_finset end lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type := cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl (λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv]) (λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm, disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm) (λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)]) lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type := begin revert τ, apply cycle_induction_on _ σ, { intro, simp }, { intros σ hσ τ, rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] }, { intros σ τ hd hc hσ hτ π, rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ], intro a, apply (hd (π⁻¹ a)).imp _ _; { intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } } end lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card := cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ (by rw [cycle_type_one, sum_zero, support_one, finset.card_empty]) (λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul]) lemma sign_of_cycle_type' (σ : perm α) : sign σ = (σ.cycle_type.map (λ n, -(-1 : ℤˣ) ^ n)).prod := cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : ℤˣ) ^ n)).prod) σ (by rw [sign_one, cycle_type_one, multiset.map_zero, prod_zero]) (λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod, list.map_singleton, list.prod_singleton]) (λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, multiset.map_add, prod_add]) lemma sign_of_cycle_type (f : perm α) : sign f = (-1 : ℤˣ)^(f.cycle_type.sum + f.cycle_type.card) := cycle_induction_on (λ f : perm α, sign f = (-1 : ℤˣ)^(f.cycle_type.sum + f.cycle_type.card)) f ( -- base_one by rw [equiv.perm.cycle_type_one, sign_one, multiset.sum_zero, multiset.card_zero, pow_zero] ) ( -- base_cycles λ f hf, by rw [equiv.perm.is_cycle.cycle_type hf, hf.sign, coe_sum, list.sum_cons, sum_nil, add_zero, coe_card, length_singleton, pow_add, pow_one, mul_comm, neg_mul, one_mul] ) ( -- induction_disjoint λ f g hfg hf Pf Pg, by rw [equiv.perm.disjoint.cycle_type hfg, multiset.sum_add, multiset.card_add,← add_assoc, add_comm f.cycle_type.sum g.cycle_type.sum, add_assoc g.cycle_type.sum _ _, add_comm g.cycle_type.sum _, add_assoc, pow_add, ← Pf, ← Pg, equiv.perm.sign_mul]) lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ := cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ (by rw [cycle_type_one, lcm_zero, order_of_one]) (λ σ hσ, by rw [hσ.cycle_type, ←singleton_coe, ←singleton_eq_cons, lcm_singleton, order_of_is_cycle hσ, normalize_eq]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, lcm_eq_nat_lcm, hστ.order_of, hσ, hτ]) lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ := begin rw ← lcm_cycle_type, exact dvd_lcm h, end lemma order_of_cycle_of_dvd_order_of (f : perm α) (x : α) : order_of (cycle_of f x) ∣ order_of f := begin by_cases hx : f x = x, { rw ←cycle_of_eq_one_iff at hx, simp [hx] }, { refine dvd_of_mem_cycle_type _, rw [cycle_type, multiset.mem_map], refine ⟨f.cycle_of x, _, _⟩, { rwa [←finset.mem_def, cycle_of_mem_cycle_factors_finset_iff, mem_support] }, { simp [order_of_is_cycle (is_cycle_cycle_of _ hx)] } } end lemma two_dvd_card_support {σ : perm α} (hσ : σ ^ 2 = 1) : 2 ∣ σ.support.card := (congr_arg (has_dvd.dvd 2) σ.sum_cycle_type).mp (multiset.dvd_sum (λ n hn, by rw le_antisymm (nat.le_of_dvd zero_lt_two $ (dvd_of_mem_cycle_type hn).trans $ order_of_dvd_of_pow_eq_one hσ) (two_le_of_mem_cycle_type hn))) lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) : ∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) := begin rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp (hσ.eq_one_or_self_of_dvd n (dvd_of_mem_cycle_type hn)) (one_lt_of_mem_cycle_type hn).ne'), use σ.cycle_type.card - 1, rw tsub_add_cancel_of_le, rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero], intro H, rw [H, order_of_one] at hσ, exact hσ.ne_one rfl, end lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime) (h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle := begin obtain ⟨n, hn⟩ := cycle_type_prime_order h1, rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right (order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, nat.le_zero_iff] at h2, rw [←card_cycle_type_eq_one, hn, card_repeat, h2], end lemma cycle_type_le_of_mem_cycle_factors_finset {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : f.cycle_type ≤ g.cycle_type := begin rw mem_cycle_factors_finset_iff at hf, rw [cycle_type_def, cycle_type_def, hf.left.cycle_factors_finset_eq_singleton], refine map_le_map _, simpa [←finset.mem_def, mem_cycle_factors_finset_iff] using hf end lemma cycle_type_mul_mem_cycle_factors_finset_eq_sub {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : (g * f⁻¹).cycle_type = g.cycle_type - f.cycle_type := begin suffices : (g * f⁻¹).cycle_type + f.cycle_type = g.cycle_type - f.cycle_type + f.cycle_type, { rw tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf) at this, simp [←this] }, simp [←(disjoint_mul_inv_of_mem_cycle_factors_finset hf).cycle_type, tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf)] end theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ := begin revert τ, apply cycle_induction_on _ σ, { intros τ h, rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h, rw h }, { intros σ hσ τ hστ, have hτ := card_cycle_type_eq_one.2 hσ, rw [hστ, card_cycle_type_eq_one] at hτ, apply hσ.is_conj hτ, rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ, simp only [and_true, eq_self_iff_true] at hστ, exact hστ }, { intros σ τ hστ hσ h1 h2 π hπ, rw [hστ.cycle_type] at hπ, { have h : σ.support.card ∈ map (finset.card ∘ perm.support) π.cycle_factors_finset.val, { simp [←cycle_type_def, ←hπ, hσ.cycle_type] }, obtain ⟨σ', hσ'l, hσ'⟩ := multiset.mem_map.mp h, have key : is_conj (σ' * (π * σ'⁻¹)) π, { rw is_conj_iff, use σ'⁻¹, simp [mul_assoc] }, refine is_conj.trans _ key, have hs : σ.cycle_type = σ'.cycle_type, { rw [←finset.mem_def, mem_cycle_factors_finset_iff] at hσ'l, rw [hσ.cycle_type, ←hσ', hσ'l.left.cycle_type] }, refine hστ.is_conj_mul (h1 hs) (h2 _) _, { rw [cycle_type_mul_mem_cycle_factors_finset_eq_sub, ←hπ, add_comm, hs, add_tsub_cancel_right], rwa finset.mem_def }, { exact (disjoint_mul_inv_of_mem_cycle_factors_finset hσ'l).symm } } } end theorem is_conj_iff_cycle_type_eq {σ τ : perm α} : is_conj σ τ ↔ σ.cycle_type = τ.cycle_type := ⟨λ h, begin obtain ⟨π, rfl⟩ := is_conj_iff.1 h, rw cycle_type_conj, end, is_conj_of_cycle_type_eq⟩ @[simp] lemma cycle_type_extend_domain {β : Type*} [fintype β] [decidable_eq β] {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} : cycle_type (g.extend_domain f) = cycle_type g := begin apply cycle_induction_on _ g, { rw [extend_domain_one, cycle_type_one, cycle_type_one] }, { intros σ hσ, rw [(hσ.extend_domain f).cycle_type, hσ.cycle_type, card_support_extend_domain] }, { intros σ τ hd hc hσ hτ, rw [hd.cycle_type, ← extend_domain_mul, (hd.extend_domain f).cycle_type, hσ, hτ] } end lemma mem_cycle_type_iff {n : ℕ} {σ : perm α} : n ∈ cycle_type σ ↔ ∃ c τ : perm α, σ = c * τ ∧ disjoint c τ ∧ is_cycle c ∧ c.support.card = n := begin split, { intro h, obtain ⟨l, rfl, hlc, hld⟩ := trunc_cycle_factors σ, rw cycle_type_eq _ rfl hlc hld at h, obtain ⟨c, cl, rfl⟩ := list.exists_of_mem_map h, rw (list.perm_cons_erase cl).pairwise_iff (λ _ _ hd, _) at hld, swap, { exact hd.symm }, refine ⟨c, (l.erase c).prod, _, _, hlc _ cl, rfl⟩, { rw [← list.prod_cons, (list.perm_cons_erase cl).symm.prod_eq' (hld.imp (λ _ _, disjoint.commute))] }, { exact disjoint_prod_right _ (λ g, list.rel_of_pairwise_cons hld) } }, { rintros ⟨c, t, rfl, hd, hc, rfl⟩, simp [hd.cycle_type, hc.cycle_type] } end lemma le_card_support_of_mem_cycle_type {n : ℕ} {σ : perm α} (h : n ∈ cycle_type σ) : n ≤ σ.support.card := (le_sum_of_mem h).trans (le_of_eq σ.sum_cycle_type) lemma cycle_type_of_card_le_mem_cycle_type_add_two {n : ℕ} {g : perm α} (hn2 : fintype.card α < n + 2) (hng : n ∈ g.cycle_type) : g.cycle_type = {n} := begin obtain ⟨c, g', rfl, hd, hc, rfl⟩ := mem_cycle_type_iff.1 hng, by_cases g'1 : g' = 1, { rw [hd.cycle_type, hc.cycle_type, multiset.singleton_eq_cons, multiset.singleton_coe, g'1, cycle_type_one, add_zero] }, contrapose! hn2, apply le_trans _ (c * g').support.card_le_univ, rw [hd.card_support_mul], exact add_le_add_left (two_le_card_support_of_ne_one g'1) _, end end cycle_type lemma card_compl_support_modeq [decidable_eq α] {p n : ℕ} [hp : fact p.prime] {σ : perm α} (hσ : σ ^ p ^ n = 1) : σ.supportᶜ.card ≡ fintype.card α [MOD p] := begin rw [nat.modeq_iff_dvd' σ.supportᶜ.card_le_univ, ←finset.card_compl, compl_compl], refine (congr_arg _ σ.sum_cycle_type).mp (multiset.dvd_sum (λ k hk, _)), obtain ⟨m, -, hm⟩ := (nat.dvd_prime_pow hp.out).mp (order_of_dvd_of_pow_eq_one hσ), obtain ⟨l, -, rfl⟩ := (nat.dvd_prime_pow hp.out).mp ((congr_arg _ hm).mp (dvd_of_mem_cycle_type hk)), exact dvd_pow_self _ (λ h, (one_lt_of_mem_cycle_type hk).ne $ by rw [h, pow_zero]), end lemma exists_fixed_point_of_prime {p n : ℕ} [hp : fact p.prime] (hα : ¬ p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) : ∃ a : α, σ a = a := begin classical, contrapose! hα, simp_rw ← mem_support at hα, exact nat.modeq_zero_iff_dvd.mp ((congr_arg _ (finset.card_eq_zero.mpr (compl_eq_bot.mpr (finset.eq_univ_iff_forall.mpr hα)))).mp (card_compl_support_modeq hσ).symm), end lemma exists_fixed_point_of_prime' {p n : ℕ} [hp : fact p.prime] (hα : p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) {a : α} (ha : σ a = a) : ∃ b : α, σ b = b ∧ b ≠ a := begin classical, have h : ∀ b : α, b ∈ σ.supportᶜ ↔ σ b = b := λ b, by rw [finset.mem_compl, mem_support, not_not], obtain ⟨b, hb1, hb2⟩ := finset.exists_ne_of_one_lt_card (lt_of_lt_of_le hp.out.one_lt (nat.le_of_dvd (finset.card_pos.mpr ⟨a, (h a).mpr ha⟩) (nat.modeq_zero_iff_dvd.mp ((card_compl_support_modeq hσ).trans (nat.modeq_zero_iff_dvd.mpr hα))))) a, exact ⟨b, (h b).mp hb1, hb2⟩, end lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime) (h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle := begin classical, exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2), end lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime) (h2 : order_of σ = fintype.card α) : σ.is_cycle := is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1) begin classical, rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)], exact one_lt_two, end section cauchy variables (G : Type*) [group G] (n : ℕ) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one : set (vector G n) := {v | v.to_list.prod = 1} namespace vectors_prod_eq_one lemma mem_iff {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma zero_eq : vectors_prod_eq_one G 0 = {vector.nil} := set.eq_singleton_iff_unique_mem.mpr ⟨eq.refl (1 : G), λ v hv, v.eq_nil⟩ lemma one_eq : vectors_prod_eq_one G 1 = {vector.nil.cons 1} := begin simp_rw [set.eq_singleton_iff_unique_mem, mem_iff, vector.to_list_singleton, list.prod_singleton, vector.head_cons], exact ⟨rfl, λ v hv, v.cons_head_tail.symm.trans (congr_arg2 vector.cons hv v.tail.eq_nil)⟩, end instance zero_unique : unique (vectors_prod_eq_one G 0) := by { rw zero_eq, exact set.unique_singleton vector.nil } instance one_unique : unique (vectors_prod_eq_one G 1) := by { rw one_eq, exact set.unique_singleton (vector.nil.cons 1) } /-- Given a vector `v` of length `n`, make a vector of length `n + 1` whose product is `1`, by appending the inverse of the product of `v`. -/ @[simps] def vector_equiv : vector G n ≃ vectors_prod_eq_one G (n + 1) := { to_fun := λ v, ⟨v.to_list.prod⁻¹ ::ᵥ v, by rw [mem_iff, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩, inv_fun := λ v, v.1.tail, left_inv := λ v, v.tail_cons v.to_list.prod⁻¹, right_inv := λ v, subtype.ext ((congr_arg2 vector.cons (eq_inv_of_mul_eq_one_left (by { rw [←list.prod_cons, ←vector.to_list_cons, v.1.cons_head_tail], exact v.2 })).symm rfl).trans v.1.cons_head_tail) } /-- Given a vector `v` of length `n` whose product is 1, make a vector of length `n - 1`, by deleting the last entry of `v`. -/ def equiv_vector : vectors_prod_eq_one G n ≃ vector G (n - 1) := ((vector_equiv G (n - 1)).trans (if hn : n = 0 then (show vectors_prod_eq_one G (n - 1 + 1) ≃ vectors_prod_eq_one G n, by { rw hn, exact equiv_of_unique_of_unique }) else by rw tsub_add_cancel_of_le (nat.pos_of_ne_zero hn).nat_succ_le)).symm instance [fintype G] : fintype (vectors_prod_eq_one G n) := fintype.of_equiv (vector G (n - 1)) (equiv_vector G n).symm lemma card [fintype G] : fintype.card (vectors_prod_eq_one G n) = fintype.card G ^ (n - 1) := (fintype.card_congr (equiv_vector G n)).trans (card_vector (n - 1)) variables {G n} {g : G} (v : vectors_prod_eq_one G n) (j k : ℕ) /-- Rotate a vector whose product is 1. -/ def rotate : vectors_prod_eq_one G n := ⟨⟨_, (v.1.1.length_rotate k).trans v.1.2⟩, list.prod_rotate_eq_one_of_prod_eq_one v.2 k⟩ lemma rotate_zero : rotate v 0 = v := subtype.ext (subtype.ext v.1.1.rotate_zero) lemma rotate_rotate : rotate (rotate v j) k = rotate v (j + k) := subtype.ext (subtype.ext (v.1.1.rotate_rotate j k)) lemma rotate_length : rotate v n = v := subtype.ext (subtype.ext ((congr_arg _ v.1.2.symm).trans v.1.1.rotate_length)) end vectors_prod_eq_one lemma exists_prime_order_of_dvd_card {G : Type*} [group G] [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ fintype.card G) : ∃ x : G, order_of x = p := begin have hp' : p - 1 ≠ 0 := mt tsub_eq_zero_iff_le.mp (not_le_of_lt hp.out.one_lt), have Scard := calc p ∣ fintype.card G ^ (p - 1) : hdvd.trans (dvd_pow (dvd_refl _) hp') ... = fintype.card (vectors_prod_eq_one G p) : (vectors_prod_eq_one.card G p).symm, let f : ℕ → vectors_prod_eq_one G p → vectors_prod_eq_one G p := λ k v, vectors_prod_eq_one.rotate v k, have hf1 : ∀ v, f 0 v = v := vectors_prod_eq_one.rotate_zero, have hf2 : ∀ j k v, f k (f j v) = f (j + k) v := λ j k v, vectors_prod_eq_one.rotate_rotate v j k, have hf3 : ∀ v, f p v = v := vectors_prod_eq_one.rotate_length, let σ := equiv.mk (f 1) (f (p - 1)) (λ s, by rw [hf2, add_tsub_cancel_of_le hp.out.one_lt.le, hf3]) (λ s, by rw [hf2, tsub_add_cancel_of_le hp.out.one_lt.le, hf3]), have hσ : ∀ k v, (σ ^ k) v = f k v := λ k v, nat.rec (hf1 v).symm (λ k hk, eq.trans (by exact congr_arg σ hk) (hf2 k 1 v)) k, replace hσ : σ ^ (p ^ 1) = 1 := perm.ext (λ v, by rw [pow_one, hσ, hf3, one_apply]), let v₀ : vectors_prod_eq_one G p := ⟨vector.repeat 1 p, (list.prod_repeat 1 p).trans (one_pow p)⟩, have hv₀ : σ v₀ = v₀ := subtype.ext (subtype.ext (list.rotate_repeat (1 : G) p 1)), obtain ⟨v, hv1, hv2⟩ := exists_fixed_point_of_prime' Scard hσ hv₀, refine exists_imp_exists (λ g hg, order_of_eq_prime _ (λ hg', hv2 _)) (list.rotate_one_eq_self_iff_eq_repeat.mp (subtype.ext_iff.mp (subtype.ext_iff.mp hv1))), { rw [←list.prod_repeat, ←v.1.2, ←hg, (show v.val.val.prod = 1, from v.2)] }, { rw [subtype.ext_iff_val, subtype.ext_iff_val, hg, hg', v.1.2], refl }, end end cauchy lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)} [d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime) (h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) : H = ⊤ := begin haveI : fact (fintype.card α).prime := ⟨h0⟩, obtain ⟨σ, hσ⟩ := exists_prime_order_of_dvd_card (fintype.card α) h1, have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ, have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1, have hσ3 : (σ : perm α).support = ⊤ := finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1), have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3, rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff], exact ⟨subtype.mem σ, h2⟩, end section partition variables [decidable_eq α] /-- The partition corresponding to a permutation -/ def partition (σ : perm α) : (fintype.card α).partition := { parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card), parts_pos := λ n hn, begin cases mem_add.mp hn with hn hn, { exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) }, { exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) }, end, parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_one, add_tsub_cancel_of_le σ.support.card_le_univ] } lemma parts_partition {σ : perm α} : σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl lemma filter_parts_partition_eq_cycle_type {σ : perm α} : (partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type := begin rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type), multiset.filter_eq_nil.2 (λ a h, _), add_zero], rw multiset.eq_of_mem_repeat h, dec_trivial end lemma partition_eq_of_is_conj {σ τ : perm α} : is_conj σ τ ↔ σ.partition = τ.partition := begin rw [is_conj_iff_cycle_type_eq], refine ⟨λ h, _, λ h, _⟩, { rw [nat.partition.ext_iff, parts_partition, parts_partition, ← sum_cycle_type, ← sum_cycle_type, h] }, { rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] } end end partition /-! ### 3-cycles -/ /-- A three-cycle is a cycle of length 3. -/ def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3} namespace is_three_cycle variables [decidable_eq α] {σ : perm α} lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 := by rw [←sum_cycle_type, h.cycle_type, multiset.sum_singleton] lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle := begin refine ⟨λ h, _, is_three_cycle.card_support⟩, by_cases h0 : σ.cycle_type = 0, { rw [←sum_cycle_type, h0, sum_zero] at h, exact (ne_of_lt zero_lt_three h).elim }, obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0, by_cases h1 : σ.cycle_type.erase n = 0, { rw [←sum_cycle_type, ←cons_erase hn, h1, ←singleton_eq_cons, multiset.sum_singleton] at h, rw [is_three_cycle, ←cons_erase hn, h1, h, singleton_eq_cons] }, obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1, rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h, linarith [two_le_of_mem_cycle_type hn, two_le_of_mem_cycle_type (mem_of_mem_erase hm)], end lemma is_cycle (h : is_three_cycle σ) : is_cycle σ := by rw [←card_cycle_type_eq_one, h.cycle_type, card_singleton] lemma sign (h : is_three_cycle σ) : sign σ = 1 := begin rw [equiv.perm.sign_of_cycle_type, h.cycle_type], refl, end lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) := by rwa [is_three_cycle, cycle_type_inv] @[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f := ⟨by { rw ← inv_inv f, apply inv }, inv⟩ lemma order_of {g : perm α} (ht : is_three_cycle g) : order_of g = 3 := by rw [←lcm_cycle_type, ht.cycle_type, multiset.lcm_singleton, normalize_eq] lemma is_three_cycle_sq {g : perm α} (ht : is_three_cycle g) : is_three_cycle (g * g) := begin rw [←pow_two, ←card_support_eq_three_iff, support_pow_coprime, ht.card_support], rw [ht.order_of, nat.coprime_iff_gcd_eq_one], norm_num, end end is_three_cycle section variable [decidable_eq α] lemma is_three_cycle_swap_mul_swap_same {a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) : is_three_cycle (swap a b * swap a c) := begin suffices h : support (swap a b * swap a c) = {a, b, c}, { rw [←card_support_eq_three_iff, h], simp [ab, ac, bc] }, apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _), { simp [ab, ac, bc] }, { simp only [finset.mem_insert, finset.mem_singleton] at hx, rw mem_support, simp only [perm.coe_mul, function.comp_app, ne.def], obtain rfl | rfl | rfl := hx, { rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm], exact ac.symm }, { rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right], exact ab }, { rw [swap_apply_right, swap_apply_left], exact bc } } end open subgroup lemma swap_mul_swap_same_mem_closure_three_cycles {a b c : α} (ab : a ≠ b) (ac : a ≠ c) : (swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } := begin by_cases bc : b = c, { subst bc, simp [one_mem] }, exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc) end lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α} (hσ : is_swap σ) (hτ : is_swap τ) : σ * τ ∈ closure {σ : perm α | is_three_cycle σ } := begin obtain ⟨a, b, ab, rfl⟩ := hσ, obtain ⟨c, d, cd, rfl⟩ := hτ, by_cases ac : a = c, { subst ac, exact swap_mul_swap_same_mem_closure_three_cycles ab cd }, have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d), { simp [swap_comm c a, mul_assoc] }, rw h', exact mul_mem (swap_mul_swap_same_mem_closure_three_cycles ab ac) (swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd), end end end equiv.perm
0fa7f0d2bcfd45590db34e60d1c84b542a5bb01b
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/ctor_layout.lean
c7932bf41950112389dbdb07bfa95856e9d45d5d
[ "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
664
lean
import Lean.Compiler.IR new_frontend open Lean open Lean.IR unsafe def main : IO Unit := withImportModules [{module := `Lean.Compiler.IR.Basic}] 0 fun env => do let ctorLayout ← IO.ofExcept $ getCtorLayout env `Lean.IR.Expr.reuse; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); IO.println "---"; let ctorLayout ← IO.ofExcept $ getCtorLayout env `Lean.EnvironmentHeader.mk; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); IO.println "---"; let ctorLayout ← IO.ofExcept $ getCtorLayout env `Subtype.mk; ctorLayout.fieldInfo.forM $ fun finfo => IO.println (format finfo); pure () #eval main
cbfa1cc1b90d0020d13bf7e51bb9bcf0a925200d
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/mv_polynomial/supported.lean
41ce4104cbf5cbb8653c8bc3fe1a5f9573ad771a
[ "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
4,241
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.mv_polynomial.variables /-! # Polynomials supported by a set of variables > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definition and lemmas about `mv_polynomial.supported`. ## Main definitions * `mv_polynomial.supported` : Given a set `s : set σ`, `supported R s` is the subalgebra of `mv_polynomial σ R` consisting of polynomials whose set of variables is contained in `s`. This subalgebra is isomorphic to `mv_polynomial s R` ## Tags variables, polynomial, vars -/ universes u v w namespace mv_polynomial variables {σ τ : Type*} {R : Type u} {S : Type v} {r : R} {e : ℕ} {n m : σ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} variables (R) /-- The set of polynomials whose variables are contained in `s` as a `subalgebra` over `R`. -/ noncomputable def supported (s : set σ) : subalgebra R (mv_polynomial σ R) := algebra.adjoin R (X '' s) variables {σ R} open_locale classical open algebra lemma supported_eq_range_rename (s : set σ) : supported R s = (rename (coe : s → σ)).range := by rw [supported, set.image_eq_range, adjoin_range_eq_range_aeval, rename] /--The isomorphism between the subalgebra of polynomials supported by `s` and `mv_polynomial s R`-/ noncomputable def supported_equiv_mv_polynomial (s : set σ) : supported R s ≃ₐ[R] mv_polynomial s R := (subalgebra.equiv_of_eq _ _ (supported_eq_range_rename s)).trans (alg_equiv.of_injective (rename (coe : s → σ)) (rename_injective _ subtype.val_injective)).symm @[simp] lemma supported_equiv_mv_polynomial_symm_C (s : set σ) (x : R) : (supported_equiv_mv_polynomial s).symm (C x) = algebra_map R (supported R s) x := begin ext1, simp [supported_equiv_mv_polynomial, mv_polynomial.algebra_map_eq], end @[simp] lemma supported_equiv_mv_polynomial_symm_X (s : set σ) (i : s) : (↑((supported_equiv_mv_polynomial s).symm (X i : mv_polynomial s R)) : mv_polynomial σ R) = X i := by simp [supported_equiv_mv_polynomial] variables {s t : set σ} lemma mem_supported : p ∈ (supported R s) ↔ ↑p.vars ⊆ s := begin rw [supported_eq_range_rename, alg_hom.mem_range], split, { rintros ⟨p, rfl⟩, refine trans (finset.coe_subset.2 (vars_rename _ _)) _, simp }, { intros hs, exact exists_rename_eq_of_vars_subset_range p (coe : s → σ) subtype.val_injective (by simpa) } end lemma supported_eq_vars_subset : (supported R s : set (mv_polynomial σ R)) = {p | ↑p.vars ⊆ s} := set.ext $ λ _, mem_supported @[simp] lemma mem_supported_vars (p : mv_polynomial σ R) : p ∈ supported R (↑p.vars : set σ) := by rw [mem_supported] variable (s) lemma supported_eq_adjoin_X : supported R s = algebra.adjoin R (X '' s) := rfl @[simp] lemma supported_univ : supported R (set.univ : set σ) = ⊤ := by simp [algebra.eq_top_iff, mem_supported] @[simp] lemma supported_empty : supported R (∅ : set σ) = ⊥ := by simp [supported_eq_adjoin_X] variables {s} lemma supported_mono (st : s ⊆ t) : supported R s ≤ supported R t := algebra.adjoin_mono (set.image_subset _ st) @[simp] lemma X_mem_supported [nontrivial R] {i : σ} : (X i) ∈ supported R s ↔ i ∈ s := by simp [mem_supported] @[simp] lemma supported_le_supported_iff [nontrivial R] : supported R s ≤ supported R t ↔ s ⊆ t := begin split, { intros h i, simpa using @h (X i) }, { exact supported_mono } end lemma supported_strict_mono [nontrivial R] : strict_mono (supported R : set σ → subalgebra R (mv_polynomial σ R)) := strict_mono_of_le_iff_le (λ _ _, supported_le_supported_iff.symm) lemma exists_restrict_to_vars (R : Type*) [comm_ring R] {F : mv_polynomial σ ℤ} (hF : ↑F.vars ⊆ s) : ∃ f : (s → R) → R, ∀ x : σ → R, f (x ∘ coe : s → R) = aeval x F := begin classical, rw [← mem_supported, supported_eq_range_rename, alg_hom.mem_range] at hF, cases hF with F' hF', use λ z, aeval z F', intro x, simp only [←hF', aeval_rename], end end comm_semiring end mv_polynomial
2d30ab8a532e4d0c2b36e319ee9440b7a1a6d7a6
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/exponentiable.lean
891fdfa79ff50d4cb661b1768debf475754dd897
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
3,277
lean
import topology.compact_open import category_theory.adjunction import for_mathlib import .category universe u open continuous_map open category_theory category_theory.adjunction local notation f ` ∘ `:80 g:80 := g ≫ f namespace homotopy_theory.topological_spaces open Top local notation `Top` := Top.{u} /- A space A is exponentiable if the functor - × A admits a right adjoint functor [A, -]. This means that for all spaces X and Y, there is a natural isomorphism of sets C(Y × A, X) ≃ C(Y, [A, X]), where C denotes the set of continuous maps. By taking Y = * so that C(Y, -) is the underlying set functor, one sees that the only possible choice for the underlying set of [A, X] is the set C(A, X). We therefore define a space A to be exponentiable if C(A, X) can be equipped with a topology for each X which is (1) functorial with respect to continuous maps X → X' and (2) such that the evaluation and coevaluation maps (which form the counit and unit of the product-exponential adjunction on Set) are continuous. -/ variables (A X : Top) def ev : (A ⟶ X) × A → X := λ p, p.1 p.2 def coev : X → (A ⟶ Top.prod X A) := λ b, Top.mk_hom (λ a, (b, a)) (by continuity) variables {X} {X' : Top} def induced : (X ⟶ X') → (A ⟶ X) → (A ⟶ X') := λ f g, f ∘ g class exponentiable (A : Top) := (exponential : Π (X : Top), topological_space (A ⟶ X)) (functorial : ∀ (X X' : Top) (g : X ⟶ X'), continuous (induced A g)) (continuous_ev : ∀ (X : Top), continuous (ev A X)) (continuous_coev : ∀ (X : Top), continuous (coev A X)) instance exponentiable.topological_space (A X : Top) [exponentiable A] : topological_space (A ⟶ X) := exponentiable.exponential X -- Now we can define the exponential functor [A, -] and show that it -- is right adjoint to - × A. def exponential (A : Top) [exponentiable A] (X : Top) : Top := Top.mk_ob (A ⟶ X) def exponential_induced (A : Top) [exponentiable A] (X X' : Top) (g : X ⟶ X') : exponential A X ⟶ exponential A X' := Top.mk_hom (induced A g) (exponentiable.functorial X X' g) def exponential_functor (A : Top) [exponentiable A] : Top ↝ Top := { obj := exponential A, map := exponential_induced A, map_id' := by intro X; ext g x; refl, map_comp' := by intros X X' X'' f g; refl } def exponential_adjunction (A : Top) [exponentiable A] : (-× A) ⊣ exponential_functor A := adjunction.mk_of_unit_counit $ { unit := { app := λ X, Top.mk_hom (coev A X) (exponentiable.continuous_coev X) }, counit := { app := λ X, Top.mk_hom (ev A X) (exponentiable.continuous_ev X) }, left_triangle' := by ext X xa; cases xa; refl, right_triangle' := by ext X f a; refl } local attribute [class] is_left_adjoint instance (A : Top) [exponentiable A] : is_left_adjoint (-× A) := { right := exponential_functor A, adj := exponential_adjunction A } -- Locally compact spaces are exponentiable by equipping A ⟶ X with -- the compact-open topology. instance (A : Top) [locally_compact_space A] : exponentiable A := { exponential := λ _, continuous_map.compact_open, functorial := assume X X' g, continuous_induced g.2, continuous_ev := assume X, continuous_ev, continuous_coev := assume X, continuous_coev } end homotopy_theory.topological_spaces
7adece88ebbae9194c0711ed1c0174494aa2eb90
6772a11d96d69b3f90d6eeaf7f9accddf2a7691d
/products.lean
c48563cabd42987b45340ac388402e2288543c25
[]
no_license
lbordowitz/lean-category-theory
5397361f0f81037d65762da48de2c16ec85a5e4b
8c59893e44af3804eba4dbc5f7fa5928ed2e0ae6
refs/heads/master
1,611,310,752,156
1,487,070,172,000
1,487,070,172,000
82,003,141
0
0
null
1,487,118,553,000
1,487,118,553,000
null
UTF-8
Lean
false
false
2,187
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .category import .functor import .natural_transformation -- set_option pp.universes true open tqft.categories open tqft.categories.functor namespace tqft.categories.products universe variables u v @[reducible] definition ProductCategory (C : Category) (D : Category) : Category := { Obj := C^.Obj × D^.Obj, Hom := (λ X Y : C^.Obj × D^.Obj, C^.Hom (X^.fst) (Y^.fst) × D^.Hom (X^.snd) (Y^.snd)), identity := λ X, (C^.identity (X^.fst), D^.identity (X^.snd)), compose := λ _ _ _ f g, (C^.compose (f^.fst) (g^.fst), D^.compose (f^.snd) (g^.snd)), left_identity := ♮, right_identity := ♮, associativity := begin intros, rewrite [ C^.associativity, D^.associativity ] end } namespace ProductCategory notation C `×` D := ProductCategory C D end ProductCategory definition ProductFunctor { A B C D : Category } ( F : Functor A B ) ( G : Functor C D ) : Functor (A × C) (B × D) := { onObjects := λ X, (F X^.fst, G X^.snd), onMorphisms := λ _ _ f, (F^.onMorphisms f^.fst, G^.onMorphisms f^.snd), identities := ♮, functoriality := ♮ } namespace ProductFunctor notation F `×` G := ProductFunctor F G end ProductFunctor @[reducible] definition SwitchProductCategory ( C D : Category ) : Functor (C × D) (D × C) := { onObjects := λ X, (X^.snd, X^.fst), onMorphisms := λ _ _ f, (f^.snd, f^.fst), identities := ♮, functoriality := ♮ } lemma switch_twice_is_the_identity ( C D : Category ) : FunctorComposition ( SwitchProductCategory C D ) ( SwitchProductCategory D C ) = IdentityFunctor (C × D) := ♮ definition ProductCategoryAssociator ( C D E : Category.{ u v } ) : Functor ((C × D) × E) (C × (D × E)) := { onObjects := λ X, (X^.fst^.fst, (X^.fst^.snd, X^.snd)), onMorphisms := λ _ _ f, (f^.fst^.fst, (f^.fst^.snd, f^.snd)), identities := ♮, functoriality := ♮ } end tqft.categories.products
29c53e550340834ba89a90eaa0ce41de3dc15c28
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_first_order/fol_06.lean
111cde219b98011f3d847f904ed1a6adb2eceb01
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
872
lean
namespace fol_06 variable A : Type variables P Q : A → Prop variable h : ¬ ∃ x, P x ∨ Q x include h theorem fol_06 : ∀ x, ¬ P x ∧ ¬ Q x := assume s, have h1: ∀ t, ¬ (P t ∨ Q t), from (assume t: A, classical.by_contradiction (assume h2: ¬¬(P t ∨ Q t), have h3: P t ∨ Q t, from classical.by_contradiction h2, h (exists.intro t h3))), have h4: ¬ (P s ∨ Q s), from h1 s, have h5: ¬ P s, from classical.by_contradiction (assume h6: ¬¬P s, have h7: P s, from classical.by_contradiction h6, have h8: P s ∨ Q s, from or.inl h7, h4 h8), have h9: ¬ Q s, from classical.by_contradiction (assume h10: ¬¬Q s, have h11: Q s, from classical.by_contradiction h10, have h12: P s ∨ Q s, from or.inr h11, h4 h12), have h13: ¬ P s ∧ ¬ Q s, from and.intro h5 h9, show ¬P s ∧ ¬Q s, from h13 end fol_06
8a279e36ba79397049236e711a37fc62001ffce7
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/nat/prime.lean
cb5ac9f7b75b8dd8e519bced59f13d30b99e77e1
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
16,447
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro Prime numbers. -/ import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm open bool subtype namespace nat open decidable /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (decidable.lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := assume hn : n = 0, have h2 : ¬ prime 0, from dec_trivial, h2 (hn ▸ h) theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 := lt_of_succ_lt pp.gt_one theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 := lt_pred_iff.2 pp.gt_one theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_ge_two h a1).1 (dvd_mul_right _ _) section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := rfl | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_ge_two pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, m ≥ 2 → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : min_fac n > 0 := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p := ⟨λ pp, ⟨pp.ge_two, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ theorem exists_infinite_primes (n : ℕ) : ∃ p, p ≥ n ∧ prime p := let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := (nat.mod_two_eq_zero_or_one p).elim (λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) or.inr theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩ lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb], perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l) * p ∣ m*n, from hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, show p^k*p ∣ m ∨ p^l*p ∣ n, from hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) end nat
595f5474b2872d028a1ba1b02d67a46831858b69
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/vector/zip.lean
7b4bb6dbae8a57364a0efb6af3c8a6e75e8cda7f
[ "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
1,165
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 data.vector.basic import data.list.zip /-! # The `zip_with` operation on vectors. -/ namespace vector section zip_with variables {α β γ : Type*} {n : ℕ} (f : α → β → γ) /-- Apply the function `f : α → β → γ` to each corresponding pair of elements from two vectors. -/ def zip_with : vector α n → vector β n → vector γ n := λ x y, ⟨list.zip_with f x.1 y.1, by simp⟩ @[simp] lemma zip_with_to_list (x : vector α n) (y : vector β n) : (vector.zip_with f x y).to_list = list.zip_with f x.to_list y.to_list := rfl @[simp] lemma zip_with_nth (x : vector α n) (y : vector β n) (i) : (vector.zip_with f x y).nth i = f (x.nth i) (y.nth i) := begin dsimp only [vector.zip_with, vector.nth], cases x, cases y, simp only [list.nth_le_zip_with, subtype.coe_mk], congr, end @[simp] lemma zip_with_tail (x : vector α n) (y : vector β n) : (vector.zip_with f x y).tail = vector.zip_with f x.tail y.tail := by { ext, simp [nth_tail], } end zip_with end vector
98f87333ce336f1dc80b9e8b0d1f2bc6f4cc56b1
ec5e5a9dbe7f60fa5784d15211d8bf24ada0825c
/src/PP.lean
07b4e36655d2903f3fe65995762e1877d446e5d9
[]
no_license
pnwamk/lean-llvm
fcd9a828e52e80eb197f7d9032b3846f2e09ef74
ebc3bca9a57a6aef29529d46394f560398fb5c9c
refs/heads/master
1,668,418,078,706
1,593,548,643,000
1,593,548,643,000
258,617,753
0
0
null
1,587,760,298,000
1,587,760,298,000
null
UTF-8
Lean
false
false
21,557
lean
import Init.Data.List import Init.Data.RBMap import Init.Data.String import LeanLLVM.AST namespace LLVM structure Doc : Type := (compose : String → String). class HasPP (α:Type _) := (pp : α → Doc) export HasPP (pp) namespace Doc reserve infixl ` <+> `: 50 reserve infixl ` $+$ `: 60 def text (x:String) := Doc.mk (fun z => x ++ z). def render (x:Doc) : String := x.compose "". def toDoc {a:Type} [HasToString a] : a → Doc := text ∘ toString. def empty : Doc := Doc.mk id. def next_to (x y : Doc) : Doc := Doc.mk (x.compose ∘ y.compose). reserve infixl ` <> `: 50 infix <> := next_to. instance : Inhabited Doc := ⟨empty⟩ def spacesep (x y:Doc) : Doc := x <> text " " <> y def linesep (x y:Doc) : Doc := x <> text "\n" <> y infix <+> := spacesep infix $+$ := linesep def hcat (xs:List Doc) : Doc := List.foldr next_to empty xs. def hsep (xs:List Doc) : Doc := List.foldr spacesep empty xs. def vcat (xs:List Doc) : Doc := List.foldr linesep empty xs. def punctuate (p:Doc) : List Doc → List Doc | [ ] => [] | (x::xs) => x :: (List.foldr (fun a b => p :: a :: b) [] xs) def nat : Nat → Doc := text ∘ toString def int : Int → Doc := text ∘ toString def pp_nonzero : Nat → Doc | Nat.zero => empty | n => nat n def surrounding (first last : String) (x:Doc) : Doc := text first <> x <> text last def parens : Doc → Doc := surrounding "(" ")" def brackets : Doc → Doc := surrounding "[" "]" def angles : Doc → Doc := surrounding "<" ">" def braces : Doc → Doc := surrounding "{" "}" def comma : Doc := text "," def commas : List Doc → Doc := hcat ∘ punctuate comma def quotes : Doc → Doc := surrounding "\'" "\'" def dquotes : Doc → Doc := surrounding "\"" "\"" def pp_opt {A:Type} (f:A → Doc) : Option A → Doc | some a => f a | none => empty end Doc end LLVM namespace LLVM open Doc namespace AlignType def ppDoc : AlignType → Doc | integer => text "i" | vector => text "v" | float => text "f" instance : HasPP AlignType := ⟨ppDoc⟩ end AlignType namespace Mangling def ppDoc : Mangling → Doc | elf => text "e" | mips => text "m" | mach_o => text "o" | windows_coff => text "w" | windows_coff_x86 => text "x" instance : HasPP Mangling := ⟨ppDoc⟩ end Mangling namespace LayoutSpec def ppDoc : LayoutSpec → Doc | endianness Endian.big => text "E" | endianness Endian.little => text "e" | pointerSize addrSpace sz abi pref idx => text "p" <> pp_nonzero addrSpace <> text ":" <> nat sz <> text ":" <> nat abi <> text ":" <> nat pref <> text ":" <> pp_opt (λi => text ":" <> nat i) idx | alignSize tp sz abi pref => pp tp <> nat sz <> text ":" <> nat abi <> pp_opt (λx => text ":" <> nat x) pref | nativeIntSize szs => text "n" <> hcat (punctuate (text ":") (List.map nat szs)) | stackAlign n => text "S" <> nat n | aggregateAlign abi pref => text "a:" <> nat abi <> text ":" <> nat pref | mangling m => text "m:" <> pp m | functionAddressSpace n => text "P" <> nat n | stackAlloca n => text "A" <> nat n instance : HasPP LayoutSpec := ⟨ppDoc⟩ end LayoutSpec section LayoutSpec open LayoutSpec def pp_layout (xs:List LayoutSpec) : Doc := hcat (punctuate (text "-") (pp <$> xs)) def l1 : List LayoutSpec := [ endianness Endian.big, mangling Mangling.mach_o, pointerSize 0 64 64 64 none, alignSize AlignType.integer 64 64 none, alignSize AlignType.float 80 128 none, alignSize AlignType.float 64 64 none, nativeIntSize [8,16,32,64], stackAlign 128 ] end LayoutSpec -- FIXME! We need to handle escaping... def pp_string_literal : String → Doc := dquotes ∘ text namespace Ident def ppDoc : Ident → Doc | named nm => text "%" <> text nm -- FIXME! deal with the 'validIdentifier' question | anon i => text "%" <> toDoc i instance : HasPP Ident := ⟨ppDoc⟩ end Ident namespace Symbol def ppDoc (n:Symbol) : Doc := text "@" <> text (n.symbol) instance : HasPP Symbol := ⟨ppDoc⟩ end Symbol namespace BlockLabel instance : HasPP BlockLabel := ⟨λl => pp l.label⟩ end BlockLabel def packed_braces : Doc → Doc := surrounding "<{" "}>" namespace FloatType def ppDoc : FloatType → Doc | half => text "half" | float => text "float" | double => text "double" | fp128 => text "fp128" | x86FP80 => text "x86_fp80" | ppcFP128 => text "ppcfp128" instance : HasPP FloatType := ⟨ppDoc⟩ end FloatType namespace PrimType def ppDoc : PrimType → Doc | label => text "label" | token => text "token" | void => text "void" | x86mmx => text "x86mmx" | metadata => text "metadata" | floatType f => pp f | integer n => text "i" <> int n instance : HasPP PrimType := ⟨ppDoc⟩ end PrimType def pp_arg_list (va:Bool) (xs:List Doc) : Doc := parens (commas (xs ++ if va then [text "..."] else [])) /- meta def pp_type_tac := `[unfold has_well_founded.r measure inv_image sizeof has_sizeof.sizeof llvm_type.sizeof at *, try { linarith } ]. -/ namespace LLVMType partial def ppDoc : LLVMType → Doc | prim pt => pp pt | alias nm => text "%" <> text nm | array len ty => brackets (int len <+> text "x" <+> ppDoc ty) | funType ret args va => ppDoc ret <> pp_arg_list va (ppDoc <$> args.toList) | ptr ty => ppDoc ty <> text "*" | struct false ts => braces (commas (ppDoc <$> ts.toList)) | struct true ts => packed_braces (commas (ppDoc <$> ts.toList)) | vector len ty => angles (int len <+> text "x" <+> ppDoc ty) instance : HasPP LLVMType := ⟨ppDoc⟩ end LLVMType namespace Typed def pp_with {α} (f:α → Doc) (x:Typed α) := pp x.type <+> f x.value instance {α} [HasPP α] : HasPP (Typed α) := ⟨pp_with pp⟩ end Typed namespace ConvOp def ppDoc : ConvOp → Doc | trunc => text "trunc" | zext => text "zext" | sext => text "sext" | fp_trunc => text "fptrunc" | fp_ext => text "fpext" | fp_to_ui => text "fptoui" | fp_to_si => text "fptosi" | ui_to_fp => text "uitofp" | si_to_fp => text "sitofp" | ptr_to_int => text "ptrtoint" | int_to_ptr => text "inttoptr" | bit_cast => text "bitcast" instance : HasPP ConvOp := ⟨ppDoc⟩ end ConvOp def pp_wrap_bits (nuw nsw:Bool) : Doc := (if nuw then text " nuw" else empty) <> (if nsw then text " nsw" else empty) def pp_exact_bit (exact:Bool) : Doc := if exact then text " exact" else empty namespace ArithOp def ppDoc : ArithOp → Doc | add nuw nsw => text "add" <> pp_wrap_bits nuw nsw | sub nuw nsw => text "sub" <> pp_wrap_bits nuw nsw | mul nuw nsw => text "mul" <> pp_wrap_bits nuw nsw | udiv exact => text "udiv" <> pp_exact_bit exact | sdiv exact => text "sdiv" <> pp_exact_bit exact | urem => text "urem" | srem => text "srem" | fadd => text "fadd" | fsub => text "fsub" | fmul => text "fmul" | fdiv => text "fdiv" | frem => text "frem" instance : HasPP ArithOp := ⟨ppDoc⟩ end ArithOp namespace ICmpOp def ppDoc : ICmpOp → Doc | ieq => text "eq" | ine => text "ne" | iugt => text "ugt" | iult => text "ult" | iuge => text "uge" | iule => text "ule" | isgt => text "sgt" | islt => text "slt" | isge => text "sge" | isle => text "sle" instance : HasPP ICmpOp := ⟨ppDoc⟩ end ICmpOp namespace FCmpOp def ppDoc : FCmpOp → Doc | ffalse => text "false" | ftrue => text "true" | foeq => text "oeq" | fogt => text "ogt" | foge => text "oge" | folt => text "olt" | fole => text "ole" | fone => text "one" | ford => text "ord" | fueq => text "ueq" | fugt => text "ugt" | fuge => text "uge" | fult => text "ult" | fule => text "ule" | fune => text "une" | funo => text "uno" instance : HasPP FCmpOp := ⟨ppDoc⟩ end FCmpOp namespace BitOp def ppDoc : BitOp → Doc | shl nuw nsw => text "shl" <> pp_wrap_bits nuw nsw | lshr exact => text "lshr" <> pp_exact_bit exact | ashr exact => text "ashr" <> pp_exact_bit exact | and => text "and" | or => text "or" | xor => text "xor" instance : HasPP BitOp := ⟨ppDoc⟩ end BitOp /- meta def pp_val_tac := `[unfold has_well_founded.r measure inv_image sized.psum_size sizeof has_sizeof.sizeof typed.sizeof const_expr.sizeof value.sizeof val_md.sizeof debug_loc.sizeof option.sizeof at *, repeat { rw llvm.typed.sizeof_spec' at *, unfold sizeof has_sizeof.sizeof at * }, try { linarith } ]. -/ section pp open ConstExpr def pp_const_expr (pp_value : Value → Doc) : ConstExpr → Doc | select cond x y => text "select" <+> cond.pp_with pp_value <+> text "," <+> x.pp_with pp_value <+> text "," <+> pp_value y.value | gep inbounds inrange tp vs => text "getelementpointer" <+> (if inbounds then text "inbounds " else empty) <> parens (pp tp <> comma <+> commas (vs.toList.map (λv => v.pp_with pp_value))) | conv op x tp => pp op <+> parens (x.pp_with pp_value <+> text "to" <+> pp tp) | arith op x y => pp op <+> parens (x.pp_with pp_value <> comma <+> pp_value y) | fcmp op x y => text "fcmp" <+> pp op <+> parens (x.pp_with pp_value <> comma <+> y.pp_with pp_value) | icmp op x y => text "icmp" <+> pp op <+> parens (x.pp_with pp_value <> comma <+> y.pp_with pp_value) | bit op x y => pp op <+> parens (x.pp_with pp_value <> comma <+> pp_value y) | blockAddr sym lab => text "blockaddress" <+> parens (pp sym <> comma <+> pp lab) open DebugLoc def pp_debug_loc (pp_md : ValMD → Doc) : DebugLoc → Doc | debugLoc line col scope none => text "!DILocation" <> parens (commas [ text "line:" <+> int line , text "column:" <+> int col , text "scope:" <+> pp_md scope ]) | debugLoc line col scope (some ia) => text "!DILocation" <> parens (commas [ text "line:" <+> int line , text "column:" <+> int col , text "scope:" <+> pp_md scope , text "inlinedAt:" <+> pp_md ia ]) open ValMD partial def pp_md (pp_value : Value → Doc) : ValMD → Doc | string s => text "!" <> pp_string_literal s | value x => x.pp_with pp_value | ref i => text "!" <> int i | node xs => text "!" <> braces (commas (xs.map (λ mx => Option.casesOn mx (text "null") pp_md))) | loc l => pp_debug_loc pp_md l | debugInfo => empty open Value partial def pp_value : Value → Doc | null => text "null" | undef => text "undef" | zeroInit => text "0" | integer i => toDoc i | Value.bool b => toDoc b | string s => text "c" <> pp_string_literal s | ident n => pp n | symbol n => pp n | constExpr e => pp_const_expr pp_value e | label l => pp l | array tp vs => brackets (commas (vs.toList.map (λv => pp tp <+> pp_value v))) | vector tp vs => angles (commas (vs.toList.map (λv => pp tp <+> pp_value v))) | struct fs => braces (commas (fs.toList.map (λf => f.pp_with pp_value))) | packedStruct fs => packed_braces (commas (fs.toList.map (λf => f.pp_with pp_value))) | md d => pp_md pp_value d instance : HasPP Value := ⟨pp_value⟩ end pp namespace AtomicOrdering protected def pp : AtomicOrdering → Doc | unordered => text "unordered" | monotonic => text "monotonic" | acquire => text "acquire" | release => text "release" | acqRel => text "acq_rel" | seqCst => text "seq_cst" instance : HasPP AtomicOrdering := ⟨AtomicOrdering.pp⟩ end AtomicOrdering def pp_align : Option Nat → Doc | some a => comma <+> text "align" <+> nat a | none => empty def pp_scope : Option String → Doc := pp_opt (λnm => text "syncscope" <> parens (pp_string_literal nm)) def pp_call (tailcall:Bool) (mty:Option LLVMType) (f:Value) (args:List (Typed Value)) : Doc := (if tailcall then text "tail call" else text "call") <+> match mty with | none => text "void" | some ty => pp ty <+> pp f <+> parens (commas (args.map pp)) def pp_alloca (tp:LLVMType) (len:Option (Typed Value)) (align:Option Nat) : Doc := text "alloca" <+> pp tp <> pp_opt (λv => comma <+> pp v) len <> pp_align align def pp_load (ptr:Typed Value) (ord:Option AtomicOrdering) (align : Option Nat) : Doc := text "load" <> (if Option.isSome ord then text " atomic" else empty) <+> pp ptr <> pp_opt pp ord <> pp_opt pp_align align def pp_store (val:Typed Value) (ptr:Typed Value) (align:Option Nat) : Doc := text "store" <+> pp val <> comma <+> pp ptr <> pp_align align def pp_phi_arg (vl:Value × BlockLabel) : Doc := brackets (pp vl.1 <> comma <+> pp vl.2) def pp_gep (bounds:Bool) (base:Typed Value) (xs:List (Typed Value)) : Doc := text "getelementpointer" <> (if bounds then text " inbounds" else empty) <+> commas (pp base :: xs.map pp) def pp_vector_index (v:Value) : Doc := text "i" <> int 32 <+> pp v def pp_typed_label (l:BlockLabel) : Doc := text "label" <+> pp l def pp_invoke (ty:LLVMType) (f:Value) (args:List (Typed Value)) (to:BlockLabel) (uw:BlockLabel) : Doc := text "invoke" <+> pp ty <+> pp f <> parens (commas (pp <$> args)) <+> text "to label" <+> pp to <+> text "unwind label" <+> pp uw def pp_clause : (clause × Typed Value)→ Doc | (clause.catch, v) => text "catch" <+> pp v | (clause.filter, v) => text "filter" <+> pp v def pp_clauses (is_cleanup:Bool) (cs:List (clause × Typed Value) ): Doc := hsep ((if is_cleanup then [text "cleanup"] else []) ++ cs.map pp_clause) def pp_switch_entry (ty:LLVMType) : (Nat × BlockLabel) → Doc | (i, l) => pp ty <+> nat i <> comma <+> pp l namespace Instruction protected def ppDoc : Instruction → Doc | ret v => text "ret" <+> pp v | retVoid => text "ret void" | arith op x y => pp op <+> pp x <> comma <+> pp y | bit op x y => pp op <+> pp x <> comma <+> pp y | conv op x ty => pp op <+> pp x <+> text "to" <+> pp ty | call tailcall ty f args => pp_call tailcall ty f args.toList | alloca tp len align => pp_alloca tp len align | load ptr ord align => pp_load ptr ord align | store val ptr align => pp_store val ptr align | icmp op x y => text "icmp" <+> pp op <+> pp x <> comma <+> pp y | fcmp op x y => text "fcmp" <+> pp op <+> pp x <> comma <+> pp y | phi ty vls => text "phi" <+> pp ty <+> commas (vls.toList.map pp_phi_arg) | gep bounds base args => pp_gep bounds base args.toList | select cond x y => text "select" <+> pp cond <> comma <+> pp x <> comma <+> pp x.type <+> pp y | extractvalue v i => text "extractvalue" <+> pp v <> comma <+> commas (i.map nat) | insertvalue v e i => text "insertvalue" <+> pp v <> comma <+> pp e <> comma <+> commas (nat <$> i) | extractelement v i => text "extractelement" <+> pp v <> comma <+> pp_vector_index i | insertelement v e i => text "insertelement" <+> pp v <> comma <+> pp e <> comma <+> pp_vector_index i | shufflevector a b m => text "shufflevector" <+> pp a <> comma <+> pp a.type <+> pp b <> comma <+> pp m | jump l => text "jump label" <+> pp l | br cond thn els => text "br" <+> pp cond <> comma <+> text "label" <+> pp thn <> comma <+> text "label" <+> pp els | invoke tp f args to uw => pp_invoke tp f args to uw | comment str => text ";" <> text str | unreachable => text "unreachable" | unwind => text "unwind" | va_arg v tp => text "va_arg" <+> pp v <> comma <+> pp tp | indirectbr d ls => text "indirectbr" <+> pp d <> comma <+> commas (pp_typed_label <$> ls) | switch c d ls => text "switch" <+> pp c <> comma <+> pp_typed_label d <+> brackets (hcat (pp_switch_entry c.type <$> ls)) | landingpad ty mfn c cs => text "landingpad" <+> pp ty <> pp_opt (λv => text " personality" <+> pp v) mfn <+> pp_clauses c cs | resume v => text "resume" <+> pp v instance : HasPP Instruction := ⟨Instruction.ppDoc⟩ end Instruction namespace Stmt def ppDoc (s:Stmt) : Doc := text " " <> match s.assign with | none => pp s.instr | some i => pp i <+> text "=" <+> pp s.instr -- <> pp_attached_metadata s.metadata instance : HasPP Stmt := ⟨ppDoc⟩ end Stmt namespace BasicBlock def ppDoc (bb:BasicBlock) := vcat ([ pp bb.label <> text ":" ] ++ pp <$> bb.stmts.toList) instance : HasPP BasicBlock := ⟨ppDoc⟩ end BasicBlock def pp_comdat_name (nm:String) : Doc := text "comdat" <> parens (text "$" <> text nm) namespace FunAttr protected def pp : FunAttr → Doc | align_stack w => text "alignstack" <> parens (nat w) | alwaysinline => text "alwaysinline" | builtin => text "builtin" | cold => text "cold" | inlinehint => text "inlinehint" | jumptable => text "jumptable" | minsize => text "minsize" | naked => text "naked" | nobuiltin => text "nobuiltin" | noduplicate => text "noduplicate" | noimplicitfloat => text "noimplicitfloat" | noinline => text "noinline" | nonlazybind => text "nonlazybind" | noredzone => text "noredzone" | noreturn => text "noreturn" | nounwind => text "nounwind" | optnone => text "optnone" | optsize => text "optsize" | readnone => text "readnone" | readonly => text "readonly" | returns_twice => text "returns_twice" | sanitize_address => text "sanitize_address" | sanitize_memory => text "sanitize_memory" | sanitize_thread => text "sanitize_thread" | ssp => text "ssp" | ssp_req => text "sspreq" | ssp_strong => text "sspstrong" | uwtable => text "uwtable" instance : HasPP FunAttr := ⟨FunAttr.pp⟩ end FunAttr namespace Declare def ppDoc (d:Declare) : Doc := text "declare" <+> pp d.retType <+> pp d.name <> pp_arg_list d.varArgs (pp <$> d.args.toList) <+> hsep (pp <$> d.attrs.toList) <> pp_opt (λnm => text " " <> pp_comdat_name nm) d.comdat instance : HasPP Declare := ⟨ppDoc⟩ end Declare namespace Linkage protected def pp : Linkage → Doc | private_linkage => text "private" | linker_private => text "linker_private" | linker_private_weak => text "linker_private_weak" | linker_private_weak_def_auto => text "linker_private_weak_def_auto" | internal => text "internal" | available_externally => text "available_externally" | linkonce => text "linkonce" | weak => text "weak" | common => text "common" | appending => text "appending" | extern_weak => text "extern_weak" | linkonce_odr => text "linkonce_odr" | weak_odr => text "weak_odr" | external => text "external" | dll_import => text "dllimport" | dll_export => text "dllexport" instance : HasPP Linkage := ⟨Linkage.pp⟩ end Linkage namespace Visibility def pp : Visibility → Doc | default => text "default" | hidden => text "hidden" | protected_visibility => text "protected" instance : HasPP Visibility := ⟨Visibility.pp⟩ end Visibility namespace GlobalAttrs protected def pp (ga:GlobalAttrs) : Doc := pp_opt pp ga.linkage <+> pp_opt pp ga.visibility <+> (if ga.const then text "const" else text "global") instance : HasPP GlobalAttrs := ⟨GlobalAttrs.pp⟩ end GlobalAttrs namespace Global def ppDoc (g:Global) : Doc := pp g.sym <+> text "=" <+> pp g.attrs <+> pp g.type <+> pp_opt pp_value g.value <> pp_align g.align -- <> pp_attached_metadata g.metadata instance : HasPP Global := ⟨ppDoc⟩ end Global namespace GlobalAlias def ppDoc (ga:GlobalAlias) : Doc := let tgtd := match ga.target with | Value.symbol _ => pp ga.type <> text " " | _ => empty; pp ga.name <+> text "=" <+> tgtd <> pp ga.target instance : HasPP GlobalAlias := ⟨ppDoc⟩ end GlobalAlias namespace TypeDeclBody def ppDoc : TypeDeclBody -> Doc | opaque => text "opaque" | defn tp => pp tp instance : HasPP TypeDeclBody := ⟨TypeDeclBody.ppDoc⟩ end TypeDeclBody namespace TypeDecl def ppDoc (t:TypeDecl) := text "%" <> text t.name <+> text "= type" <+> pp t.decl instance : HasPP TypeDecl := ⟨TypeDecl.ppDoc⟩ end TypeDecl namespace GC def ppDoc (x:GC) : Doc := pp_string_literal x.gc instance : HasPP GC := ⟨ppDoc⟩ end GC namespace Define def ppDoc (d:Define) : Doc := text "define" <+> pp_opt pp d.linkage <+> pp d.retType <+> pp d.name <> pp_arg_list d.varArgs (pp <$> d.args.toList) <+> hsep (pp <$> d.attrs.toList) <> pp_opt (λs => text " section" <+> pp_string_literal s) d.sec <> pp_opt (λg => text " gc" <+> pp g) d.gc <+> -- pp_mds d.metadata <+> vcat ([ text "{" ] ++ List.map pp d.body.toList ++ [ text "}" ]) instance : HasPP Define := ⟨ppDoc⟩ end Define namespace Module def ppDoc (m:Module) : Doc := pp_opt (λnm => text "source_filename = " <> pp_string_literal nm) m.sourceName $+$ text "target datalayout = " <> dquotes (pp_layout m.dataLayout) $+$ vcat (List.join [ pp <$> m.types.toList , pp <$> m.globals.toList , pp <$> m.aliases.toList , pp <$> m.declares.toList , pp <$> m.defines.toList -- , list.map pp_named_md m.named_md -- , list.map pp_unnamed_md m.unnamed_md -- , list.map pp_comdat m.comdat ]) instance : HasPP Module := ⟨ppDoc⟩ end Module end LLVM def ppLLVM {α} [LLVM.HasPP α] (a : α) : String := LLVM.Doc.render $ LLVM.HasPP.pp a
4612b2330070d22c3e850e986f27e893b51ce897
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/ring_theory/euclidean_domain.lean
f955c2296d1c1e212add668c21d89cf1d7e538aa
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,905
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import algebra.associated algebra.euclidean_domain ring_theory.ideals noncomputable theory open_locale classical open euclidean_domain set ideal theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin apply le_antisymm; refine span_le.1 _, { simp [submodule.span_span, mem_span_pair, submodule.le_def', mem_span_singleton'], assume a b ha, exact ⟨b * gcd_a x y, b * gcd_b x y, by rw [← ha, gcd_eq_gcd_ab x y]; simp [mul_add, mul_comm, mul_left_comm]⟩ }, { assume z , simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair, @eq_comm _ _ z] {contextual := tt}, assume a b h, exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _) (dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) } end theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := by rw [← span_singleton_eq_top, span_gcd, is_coprime] theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, euclidean_domain.gcd_eq_zero_iff] end theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), unfreezeI, apply is_coprime_of_dvd, { rintro ⟨rfl, rfl⟩, simpa using h }, { rintro z nu nz ⟨w, rfl⟩ dy, refine h' (dvd.trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end
bc9cabf8a568b7f329b7a96f208aa59087d30d8c
f3ab5c6b849dd89e43f1fe3572fbed3fc1baaf0f
/lean/invertible.lean
eb60ab694ce3fc2f463aa5983aa0205ca62b2313
[ "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ekmett/coda
69fa7ac66924ea2cee12f7005b192c22baf9e03e
3309ea70c31b58a3915b0ecc9140985c3a1ac565
refs/heads/master
1,670,616,044,398
1,619,020,702,000
1,619,020,702,000
100,850,826
170
15
NOASSERTION
1,670,434,088,000
1,503,220,814,000
Haskell
UTF-8
Lean
false
false
3,618
lean
open function open sigma section bijections universes u₁ u₂ variables {α : Type u₁} {β : Type u₂} -- promote some existing propositions to classes attribute [class] injective attribute [class] surjective attribute [class] bijective attribute [class] has_left_inverse attribute [class] has_right_inverse instance mk_bijective {f: α → β} [fi : injective f] [fs: surjective f]: bijective f := (| fi, fs |) instance bijective_injective {f: α → β} [bf: bijective f]: injective f := bf.1 instance bijective_surjective {f: α → β} [bf: bijective f]: surjective f := bf.2 instance has_left_inverse_injective {f : α → β} [h : has_left_inverse f]: injective f := injective_of_has_left_inverse h instance has_right_inverse_surjective {f : α → β} [h : has_right_inverse f]: surjective f := surjective_of_has_right_inverse h end bijections structure {u₁ u₂} invertible {α : Type u₁} {β : Type u₂} (f : α → β) := (invf : β → α) (invinj : injective invf) (linv : left_inverse invf f) attribute [class] invertible section inverses -- computable inverses -- end goal: uniqueness of inverses universes u₁ u₂ variables {α : Type u₁} {β : Type u₂} def inverse (f : α → β) [iF : invertible f]: β → α := invertible.invf iF def invertible_left_inverse (f : α → β) [iF : invertible f]: left_inverse (inverse f) f := invertible.linv iF def invertible_right_inverse (f : α → β) [iF : invertible f]: right_inverse (inverse f) f := right_inverse_of_injective_of_left_inverse (invertible.invinj iF) (invertible.linv iF) def invertible_has_right_inverse (f : α → β) [iF : invertible f]: has_right_inverse f := exists.intro (invertible.invf iF) (invertible_right_inverse f) def invertible_has_left_inverse (f : α → β) [iF : invertible f]: has_left_inverse f := exists.intro (invertible.invf iF) (invertible.linv iF) instance invertible_injective_inverse {f : α → β} [iF : invertible f]: injective (inverse f) := invertible.invinj iF instance invertible_surjective {f : α → β} [iF : invertible f]: surjective f := begin destruct (invertible_has_right_inverse f), intros g fg b, apply exists.intro, exact (fg b) end instance invertible_injective {f: α → β} [iF : invertible f]: injective f := injective_of_has_left_inverse (invertible_has_left_inverse f) instance invertible_surjective_inverse {f : α → β} [iF : invertible f]: surjective (inverse f) := begin intro a, apply exists.intro, exact (invertible.linv iF a), end instance invertible_inverse {f : α → β} [iF : invertible f]: invertible (inverse f) := invertible.mk f invertible_injective (invertible_right_inverse f) instance invertible_bijective (f : α → β) [iF : invertible f]: bijective f := (| invertible_injective, invertible_surjective |) instance invertible_bijective_inverse (f : α → β) [iF : invertible f]: bijective (inverse f) := (| invertible_injective_inverse, invertible_surjective_inverse |) -- def invertible_is_unique {f : α → β} (p q: invertible f) : p = q -- up to funext/propext end inverses def {u1 u2 u3} lhs {α : Sort u1} { β : Sort u2 } {γ : Sort u3} (f g : β → α) (h : γ -> β) (fg : f = g) : f ∘ h = g ∘ h := eq.subst fg (@eq.refl (γ → α) (f ∘ h)) def {u1 u2 u3} rhs {α : Sort u1} { β : Sort u2 } {γ : Sort u3} (f : β → α) (g h : γ -> β) (gh : g = h) : f ∘ g = f ∘ h := eq.subst gh (@eq.refl (γ → α) (f ∘ g))
eaa5c6b1e9d5839b7c0cd09a7c8ebdd3bbbfff3b
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/ODE/gronwall.lean
43368b96ed0995789ae12d29add34eeb2cc92822
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
13,193
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.exp_log /-! # Grönwall's inequality The main technical result of this file is the Grönwall-like inequality `norm_le_gronwall_bound_of_norm_deriv_right_le`. It states that if `f : ℝ → E` satisfies `∥f a∥ ≤ δ` and `∀ x ∈ [a, b), ∥f' x∥ ≤ K * ∥f x∥ + ε`, then for all `x ∈ [a, b]` we have `∥f x∥ ≤ δ * exp (K * x) + (ε / K) * (exp (K * x) - 1)`. Then we use this inequality to prove some estimates on the possible rate of growth of the distance between two approximate or exact solutions of an ordinary differential equation. The proofs are based on [Hubbard and West, *Differential Equations: A Dynamical Systems Approach*, Sec. 4.5][HubbardWest-ode], where `norm_le_gronwall_bound_of_norm_deriv_right_le` is called “Fundamental Inequality”. ## TODO - Once we have FTC, prove an inequality for a function satisfying `∥f' x∥ ≤ K x * ∥f x∥ + ε`, or more generally `liminf_{y→x+0} (f y - f x)/(y - x) ≤ K x * f x + ε` with any sign of `K x` and `f x`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics filter real open_locale classical topological_space nnreal /-! ### Technical lemmas about `gronwall_bound` -/ /-- Upper bound used in several Grönwall-like inequalities. -/ noncomputable def gronwall_bound (δ K ε x : ℝ) : ℝ := if K = 0 then δ + ε * x else δ * exp (K * x) + (ε / K) * (exp (K * x) - 1) lemma gronwall_bound_K0 (δ ε : ℝ) : gronwall_bound δ 0 ε = λ x, δ + ε * x := funext $ λ x, if_pos rfl lemma gronwall_bound_of_K_ne_0 {δ K ε : ℝ} (hK : K ≠ 0) : gronwall_bound δ K ε = λ x, δ * exp (K * x) + (ε / K) * (exp (K * x) - 1) := funext $ λ x, if_neg hK lemma has_deriv_at_gronwall_bound (δ K ε x : ℝ) : has_deriv_at (gronwall_bound δ K ε) (K * (gronwall_bound δ K ε x) + ε) x := begin by_cases hK : K = 0, { subst K, simp only [gronwall_bound_K0, zero_mul, zero_add], convert ((has_deriv_at_id x).const_mul ε).const_add δ, rw [mul_one] }, { simp only [gronwall_bound_of_K_ne_0 hK], convert (((has_deriv_at_id x).const_mul K).exp.const_mul δ).add ((((has_deriv_at_id x).const_mul K).exp.sub_const 1).const_mul (ε / K)) using 1, simp only [id, mul_add, (mul_assoc _ _ _).symm, mul_comm _ K, mul_div_cancel' _ hK], ring } end lemma has_deriv_at_gronwall_bound_shift (δ K ε x a : ℝ) : has_deriv_at (λ y, gronwall_bound δ K ε (y - a)) (K * (gronwall_bound δ K ε (x - a)) + ε) x := begin convert (has_deriv_at_gronwall_bound δ K ε _).comp x ((has_deriv_at_id x).sub_const a), rw [id, mul_one] end lemma gronwall_bound_x0 (δ K ε : ℝ) : gronwall_bound δ K ε 0 = δ := begin by_cases hK : K = 0, { simp only [gronwall_bound, if_pos hK, mul_zero, add_zero] }, { simp only [gronwall_bound, if_neg hK, mul_zero, exp_zero, sub_self, mul_one, add_zero] } end lemma gronwall_bound_ε0 (δ K x : ℝ) : gronwall_bound δ K 0 x = δ * exp (K * x) := begin by_cases hK : K = 0, { simp only [gronwall_bound_K0, hK, zero_mul, exp_zero, add_zero, mul_one] }, { simp only [gronwall_bound_of_K_ne_0 hK, zero_div, zero_mul, add_zero] } end lemma gronwall_bound_ε0_δ0 (K x : ℝ) : gronwall_bound 0 K 0 x = 0 := by simp only [gronwall_bound_ε0, zero_mul] lemma gronwall_bound_continuous_ε (δ K x : ℝ) : continuous (λ ε, gronwall_bound δ K ε x) := begin by_cases hK : K = 0, { simp only [gronwall_bound_K0, hK], exact continuous_const.add (continuous_id.mul continuous_const) }, { simp only [gronwall_bound_of_K_ne_0 hK], exact continuous_const.add ((continuous_id.mul continuous_const).mul continuous_const) } end /-! ### Inequality and corollaries -/ /-- A Grönwall-like inequality: if `f : ℝ → ℝ` is continuous on `[a, b]` and satisfies the inequalities `f a ≤ δ` and `∀ x ∈ [a, b), liminf_{z→x+0} (f z - f x)/(z - x) ≤ K * (f x) + ε`, then `f x` is bounded by `gronwall_bound δ K ε (x - a)` on `[a, b]`. See also `norm_le_gronwall_bound_of_norm_deriv_right_le` for a version bounding `∥f x∥`, `f : ℝ → E`. -/ theorem le_gronwall_bound_of_liminf_deriv_right_le {f f' : ℝ → ℝ} {δ K ε : ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) (ha : f a ≤ δ) (bound : ∀ x ∈ Ico a b, f' x ≤ K * f x + ε) : ∀ x ∈ Icc a b, f x ≤ gronwall_bound δ K ε (x - a) := begin have H : ∀ x ∈ Icc a b, ∀ ε' ∈ Ioi ε, f x ≤ gronwall_bound δ K ε' (x - a), { assume x hx ε' hε', apply image_le_of_liminf_slope_right_lt_deriv_boundary hf hf', { rwa [sub_self, gronwall_bound_x0] }, { exact λ x, has_deriv_at_gronwall_bound_shift δ K ε' x a }, { assume x hx hfB, rw [← hfB], apply lt_of_le_of_lt (bound x hx), exact add_lt_add_left hε' _ }, { exact hx } }, assume x hx, change f x ≤ (λ ε', gronwall_bound δ K ε' (x - a)) ε, convert continuous_within_at_const.closure_le _ _ (H x hx), { simp only [closure_Ioi, left_mem_Ici] }, exact (gronwall_bound_continuous_ε δ K (x - a)).continuous_within_at end /-- A Grönwall-like inequality: if `f : ℝ → E` is continuous on `[a, b]`, has right derivative `f' x` at every point `x ∈ [a, b)`, and satisfies the inequalities `∥f a∥ ≤ δ`, `∀ x ∈ [a, b), ∥f' x∥ ≤ K * ∥f x∥ + ε`, then `∥f x∥` is bounded by `gronwall_bound δ K ε (x - a)` on `[a, b]`. -/ theorem norm_le_gronwall_bound_of_norm_deriv_right_le {f f' : ℝ → E} {δ K ε : ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (ha : ∥f a∥ ≤ δ) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ K * ∥f x∥ + ε) : ∀ x ∈ Icc a b, ∥f x∥ ≤ gronwall_bound δ K ε (x - a) := le_gronwall_bound_of_liminf_deriv_right_le (continuous_norm.comp_continuous_on hf) (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha bound /-- If `f` and `g` are two approximate solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in some time-dependent set `s t`, and assumes that the solutions never leave this set. -/ theorem dist_le_of_approx_trajectories_ODE_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g f' g' : ℝ → E} {a b : ℝ} {εf εg δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (f' t) (Ici t) t) (f_bound : ∀ t ∈ Ico a b, dist (f' t) (v t (f t)) ≤ εf) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (g' t) (Ici t) t) (g_bound : ∀ t ∈ Ico a b, dist (g' t) (v t (g t)) ≤ εg) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ gronwall_bound δ K (εf + εg) (t - a) := begin simp only [dist_eq_norm] at ha ⊢, have h_deriv : ∀ t ∈ Ico a b, has_deriv_within_at (λ t, f t - g t) (f' t - g' t) (Ici t) t, from λ t ht, (hf' t ht).sub (hg' t ht), apply norm_le_gronwall_bound_of_norm_deriv_right_le (hf.sub hg) h_deriv ha, assume t ht, have := dist_triangle4_right (f' t) (g' t) (v t (f t)) (v t (g t)), rw [dist_eq_norm] at this, apply le_trans this, apply le_trans (add_le_add (add_le_add (f_bound t ht) (g_bound t ht)) (hv t (f t) (g t) (hfs t ht) (hgs t ht))), rw [dist_eq_norm, add_comm] end /-- If `f` and `g` are two approximate solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in the whole space. -/ theorem dist_le_of_approx_trajectories_ODE {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g f' g' : ℝ → E} {a b : ℝ} {εf εg δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (f' t) (Ici t) t) (f_bound : ∀ t ∈ Ico a b, dist (f' t) (v t (f t)) ≤ εf) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (g' t) (Ici t) t) (g_bound : ∀ t ∈ Ico a b, dist (g' t) (v t (g t)) ≤ εg) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ gronwall_bound δ K (εf + εg) (t - a) := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, dist_le_of_approx_trajectories_ODE_of_mem_set (λ t x y hx hy, (hv t).dist_le_mul x y) hf hf' f_bound hfs hg hg' g_bound (λ t ht, trivial) ha /-- If `f` and `g` are two exact solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in some time-dependent set `s t`, and assumes that the solutions never leave this set. -/ theorem dist_le_of_trajectories_ODE_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g : ℝ → E} {a b : ℝ} {δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ δ * exp (K * (t - a)) := begin have f_bound : ∀ t ∈ Ico a b, dist (v t (f t)) (v t (f t)) ≤ 0, by { intros, rw [dist_self] }, have g_bound : ∀ t ∈ Ico a b, dist (v t (g t)) (v t (g t)) ≤ 0, by { intros, rw [dist_self] }, assume t ht, have := dist_le_of_approx_trajectories_ODE_of_mem_set hv hf hf' f_bound hfs hg hg' g_bound hgs ha t ht, rwa [zero_add, gronwall_bound_ε0] at this, end /-- If `f` and `g` are two exact solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in the whole space. -/ theorem dist_le_of_trajectories_ODE {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g : ℝ → E} {a b : ℝ} {δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ δ * exp (K * (t - a)) := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, dist_le_of_trajectories_ODE_of_mem_set (λ t x y hx hy, (hv t).dist_le_mul x y) hf hf' hfs hg hg' (λ t ht, trivial) ha /-- There exists only one solution of an ODE \(\dot x=v(t, x)\) in a set `s ⊆ ℝ × E` with a given initial value provided that RHS is Lipschitz continuous in `x` within `s`, and we consider only solutions included in `s`. -/ theorem ODE_solution_unique_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g : ℝ → E} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : f a = g a) : ∀ t ∈ Icc a b, f t = g t := begin assume t ht, have := dist_le_of_trajectories_ODE_of_mem_set hv hf hf' hfs hg hg' hgs (dist_le_zero.2 ha) t ht, rwa [zero_mul, dist_le_zero] at this end /-- There exists only one solution of an ODE \(\dot x=v(t, x)\) with a given initial value provided that RHS is Lipschitz continuous in `x`. -/ theorem ODE_solution_unique {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g : ℝ → E} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (ha : f a = g a) : ∀ t ∈ Icc a b, f t = g t := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, ODE_solution_unique_of_mem_set (λ t x y hx hy, (hv t).dist_le_mul x y) hf hf' hfs hg hg' (λ t ht, trivial) ha
050b4343c9794744c01cc855cdbbd70d3c90c386
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/equiv/ring.lean
8c352ae4cabf3c675ab2e42bc881766fd877053e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
12,379
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, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /-- An equivalence between two (semi)rings that preserves the algebraic structure. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv /-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_equiv /-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_add_equiv /-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_mul_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe_fun (f : R ≃+* S) : f.to_fun = f := rfl /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ @[norm_cast] lemma coe_mul_equiv (f : R ≃+* S) (a : R) : (f : R ≃* S) a = f a := rfl @[norm_cast] lemma coe_add_equiv (f : R ≃+* S) (a : R) : (f : R ≃+ S) a = f a := rfl variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩ variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun (e : R ≃+* S) : S → R := e.symm initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply) /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } @[simp] lemma trans_apply {A B C : Type*} [semiring A] [semiring B] [semiring C] (e : A ≃+* B) (f : B ≃+* C) (a : A) : e.trans f a = f (e a) := rfl protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring section semiring variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] [semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) := λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h) instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ @[norm_cast] lemma coe_ring_hom (f : R ≃+* S) (a : R) : (f : R →+* S) a = f a := rfl lemma coe_ring_hom_inj_iff {R S : Type*} [semiring R] [semiring S] (f g : R ≃+* S) : f = g ↔ (f : R →+* S) = g := ⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩ /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl /-- Construct an equivalence of rings from homomorphisms in both directions, which are inverses. -/ def of_hom_inv (hom : R →+* S) (inv : S →+* R) (hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) : R ≃+* S := { inv_fun := inv, left_inv := λ x, ring_hom.congr_fun hom_inv_id x, right_inv := λ x, ring_hom.congr_fun inv_hom_id x, ..hom } @[simp] lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) : (of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl @[simp] lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) : (of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] @[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx) (λ hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by λ g h, ring_equiv.trans h g. This means that multiplication agrees with composition, (g*h)(x) = g (h x) . -/ instance : group (ring_aut R) := by refine_struct { mul := λ g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R →* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R →* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R →* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut namespace equiv variables (K : Type*) [division_ring K] /-- In a division ring `K`, the unit group `units K` is equivalent to the subtype of nonzero elements. -/ -- TODO: this might already exist elsewhere for `group_with_zero` -- deduplicate or generalize def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} := ⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
4cad54f62c2d19566689c4fd7199fcf941044516
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/types/nat/basic.hlean
32f50878271e01fc1abfd552ba97854e042e5bb5
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
10,020
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. (Ported from standard library) Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad Basic operations on the natural numbers. -/ import ..num algebra.ring open prod binary eq algebra lift is_trunc namespace nat /- a variant of add, defined by recursion on the first argument -/ definition addl (x y : ℕ) : ℕ := nat.rec y (λ n r, succ r) x infix ` ⊕ `:65 := addl theorem addl_succ_right (n m : ℕ) : n ⊕ succ m = succ (n ⊕ m) := nat.rec_on n rfl (λ n₁ ih, calc succ n₁ ⊕ succ m = succ (n₁ ⊕ succ m) : rfl ... = succ (succ (n₁ ⊕ m)) : ih ... = succ (succ n₁ ⊕ m) : rfl) theorem add_eq_addl (x : ℕ) : Πy, x + y = x ⊕ y := nat.rec_on x (λ y, nat.rec_on y rfl (λ y₁ ih, calc 0 + succ y₁ = succ (0 + y₁) : rfl ... = succ (0 ⊕ y₁) : {ih} ... = 0 ⊕ (succ y₁) : rfl)) (λ x₁ ih₁ y, nat.rec_on y (calc succ x₁ + 0 = succ (x₁ + 0) : rfl ... = succ (x₁ ⊕ 0) : {ih₁ 0} ... = succ x₁ ⊕ 0 : rfl) (λ y₁ ih₂, calc succ x₁ + succ y₁ = succ (succ x₁ + y₁) : rfl ... = succ (succ x₁ ⊕ y₁) : {ih₂} ... = succ x₁ ⊕ succ y₁ : addl_succ_right)) /- successor and predecessor -/ theorem succ_ne_zero (n : ℕ) : succ n ≠ 0 := by contradiction -- add_rewrite succ_ne_zero theorem pred_zero [simp] : pred 0 = 0 := rfl theorem pred_succ [simp] (n : ℕ) : pred (succ n) = n := rfl theorem eq_zero_sum_eq_succ_pred (n : ℕ) : n = 0 ⊎ n = succ (pred n) := nat.rec_on n (sum.inl rfl) (take m IH, sum.inr (show succ m = succ (pred (succ m)), from ap succ !pred_succ⁻¹)) theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : Σk : ℕ, n = succ k := sigma.mk _ (sum_resolve_right !eq_zero_sum_eq_succ_pred H) theorem succ.inj {n m : ℕ} (H : succ n = succ m) : n = m := down (nat.no_confusion H imp.id) abbreviation eq_of_succ_eq_succ := @succ.inj theorem succ_ne_self {n : ℕ} : succ n ≠ n := nat.rec_on n (take H : 1 = 0, have ne : 1 ≠ 0, from !succ_ne_zero, absurd H ne) (take k IH H, IH (succ.inj H)) theorem discriminate {B : Type} {n : ℕ} (H1: n = 0 → B) (H2 : Πm, n = succ m → B) : B := have H : n = n → B, from nat.cases_on n H1 H2, H rfl theorem two_step_rec_on {P : ℕ → Type} (a : ℕ) (H1 : P 0) (H2 : P 1) (H3 : Π (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a × P (succ a), from nat.rec_on a (pair H1 H2) (take k IH, have IH1 : P k, from prod.pr1 IH, have IH2 : P (succ k), from prod.pr2 IH, pair IH2 (H3 k IH1 IH2)), prod.pr1 stronger theorem sub_induction {P : ℕ → ℕ → Type} (n m : ℕ) (H1 : Πm, P 0 m) (H2 : Πn, P (succ n) 0) (H3 : Πn m, P n m → P (succ n) (succ m)) : P n m := have general : Πm, P n m, from nat.rec_on n H1 (take k : ℕ, assume IH : Πm, P k m, take m : ℕ, nat.cases_on m (H2 k) (take l, (H3 k l (IH l)))), general m /- addition -/ protected definition add_zero [simp] (n : ℕ) : n + 0 = n := rfl definition add_succ [simp] (n m : ℕ) : n + succ m = succ (n + m) := rfl protected definition zero_add [simp] (n : ℕ) : 0 + n = n := begin induction n with n IH, reflexivity, exact ap succ IH end definition succ_add [simp] (n m : ℕ) : (succ n) + m = succ (n + m) := begin induction m with m IH, reflexivity, exact ap succ IH end protected definition add_comm [simp] (n m : ℕ) : n + m = m + n := begin induction n with n IH, { apply nat.zero_add}, { exact !succ_add ⬝ ap succ IH} end protected definition add_add (n l k : ℕ) : n + l + k = n + (k + l) := begin induction l with l IH, reflexivity, exact succ_add (n + l) k ⬝ ap succ IH end definition succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := !succ_add protected definition add_assoc [simp] (n m k : ℕ) : (n + m) + k = n + (m + k) := begin induction k with k IH, reflexivity, exact ap succ IH end protected theorem add_left_comm : Π (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add_comm nat.add_assoc protected theorem add_right_comm : Π (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add_comm nat.add_assoc protected theorem add_left_cancel {n m k : ℕ} : n + m = n + k → m = k := nat.rec_on n (take H : 0 + m = 0 + k, !nat.zero_add⁻¹ ⬝ H ⬝ !nat.zero_add) (take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k), have succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : succ_add ... = succ n + k : H ... = succ (n + k) : succ_add, have n + m = n + k, from succ.inj this, IH this) protected theorem add_right_cancel {n m k : ℕ} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from !nat.add_comm ⬝ H ⬝ !nat.add_comm, nat.add_left_cancel H2 theorem eq_zero_of_add_eq_zero_right {n m : ℕ} : n + m = 0 → n = 0 := nat.rec_on n (take (H : 0 + m = 0), rfl) (take k IH, assume H : succ k + m = 0, absurd (show succ (k + m) = 0, from calc succ (k + m) = succ k + m : succ_add ... = 0 : H) !succ_ne_zero) theorem eq_zero_of_add_eq_zero_left {n m : ℕ} (H : n + m = 0) : m = 0 := eq_zero_of_add_eq_zero_right (!nat.add_comm ⬝ H) theorem eq_zero_prod_eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 × m = 0 := pair (eq_zero_of_add_eq_zero_right H) (eq_zero_of_add_eq_zero_left H) theorem add_one [simp] (n : ℕ) : n + 1 = succ n := rfl theorem one_add (n : ℕ) : 1 + n = succ n := !nat.zero_add ▸ !succ_add /- multiplication -/ protected theorem mul_zero [simp] (n : ℕ) : n * 0 = 0 := rfl theorem mul_succ [simp] (n m : ℕ) : n * succ m = n * m + n := rfl -- commutativity, distributivity, associativity, identity protected theorem zero_mul [simp] (n : ℕ) : 0 * n = 0 := nat.rec_on n !nat.mul_zero (take m IH, !mul_succ ⬝ !nat.add_zero ⬝ IH) theorem succ_mul [simp] (n m : ℕ) : (succ n) * m = (n * m) + m := nat.rec_on m (by rewrite nat.mul_zero) (take k IH, calc succ n * succ k = succ n * k + succ n : mul_succ ... = n * k + k + succ n : IH ... = n * k + (k + succ n) : nat.add_assoc ... = n * k + (succ n + k) : nat.add_comm ... = n * k + (n + succ k) : succ_add_eq_succ_add ... = n * k + n + succ k : nat.add_assoc ... = n * succ k + succ k : mul_succ) protected theorem mul_comm [simp] (n m : ℕ) : n * m = m * n := nat.rec_on m (!nat.mul_zero ⬝ !nat.zero_mul⁻¹) (take k IH, calc n * succ k = n * k + n : mul_succ ... = k * n + n : IH ... = (succ k) * n : succ_mul) protected theorem right_distrib (n m k : ℕ) : (n + m) * k = n * k + m * k := nat.rec_on k (calc (n + m) * 0 = 0 : nat.mul_zero ... = 0 + 0 : nat.add_zero ... = n * 0 + 0 : nat.mul_zero ... = n * 0 + m * 0 : nat.mul_zero) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ ... = n * l + m * l + (n + m) : IH ... = n * l + m * l + n + m : nat.add_assoc ... = n * l + n + m * l + m : nat.add_right_comm ... = n * l + n + (m * l + m) : nat.add_assoc ... = n * succ l + (m * l + m) : mul_succ ... = n * succ l + m * succ l : mul_succ) protected theorem left_distrib (n m k : ℕ) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : nat.mul_comm ... = m * n + k * n : nat.right_distrib ... = n * m + k * n : nat.mul_comm ... = n * m + n * k : nat.mul_comm protected theorem mul_assoc [simp] (n m k : ℕ) : (n * m) * k = n * (m * k) := nat.rec_on k (calc (n * m) * 0 = n * (m * 0) : nat.mul_zero) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ ... = n * (m * l) + n * m : IH ... = n * (m * l + m) : nat.left_distrib ... = n * (m * succ l) : mul_succ) protected theorem mul_one [simp] (n : ℕ) : n * 1 = n := calc n * 1 = n * 0 + n : mul_succ ... = 0 + n : nat.mul_zero ... = n : nat.zero_add protected theorem one_mul [simp] (n : ℕ) : 1 * n = n := calc 1 * n = n * 1 : nat.mul_comm ... = n : nat.mul_one theorem eq_zero_sum_eq_zero_of_mul_eq_zero {n m : ℕ} : n * m = 0 → n = 0 ⊎ m = 0 := nat.cases_on n (assume H, sum.inl rfl) (take n', nat.cases_on m (assume H, sum.inr rfl) (take m', assume H : succ n' * succ m' = 0, absurd (calc 0 = succ n' * succ m' : H ... = succ n' * m' + succ n' : mul_succ ... = succ (succ n' * m' + n') : add_succ)⁻¹ !succ_ne_zero)) protected definition comm_semiring [trans_instance] : comm_semiring nat := ⦃comm_semiring, add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm, is_set_carrier:= _⦄ end nat section open nat definition iterate {A : Type} (op : A → A) : ℕ → A → A | 0 := λ a, a | (succ k) := λ a, op (iterate k a) notation f `^[`:80 n:0 `]`:0 := iterate f n end
9300a4d8c00cac9fa24a565a9fc26488dc3919ba
5ec8f5218a7c8e87dd0d70dc6b715b36d61a8d61
/switch.lean
17bff4216166d3cffd2e65e9f86ab963750619f8
[]
no_license
mbrodersen/kremlin
f9f2f9dd77b9744fe0ffd5f70d9fa0f1f8bd8cec
d4665929ce9012e93a0b05fc7063b96256bab86f
refs/heads/master
1,624,057,268,130
1,496,957,084,000
1,496,957,084,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,363
lean
/- Multi-way branches (``switch'' statements) and their compilation to comparison trees. -/ import .values namespace switch open values word integers maps inductive switch_argument : bool → val → Π w:ℕ+, word w → Prop | switch_argument_32 (i) : switch_argument ff (Vint i) _ i | switch_argument_64 (i) : switch_argument tt (Vlong i) _ i section parameter wordsize : ℕ+ local notation `uword` := uword wordsize /- A multi-way branch is composed of a list of (key, action) pairs, plus a default action. -/ def table : Type := list (uword × ℕ) def switch_target (n : uword) (dfl : ℕ) : table → ℕ | [] := dfl | ((key, action) :: rem) := if n = key then action else switch_target rem def switch_target' (n : uword) (dfl : ℕ) (tbl : list (ℤ × ℕ)) : ℕ := switch_target n dfl $ tbl.map (λ⟨a, b⟩, (repr a, b)) /- Multi-way branches are translated to comparison trees. Each node of the tree performs either - an equality against one of the keys; - or a "less than" test against one of the keys; - or a computed branch (jump table) against a range of key values. -/ inductive comptree : Type | CTaction {} (act : ℕ) | CTifeq (key : uword) (act : ℕ) (cne : comptree) | CTiflt (key : uword) (clt : comptree) (cge : comptree) | CTjumptable (ofs sz : uword) (acts : list ℕ) (h : (sz:ℕ) ≤ acts.length) (cother : comptree) open comptree def comptree_match (n : uword) : comptree → option ℕ | (CTaction act) := some act | (CTifeq key act t') := if n = key then some act else comptree_match t' | (CTiflt key t1 t2) := if n < key then comptree_match t1 else comptree_match t2 | (CTjumptable ofs sz tbl sl t') := let delta := n - ofs in if h : delta < sz then some (list.nth_le tbl (unsigned delta) (lt_of_lt_of_le h sl)) else comptree_match t' def comptree_match' (n : uword) (dfl : ℕ) (t : comptree) : ℕ := (comptree_match n t).get_or_else dfl /- The translation from a table to a comparison tree is performed by untrusted Caml code (function [compile_switch] in file [RTLgenaux.ml]). In Coq, we validate a posteriori the result of this function. In other terms, we now develop and prove correct Coq functions that take a table and a comparison tree, and check that their semantics are equivalent. -/ def split_lt (pivot : uword) (cases : table) : table × table := cases.partition (λ e, e.1 < pivot) def split_eq (pivot : uword) : table → option ℕ × table | [] := (none, []) | ((key, act) :: rem) := let (same, others) := split_eq rem in if key = pivot then (some act, others) else (same, (key, act) :: others) def split_between (ofs sz : uword) : table → PTree ℕ × table | [] := (∅, []) | ((key, act) :: rem) := let (inside, outside) := split_between rem in if key - ofs < sz then (PTree.set (pos_num.of_nat_succ key) act inside, outside) else (inside, (key, act) :: outside) def refine_low_bound (v lo : uword) := if v = lo then lo + 1 else lo def refine_high_bound (v hi : uword) := if v = hi then hi - 1 else hi def validate_jumptable (dfl : ℕ) (cases : PTree ℕ) : Π (tbl : list ℕ) (n : uword), semidecidable (∀ (v : uword) h, tbl.nth_le (unsigned (v - n)) h = cases.get_or (pos_num.of_nat_succ v) dfl) | [] n := semidecidable.success $ λ v h, absurd h (nat.not_lt_zero _) | (act :: rem) n := semidecidable.bind (act = cases.get_or (pos_num.of_nat_succ n) dfl) $ λae, @semidecidable.bind _ _ (validate_jumptable rem (n + 1)) $ λIH, semidecidable.success $ show ∀ (v : uword) h, list.nth_le (act :: rem) (unsigned (v - n)) h = PTree.get_or (pos_num.of_nat_succ ↑v) cases dfl, begin intro v, ginduction unsigned (v - n) with u; rw u; dsimp [list.nth_le]; intro h, { note vn : v = n := eq_of_sub_eq_zero (unsigned_eq.2 $ eq.trans u unsigned_zero.symm), rw vn, exact ae }, { assert va : unsigned (v - (n + 1)) = a, { rw [-sub_sub, sub_unsigned, unsigned_one, u, -int.coe_nat_sub, unsigned_repr], refl, { change a ≤ _, apply nat.le_of_succ_le, rw -u, apply unsigned_range_2 }, { apply nat.succ_pos } }, note : ∀ h, list.nth_le rem (unsigned (v - (n + 1))) h = PTree.get_or (pos_num.of_nat_succ ↑v) cases dfl := IH v, rw va at this, apply this } end def table_tree_agree' (dfl : ℕ) (cases : table) (t : comptree) (lo hi : uword) : Prop := ∀ ⦃n⦄, lo ≤ n → n ≤ hi → switch_target n dfl cases = comptree_match' n dfl t def table_tree_agree (dfl : ℕ) (cases : table) (t : comptree) : Prop := ∀ ⦃n⦄, switch_target n dfl cases = comptree_match' n dfl t lemma split_eq_prop (dfl : ℕ) {pivot cases} (v) : ∀ ⦃optact cases'⦄, split_eq pivot cases = (optact, cases') → switch_target v dfl cases = (if v = pivot then optact.get_or_else dfl else switch_target v dfl cases') := sorry' lemma split_lt_prop (dfl : ℕ) {pivot cases} (v) : ∀ ⦃lcases rcases⦄, split_lt pivot cases = (lcases, rcases) → switch_target v dfl cases = (if v < pivot then switch_target v dfl lcases else switch_target v dfl rcases) := sorry' lemma split_between_prop (dfl : ℕ) (v) {ofs sz} : ∀ {cases} ⦃inside outside⦄, split_between ofs sz cases = (inside, outside) → switch_target v dfl cases = (if v - ofs < sz then PTree.get_or (pos_num.of_nat_succ v) inside dfl else switch_target v dfl outside) := sorry' def validate (dfl : ℕ) : Π (cases : table) (t : comptree) (lo hi : uword), semidecidable (table_tree_agree' dfl cases t lo hi) | [] (CTaction act) lo hi := semidecidable.bind (dfl = act) $ λh, semidecidable.success $ λ n nl nh, h | ((key1, act1) :: _) (CTaction act) lo hi := semidecidable.bind (key1 = lo ∧ lo = hi ∧ act1 = act) $ λ⟨kl, lh, aa⟩, semidecidable.success $ λ n nl nh, begin dsimp [switch_target], rw if_pos, exact aa, rw [kl], rw -lh at nh, exact le_antisymm nh nl end | cases (CTifeq pivot act t') lo hi := match _, rfl : ∀ x, split_eq pivot cases = x → _ with | (none, _), _ := semidecidable.fail | (some act', others), se := semidecidable.bind (act' = act) $ λaa, @semidecidable.bind _ _ (validate others t' (refine_low_bound pivot lo) (refine_high_bound pivot hi)) $ λIH, semidecidable.success $ show table_tree_agree' dfl cases (CTifeq pivot act t') lo hi, begin rw aa at se, intros n nl nh, rw [split_eq_prop _ dfl n se], by_cases n = pivot with np; simp [np, option.get_or_else, comptree_match', comptree_match], apply IH, { dsimp [refine_low_bound], by_cases pivot = lo with pl; simp [pl], { rw pl at np, exact uword.succ_le_of_lt (lt_of_le_of_ne nl (ne.symm np)) }, { exact nl } }, { dsimp [refine_high_bound], by_cases pivot = hi with ph; simp [ph], { rw ph at np, exact uword.le_pred_of_lt (lt_of_le_of_ne nh np) }, { exact nh } } end end | cases (CTiflt pivot t1 t2) lo hi := match _, rfl : ∀ x, split_lt pivot cases = x → _ with | (lcases, rcases), sl := @semidecidable.bind _ _ (validate lcases t1 lo (pivot - 1)) $ λL, @semidecidable.bind _ _ (validate rcases t2 pivot hi) $ λR, semidecidable.success $ show table_tree_agree' dfl cases (CTiflt pivot t1 t2) lo hi, begin intros n nl nh, rw [split_lt_prop _ dfl n sl], by_cases (n < pivot) with lp; simp [lp, comptree_match', comptree_match], exact L nl (uword.le_pred_of_lt lp), exact R (le_of_not_gt lp) nh, end end | cases (CTjumptable ofs sz tbl h t') lo hi := match _, rfl : ∀ x, split_between ofs sz cases = x → _ with | (inside, outside), sb := @semidecidable.bind _ _ (validate_jumptable dfl inside tbl ofs) $ λI, @semidecidable.bind _ _ (validate outside t' lo hi) $ λO, semidecidable.success $ show table_tree_agree' dfl cases (CTjumptable ofs sz tbl h t') lo hi, begin intros n nl nh, rw [split_between_prop _ dfl n sb], dsimp only [comptree_match', comptree_match], cases (by apply_instance : decidable (n - ofs < sz)) with ns ns; dsimp only [ite, dite, option.get_or_else], exact O nl nh, { rw I } end end def validate_switch (dfl : ℕ) (cases : table) (t : comptree) : semidecidable (table_tree_agree dfl cases t) := begin refine @semidecidable.of_imp _ _ _ (validate _ dfl cases t 0 (repr (max_unsigned wordsize))), intros h n, apply h (uword.zero_le _), unfold has_le.le leu, rw unsigned_repr, { apply unsigned_range_2 }, { apply le_refl } end /- Caml code for compile_switch module ZSet = Set.Make(Z) let normalize_table tbl = let rec norm keys accu = function | [] -> (accu, keys) | (key, act) :: rem -> if ZSet.mem key keys then norm keys accu rem else norm (ZSet.add key keys) ((key, act) :: accu) rem in norm ZSet.empty [] tbl let compile_switch_as_tree modulus default tbl = let sw = Array.of_list tbl in Array.stable_sort (fun (n1, _) (n2, _) -> Z.compare n1 n2) sw; let rec build lo hi minval maxval = match hi - lo with | 0 -> CTaction default | 1 -> let (key, act) = sw.(lo) in if Z.sub maxval minval = Z.zero then CTaction act else CTifeq(key, act, CTaction default) | 2 -> let (key1, act1) = sw.(lo) and (key2, act2) = sw.(lo+1) in CTifeq(key1, act1, if Z.sub maxval minval = Z.one then CTaction act2 else CTifeq(key2, act2, CTaction default)) | 3 -> let (key1, act1) = sw.(lo) and (key2, act2) = sw.(lo+1) and (key3, act3) = sw.(lo+2) in CTifeq(key1, act1, CTifeq(key2, act2, if Z.sub maxval minval = Z.of_uint 2 then CTaction act3 else CTifeq(key3, act3, CTaction default))) | _ -> let mid = (lo + hi) / 2 in let (pivot, _) = sw.(mid) in CTiflt(pivot, build lo mid minval (Z.sub pivot Z.one), build mid hi pivot maxval) in build 0 (Array.length sw) Z.zero modulus let compile_switch_as_jumptable default cases minkey maxkey = let tblsize = 1 + Z.to_int (Z.sub maxkey minkey) in assert (tblsize >= 0 && tblsize <= Sys.max_array_length); let tbl = Array.make tblsize default in List.iter (fun (key, act) -> let pos = Z.to_int (Z.sub key minkey) in tbl.(pos) <- act) cases; CTjumptable(minkey, Z.of_uint tblsize, Array.to_list tbl, CTaction default) let dense_enough (numcases: int) (minkey: Z.t) (maxkey: Z.t) = let span = Z.sub maxkey minkey in assert (Z.ge span Z.zero); let tree_size = Z.mul (Z.of_uint 4) (Z.of_uint numcases) and table_size = Z.add (Z.of_uint 8) span in numcases >= 7 (* small jump tables are always less efficient *) && Z.le table_size tree_size && Z.lt span (Z.of_uint Sys.max_array_length) let compile_switch modulus default table = let (tbl, keys) = normalize_table table in if ZSet.is_empty keys then CTaction default else begin let minkey = ZSet.min_elt keys and maxkey = ZSet.max_elt keys in if dense_enough (List.length tbl) minkey maxkey then compile_switch_as_jumptable default tbl minkey maxkey else compile_switch_as_tree modulus default tbl end -/ end end switch
e5bc6a84bee07a286dceee6f346d13e70f3ce03c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/with_options.lean
7b6bbb380541978dc2fec8c6111e0511047436db
[ "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
429
lean
example {A : Type} (a b c : A) : a = b → b = c → a = c := begin intro h₁ h₂, with_options [pp.implicit true, pp.notation false] state; state, with_options [pp.all true, pp.max_depth 1] state, with_options [pp.notation false] state, with_options [pp.notation false] (state; state), substvars end example {A : Type} (a b c : A) : a = b → b = c → a = c := begin intros, with_options [] id, -- error end
edb445a06332e04fc629355f35b4fd85ab06bc65
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/meta/expr.lean
45f0f5a58f28d4baaf0ee3d105b631b16ef0ffd7
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
41,955
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs import data.option.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind @[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α := ⟨λ b, pexpr.of_expr (reflect b)⟩ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxiliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxiliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name. -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- Update the last component of a name. -/ def update_last (f : string → string) : name → name | (mk_string s n) := mk_string (f s) n | n := n /-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`, either as prefix or as suffix (specified by `is_prefix`), separated by `_`. Used by `simps_add_projections`. -/ def append_to_last (nm : name) (s : string) (is_prefix : bool) : name := nm.update_last $ λ s', if is_prefix then s ++ "_" ++ s' else s' ++ "_" ++ s /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') /-- In surface Lean, we can write anonymous Π binders (i.e. binders where the argument is not named) using the function arrow notation: ```lean inductive test : Type | intro : unit → test ``` After elaboration, however, every binder must have a name, so Lean generates one. In the example, the binder in the type of `intro` is anonymous, so Lean gives it the name `ᾰ`: ```lean test.intro : ∀ (ᾰ : unit), test ``` When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc. Thus, when we want to know whether the user named a binder, we can check whether the name follows this scheme. Note, however, that this is not reliable. When the user writes (for whatever reason) ```lean inductive test : Type | intro : ∀ (ᾰ : unit), test ``` we cannot tell that the binder was, in fact, named. The function `name.is_likely_generated_binder_name` checks if a name is of the form `ᾰ`, `ᾰ_1`, etc. -/ library_note "likely generated binder names" /-- Check whether a simple name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_simple_name : string → bool | "ᾰ" := tt | n := match n.get_rest "ᾰ_" with | none := ff | some suffix := suffix.is_nat end /-- Check whether a name was likely generated by Lean to name an anonymous binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See note [likely generated binder names]. -/ meta def is_likely_generated_binder_name (n : name) : bool := match n with | mk_string s anonymous := is_likely_generated_binder_simple_name s | _ := ff end end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ 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 /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Implementation of `expr.mreplace`. -/ meta def mreplace_aux {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) : expr → ℕ → m expr | (app f x) n := option.mget_or_else (R (app f x) n) (do Rf ← mreplace_aux f n, Rx ← mreplace_aux x n, return $ app Rf Rx) | (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd) | (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n) (do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd) | (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n) (do Rty ← mreplace_aux ty n, Ra ← mreplace_aux a n, Rb ← mreplace_aux b n, return $ elet nm Rty Ra Rb) | e n := option.mget_or_else (R e n) (return e) /-- Monadic analogue of `expr.replace`. The `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where `n` is the number of binders above `e`. If `R s n` fails, the whole replacement fails. If `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit its subexpressions). If `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`. -/ meta def mreplace {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) (e : expr) : m expr := mreplace_aux R e 0 /-- Match a variable. -/ meta def match_var {elab} : expr elab → option ℕ | (var n) := some n | _ := none /-- Match a sort. -/ meta def match_sort {elab} : expr elab → option level | (sort u) := some u | _ := none /-- Match a constant. -/ meta def match_const {elab} : expr elab → option (name × list level) | (const n lvls) := some (n, lvls) | _ := none /-- Match a metavariable. -/ meta def match_mvar {elab} : expr elab → option (name × name × expr elab) | (mvar unique pretty type) := some (unique, pretty, type) | _ := none /-- Match a local constant. -/ meta def match_local_const {elab} : expr elab → option (name × name × binder_info × expr elab) | (local_const unique pretty bi type) := some (unique, pretty, bi, type) | _ := none /-- Match an application. -/ meta def match_app {elab} : expr elab → option (expr elab × expr elab) | (app t u) := some (t, u) | _ := none /-- Match an application of `coe_fn`. -/ meta def match_app_coe_fn : expr → option (expr × expr × expr × expr) | (app `(@coe_fn %%α %%inst %%fexpr) x) := some (α, inst, fexpr, x) | _ := none /-- Match an abstraction. -/ meta def match_lam {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (lam var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a Π type. -/ meta def match_pi {elab} : expr elab → option (name × binder_info × expr elab × expr elab) | (pi var_name bi type body) := some (var_name, bi, type, body) | _ := none /-- Match a let. -/ meta def match_elet {elab} : expr elab → option (name × expr elab × expr elab × expr elab) | (elet var_name type assignment body) := some (var_name, type, assignment, body) | _ := none /-- Match a macro. -/ meta def match_macro {elab} : expr elab → option (macro_def × list (expr elab)) | (macro df args) := some (df, args) | _ := none /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Get the universe levels of a `const` expression -/ meta def univ_levels : expr → list level | (const n ls) := ls | _ := [] /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ 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 /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns the set of all local constants in an expression. -/ meta def list_local_consts' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es) /-- Returns the unique names of all local constants in an expression. -/ meta def list_local_const_unique_names (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns the set of all meta-variables in an expression. -/ meta def list_meta_vars' (e : expr) : expr_set := e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Returns true if `e` contains a `sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr × name_set) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- Repeatedly apply `expr.subst`. -/ meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxiliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxiliary defintion for `get_app_fn_args`. -/ 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) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ 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 /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the resulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file` Use `environment.in_current_file` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
90081b622ee63a6a18d99d5a3299f0d9ce6a2f60
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/tauto.lean
a741253119b0c6481e4bdae2ff81a17de10ea7d9
[ "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
11,507
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.hint namespace tactic open expr open tactic.interactive ( casesm constructor_matching ) /-- find all assumptions of the shape `¬ (p ∧ q)` or `¬ (p ∨ q)` and replace them using de Morgan's law. -/ meta def distrib_not : tactic unit := do hs ← local_context, hs.for_each $ λ h, all_goals' $ iterate_at_most' 3 $ do h ← get_local h.local_pp_name, e ← infer_type h, match e with | `(¬ _ = _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ ≠ _) := replace h.local_pp_name ``(mt iff.to_eq %%h) | `(_ = _) := replace h.local_pp_name ``(eq.to_iff %%h) | `(¬ (_ ∧ _)) := replace h.local_pp_name ``(decidable.not_and_distrib'.mp %%h) <|> replace h.local_pp_name ``(decidable.not_and_distrib.mp %%h) | `(¬ (_ ∨ _)) := replace h.local_pp_name ``(not_or_distrib.mp %%h) | `(¬ ¬ _) := replace h.local_pp_name ``(decidable.of_not_not %%h) | `(¬ (_ → (_ : Prop))) := replace h.local_pp_name ``(decidable.not_imp.mp %%h) | `(¬ (_ ↔ _)) := replace h.local_pp_name ``(decidable.not_iff.mp %%h) | `(_ ↔ _) := replace h.local_pp_name ``(decidable.iff_iff_and_or_not_and_not.mp %%h) <|> replace h.local_pp_name ``(decidable.iff_iff_and_or_not_and_not.mp (%%h).symm) <|> () <$ tactic.cases h | `(_ → _) := replace h.local_pp_name ``(decidable.not_or_of_imp %%h) | _ := failed end /-! The following definitions maintain a path compression datastructure, i.e. a forest such that: - every node is the type of a hypothesis - there is a edge between two nodes only if they are provably equivalent - every edge is labelled with a proof of equivalence for its vertices - edges are added when normalizing propositions. -/ meta def tauto_state := ref $ expr_map (option (expr × expr)) meta def modify_ref {α : Type} (r : ref α) (f : α → α) := read_ref r >>= write_ref r ∘ f meta def add_refl (r : tauto_state) (e : expr) : tactic (expr × expr) := do m ← read_ref r, p ← mk_mapp `rfl [none,e], write_ref r $ m.insert e none, return (e,p) /-- If there exists a symmetry lemma that can be applied to the hypothesis `e`, store it. -/ meta def add_symm_proof (r : tauto_state) (e : expr) : tactic (expr × expr) := do env ← get_env, let rel := e.get_app_fn.const_name, some symm ← pure $ environment.symm_for env rel | add_refl r e, (do e' ← mk_meta_var `(Prop), iff_t ← to_expr ``(%%e = %%e'), (_,p) ← solve_aux iff_t (applyc `iff.to_eq ; () <$ split ; applyc symm), e' ← instantiate_mvars e', m ← read_ref r, write_ref r $ (m.insert e (e',p)).insert e' none, return (e',p) ) <|> add_refl r e meta def add_edge (r : tauto_state) (x y p : expr) : tactic unit := modify_ref r $ λ m, m.insert x (y,p) /-- Retrieve the root of the hypothesis `e` from the proof forest. If `e` has not been internalized, add it to the proof forest. -/ meta def root (r : tauto_state) : expr → tactic (expr × expr) | e := do m ← read_ref r, let record_e : tactic (expr × expr) := match e with | v@(expr.mvar _ _ _) := (do (e,p) ← get_assignment v >>= root, add_edge r v e p, return (e,p)) <|> add_refl r e | _ := add_refl r e end, some e' ← pure $ m.find e | record_e, match e' with | (some (e',p')) := do (e'',p'') ← root e', p'' ← mk_app `eq.trans [p',p''], add_edge r e e'' p'', pure (e'',p'') | none := prod.mk e <$> mk_mapp `rfl [none,some e] end /-- Given hypotheses `a` and `b`, build a proof that `a` is equivalent to `b`, applying congruence and recursing into arguments if `a` and `b` are applications of function symbols. -/ meta def symm_eq (r : tauto_state) : expr → expr → tactic expr | a b := do m ← read_ref r, (a',pa) ← root r a, (b',pb) ← root r b, (unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]) <|> do p ← match (a', b') with | (`(¬ %%a₀), `(¬ %%b₀)) := do p ← symm_eq a₀ b₀, p' ← mk_app `congr_arg [`(not),p], add_edge r a' b' p', return p' | (`(%%a₀ ∧ %%a₁), `(%%b₀ ∧ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg and %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ∨ %%a₁), `(%%b₀ ∨ %%b₁)) := do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg or %%p₀) %%p₁), add_edge r a' b' p', return p' | (`(%%a₀ ↔ %%a₁), `(%%b₀ ↔ %%b₁)) := (do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← to_expr ``(congr (congr_arg iff %%p₀) %%p₁), add_edge r a' b' p', return p') <|> do p₀ ← symm_eq a₀ b₁, p₁ ← symm_eq a₁ b₀, p' ← to_expr ``(eq.trans (congr (congr_arg iff %%p₀) %%p₁) (iff.to_eq iff.comm ) ), add_edge r a' b' p', return p' | (`(%%a₀ → %%a₁), `(%%b₀ → %%b₁)) := if ¬ a₁.has_var ∧ ¬ b₁.has_var then do p₀ ← symm_eq a₀ b₀, p₁ ← symm_eq a₁ b₁, p' ← mk_app `congr_arg [`(implies),p₀,p₁], add_edge r a' b' p', return p' else unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a] | (_, _) := (do guard $ a'.get_app_fn.is_constant ∧ a'.get_app_fn.const_name = b'.get_app_fn.const_name, (a'',pa') ← add_symm_proof r a', guard $ a'' =ₐ b', pure pa' ) end, p' ← mk_eq_trans pa p, add_edge r a' b' p', mk_eq_symm pb >>= mk_eq_trans p' meta def find_eq_type (r : tauto_state) : expr → list expr → tactic (expr × expr) | e [] := failed | e (H :: Hs) := do t ← infer_type H, (prod.mk H <$> symm_eq r e t) <|> find_eq_type e Hs private meta def contra_p_not_p (r : tauto_state) : list expr → list expr → tactic unit | [] Hs := failed | (H1 :: Rs) Hs := do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf, (do a ← match_not t, (H2,p) ← find_eq_type r a Hs, H2 ← to_expr ``( (%%p).mpr %%H2 ), tgt ← target, pr ← mk_app `absurd [tgt, H2, H1], tactic.exact pr) <|> contra_p_not_p Rs Hs meta def contradiction_with (r : tauto_state) : tactic unit := contradiction <|> do tactic.try intro1, ctx ← local_context, contra_p_not_p r ctx ctx meta def contradiction_symm := using_new_ref (native.rb_map.mk _ _) contradiction_with meta def assumption_with (r : tauto_state) : tactic unit := do { ctx ← local_context, t ← target, (H,p) ← find_eq_type r t ctx, mk_eq_mpr p H >>= tactic.exact } <|> fail "assumption tactic failed" meta def assumption_symm := using_new_ref (native.rb_map.mk _ _) assumption_with /-- Configuration options for `tauto`. If `classical` is `tt`, runs `classical` before the rest of `tauto`. `closer` is run on any remaining subgoals left by `tauto_core; basic_tauto_tacs`. -/ meta structure tauto_cfg := (classical : bool := ff) (closer : tactic unit := pure ()) meta def tautology (cfg : tauto_cfg := {}) : tactic unit := focus1 $ let basic_tauto_tacs : list (tactic unit) := [reflexivity, solve_by_elim, constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _),``(true)]], tauto_core (r : tauto_state) : tactic unit := do try (contradiction_with r); try (assumption_with r); repeat (do gs ← get_goals, repeat (() <$ tactic.intro1); distrib_not; casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)]; try (contradiction_with r); try (target >>= match_or >> refine ``( or_iff_not_imp_left.mpr _)); try (target >>= match_or >> refine ``( or_iff_not_imp_right.mpr _)); repeat (() <$ tactic.intro1); constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)]; try (assumption_with r), gs' ← get_goals, guard (gs ≠ gs') ) in do when cfg.classical classical, using_new_ref (expr_map.mk _) tauto_core; repeat (first basic_tauto_tacs); cfg.closer, done namespace interactive local postfix `?`:9001 := optional setup_tactic_parser /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variant `tautology!` uses the law of excluded middle. `tautology {closer := tac}` will use `tac` on any subgoals created by `tautology` that it is unable to solve before failing. -/ meta def tautology (c : parse $ (tk "!")?) (cfg : tactic.tauto_cfg := {}) := tactic.tautology $ { classical := c.is_some, ..cfg } -- Now define a shorter name for the tactic `tautology`. /-- `tauto` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variant `tauto!` uses the law of excluded middle. `tauto {closer := tac}` will use `tac` on any subgoals created by `tauto` that it is unable to solve before failing. -/ meta def tauto (c : parse $ (tk "!")?) (cfg : tactic.tauto_cfg := {}) : tactic unit := tautology c cfg add_hint_tactic "tauto" /-- This tactic (with shorthand `tauto`) breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it either closes the goal or raises an error. The variants `tautology!` and `tauto!` use the law of excluded middle. For instance, one can write: ```lean example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto ``` and the decidability assumptions can be dropped if `tauto!` is used instead of `tauto`. `tauto {closer := tac}` will use `tac` on any subgoals created by `tauto` that it is unable to solve before failing. -/ add_tactic_doc { name := "tautology", category := doc_category.tactic, decl_names := [`tactic.interactive.tautology, `tactic.interactive.tauto], tags := ["logic", "decision procedure"] } end interactive end tactic
7180daefee4bae79d387f30510c3e3483cc51609
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love08_operational_semantics_demo.lean
f953a54c231273b98c7d6b42817ec6d328b38581
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,026
lean
import .lovelib /- # LoVe Demo 8: Operational Semantics In this and the next two lectures, we will see how to use Lean to specify the syntax and semantics of programming languages and to reason about the semantics. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Formal Semantics A formal semantics helps specify and reason about the programming language itself, and about individual programs. It can form the basis of verified compilers, interpreters, verifiers, static analyzers, type checkers, etc. Without formal proofs, these tools are **almost always wrong**. In this area, proof assistants are widely used. Every year, about 10-20% of POPL papers are partially or totally formalized. Reasons for this success: * Little machinery (background libraries, tactics) is needed to get started, beyond inductive types and predicates and recursive functions. * The proofs tend to have lots of cases, which is a good match for computers. * Proof assistants keep track of what needs to be changed when as extend the programming language with more features. Case in point: WebAssembly. To quote Conrad Watt (with some abbreviations): We have produced a full Isabelle mechanisation of the core execution semantics and type system of the WebAssembly language. To complete this proof, **several deficiencies** in the official WebAssembly specification, uncovered by our proof and modelling work, needed to be corrected. In some cases, these meant that the type system was **originally unsound**. We have maintained a constructive dialogue with the working group, verifying new features as they are added. In particular, the mechanism by which a WebAssembly implementation interfaces with its host environment was not formally specified in the working group's original paper. Extending our mechanisation to model this feature revealed a deficiency in the WebAssembly specification that **sabotaged the soundness** of the type system. ## A Minimalistic Imperative Language __WHILE__ is a minimalistic imperative language with the following grammar: S ::= skip -- no-op | x := a -- assignment | S ; S -- sequential composition | if b then S else S -- conditional statement | while b do S -- while loop where `S` stands for a statement (also called command or program), `x` for a variable, `a` for an arithmetic expression, and `b` for a Boolean expression. -/ inductive stmt : Type | skip : stmt | assign : string → (state → ℕ) → stmt | seq : stmt → stmt → stmt | ite : (state → Prop) → stmt → stmt → stmt | while : (state → Prop) → stmt → stmt infixr ` ;; ` : 90 := stmt.seq /- In our grammar, we deliberately leave the syntax of arithmetic and Boolean expressions unspecified. In Lean, we have the choice: * We could use a type such as `aexp` from lecture 1 and similarly for Boolean expressions. * Supposing a state `s` is a function from variable names to values (`string → ℕ`), we could decide that an arithmetic expression is simply a function from states to natural numbers (`state → ℕ`) and a Boolean expression is a predicate (`state → Prop` or `state → bool`). This corresponds to the difference between deep and shallow embeddings: * A __deep embedding__ of some syntax (expression, formula, program, etc.) consists of an abstract syntax tree specified in the proof assistant (e.g., `aexp`) with a semantics (e.g., `eval`). * In contrast, a __shallow embedding__ simply reuses the corresponding mechanisms from the logic (e.g., λ-terms, functions and predicate types). A deep embedding allows us to reason about the syntax (and its semantics). A shallow embedding is more lightweight, because we can use it directly, without having to define a semantics. We will use a deep embedding of programs (which we find interesting), and shallow embeddings of assignments and Boolean expressions (which we find boring). Examples: `λs : state, s "x" + s "y" + 1` -- x + y + 1 `λs : state, s "a" ≠ s "b"` -- a ≠ b ## Big-Step Semantics An __operational semantics__ corresponds to an idealized interpreter (specified in a Prolog-like language). Two main variants: * big-step semantics; * small-step semantics. In a __big-step semantics__ (also called __natural semantics__), judgments have the form `(S, s) ⟹ t`: Starting in a state `s`, executing `S` terminates in the state `t`. Example: `(x := x + y; y := 0, [x ↦ 3, y ↦ 5]) ⟹ [x ↦ 8, y ↦ 0]` Derivation rules: ——————————————— Skip (skip, s) ⟹ s ——————————————————————————— Asn (x := a, s) ⟹ s[x ↦ s(a)] (S, s) ⟹ t (T, t) ⟹ u ——————————————————————————— Seq (S; T, s) ⟹ u (S, s) ⟹ t ————————————————————————————— If-True if s(b) is true (if b then S else T, s) ⟹ t (T, s) ⟹ t ————————————————————————————— If-False if s(b) is false (if b then S else T, s) ⟹ t (S, s) ⟹ t (while b do S, t) ⟹ u —————————————————————————————————————— While-True if s(b) is true (while b do S, s) ⟹ u ————————————————————————— While-False if s(b) is false (while b do S, s) ⟹ s Above, `s(e)` denotes the value of expression `e` in state `s`. In Lean, the judgment corresponds to an inductive predicate, and the derivation rules correspond to the predicate's introduction rules. Using an inductive predicate as opposed to a recursive function allows us to cope with nontermination (e.g., a diverging `while`) and nondeterminism (e.g., multithreading). -/ inductive big_step : stmt × state → state → Prop | skip {s} : big_step (stmt.skip, s) s | assign {x a s} : big_step (stmt.assign x a, s) (s{x ↦ a s}) | seq {S T s t u} (hS : big_step (S, s) t) (hT : big_step (T, t) u) : big_step (S ;; T, s) u | ite_true {b : state → Prop} {S T s t} (hcond : b s) (hbody : big_step (S, s) t) : big_step (stmt.ite b S T, s) t | ite_false {b : state → Prop} {S T s t} (hcond : ¬ b s) (hbody : big_step (T, s) t) : big_step (stmt.ite b S T, s) t | while_true {b : state → Prop} {S s t u} (hcond : b s) (hbody : big_step (S, s) t) (hrest : big_step (stmt.while b S, t) u) : big_step (stmt.while b S, s) u | while_false {b : state → Prop} {S s} (hcond : ¬ b s) : big_step (stmt.while b S, s) s infix ` ⟹ ` : 110 := big_step /- ## Properties of the Big-Step Semantics Equipped with a big-step semantics, we can * prove properties of the programming language, such as **equivalence proofs** between programs and **determinism**; * reason about **concrete programs**, proving theorems relating final states `t` with initial states `s`. -/ lemma big_step_deterministic {S s l r} (hl : (S, s) ⟹ l) (hr : (S, s) ⟹ r) : l = r := begin induction' hl, case skip { cases' hr, refl }, case assign { cases' hr, refl }, case seq : S T s t l hS hT ihS ihT { cases' hr with _ _ _ _ _ _ _ t' _ hS' hT', cases' ihS hS', cases' ihT hT', refl }, case ite_true : b S T s t hb hS ih { cases' hr, { apply ih hr }, { cc } }, case ite_false : b S T s t hb hT ih { cases' hr, { cc }, { apply ih hr } }, case while_true : b S s t u hb hS hw ihS ihw { cases' hr, { cases' ihS hr, cases' ihw hr_1, refl }, { cc } }, { cases' hr, { cc }, { refl } } end lemma big_step_terminates {S s} : ∃t, (S, s) ⟹ t := sorry -- unprovable lemma big_step_doesnt_terminate {S s t} : ¬ (stmt.while (λ_, true) S, s) ⟹ t := begin intro hw, induction' hw, case while_true { assumption }, case while_false { cc } end /- We can define inversion rules about the big-step semantics: -/ @[simp] lemma big_step_skip_iff {s t} : (stmt.skip, s) ⟹ t ↔ t = s := begin apply iff.intro, { intro h, cases' h, refl }, { intro h, rw h, exact big_step.skip } end @[simp] lemma big_step_assign_iff {x a s t} : (stmt.assign x a, s) ⟹ t ↔ t = s{x ↦ a s} := begin apply iff.intro, { intro h, cases' h, refl }, { intro h, rw h, exact big_step.assign } end @[simp] lemma big_step_seq_iff {S T s t} : (S ;; T, s) ⟹ t ↔ (∃u, (S, s) ⟹ u ∧ (T, u) ⟹ t) := begin apply iff.intro, { intro h, cases' h, apply exists.intro, apply and.intro; assumption }, { intro h, cases' h, cases' h, apply big_step.seq; assumption } end @[simp] lemma big_step_ite_iff {b S T s t} : (stmt.ite b S T, s) ⟹ t ↔ (b s ∧ (S, s) ⟹ t) ∨ (¬ b s ∧ (T, s) ⟹ t) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, cc }, { apply or.intro_right, cc } }, { intro h, cases' h; cases' h, { apply big_step.ite_true; assumption }, { apply big_step.ite_false; assumption } } end lemma big_step_while_iff {b S s u} : (stmt.while b S, s) ⟹ u ↔ (∃t, b s ∧ (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) ∨ (¬ b s ∧ u = s) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, apply exists.intro t, cc }, { apply or.intro_right, cc } }, { intro h, cases' h, case inl { cases' h with t h, cases' h with hb h, cases' h with hS hwhile, exact big_step.while_true hb hS hwhile }, case inr { cases' h with hb hus, rw hus, exact big_step.while_false hb } } end lemma big_step_while_true_iff {b : state → Prop} {S s u} (hcond : b s) : (stmt.while b S, s) ⟹ u ↔ (∃t, (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) := by rw big_step_while_iff; simp [hcond] @[simp] lemma big_step_while_false_iff {b : state → Prop} {S s t} (hcond : ¬ b s) : (stmt.while b S, s) ⟹ t ↔ t = s := by rw big_step_while_iff; simp [hcond] /- ## Small-Step Semantics A big-step semantics * does not let us reason about intermediate states; * does not let us express nontermination or interleaving (for multithreading). __Small-step semantics__ (also called __structural operational semantics__) solve the above issues. A judgment has the form `(S, s) ⇒ (T, t)`: Starting in a state `s`, executing one step of `S` leaves us in the state `t`, with the program `T` remaining to be executed. An execution is a finite or infinite chain `(S₀, s₀) ⇒ (S₁, s₁) ⇒ …`. A pair `(S, s)` is called a __configuration__. It is __final__ if no transition of the form `(S, s) ⇒ _` is possible. Example: `(x := x + y; y := 0, [x ↦ 3, y ↦ 5])` `⇒ (skip; y := 0, [x ↦ 8, y ↦ 5])` `⇒ (y := 0, [x ↦ 8, y ↦ 5])` `⇒ (skip, [x ↦ 8, y ↦ 0])` Derivation rules: ————————————————————————————————— Asn (x := a, s) ⇒ (skip, s[x ↦ s(a)]) (S, s) ⇒ (S', s') ———-————————————————————— Seq-Step (S ; T, s) ⇒ (S' ; T, s') —————————————————————— Seq-Skip (skip ; S, s) ⇒ (S, s) ———————————————————————————————— If-True if s(b) is true (if b then S else T, s) ⇒ (S, s) ———————————————————————————————— If-False if s(b) is false (if b then S else T, s) ⇒ (T, s) ——————————————————————————————————————————————————————————————— While (while b do S, s) ⇒ (if b then (S ; while b do S) else skip, s) There is no rule for `skip` (why?). -/ inductive small_step : stmt × state → stmt × state → Prop | assign {x a s} : small_step (stmt.assign x a, s) (stmt.skip, s{x ↦ a s}) | seq_step {S S' T s s'} (hS : small_step (S, s) (S', s')) : small_step (S ;; T, s) (S' ;; T, s') | seq_skip {T s} : small_step (stmt.skip ;; T, s) (T, s) | ite_true {b : state → Prop} {S T s} (hcond : b s) : small_step (stmt.ite b S T, s) (S, s) | ite_false {b : state → Prop} {S T s} (hcond : ¬ b s) : small_step (stmt.ite b S T, s) (T, s) | while {b : state → Prop} {S s} : small_step (stmt.while b S, s) (stmt.ite b (S ;; stmt.while b S) stmt.skip, s) infixr ` ⇒ ` := small_step infixr ` ⇒* ` : 100 := star small_step /- Equipped with a small-step semantics, we can **define** a big-step semantics: `(S, s) ⟹ t` if and only if `(S, s) ⇒* (skip, t)` where `r*` denotes the reflexive transitive closure of a relation `r`. Alternatively, if we have already defined a big-step semantics, we can **prove** the above equivalence theorem to validate our definitions. The main disadvantage of small-step semantics is that we now have two relations, `⇒` and `⇒*`, and reasoning tends to be more complicated. ## Properties of the Small-Step Semantics We can prove that a configuration `(S, s)` is final if and only if `S = skip`. This ensures that we have not forgotten a derivation rule. -/ lemma small_step_final (S s) : (¬ ∃T t, (S, s) ⇒ (T, t)) ↔ S = stmt.skip := begin induction' S, case skip { simp, intros T t hstep, cases' hstep }, case assign : x a { simp, apply exists.intro stmt.skip, apply exists.intro (s{x ↦ a s}), exact small_step.assign }, case seq : S T ihS ihT { simp, cases' classical.em (S = stmt.skip), case inl { rw h, apply exists.intro T, apply exists.intro s, exact small_step.seq_skip }, case inr { simp [h, auto.not_forall_eq, auto.not_not_eq] at ihS, cases' ihS s with S' hS', cases' hS' with s' hs', apply exists.intro (S' ;; T), apply exists.intro s', exact small_step.seq_step hs' } }, case ite : b S T ihS ihT { simp, cases' classical.em (b s), case inl { apply exists.intro S, apply exists.intro s, exact small_step.ite_true h }, case inr { apply exists.intro T, apply exists.intro s, exact small_step.ite_false h } }, case while : b S ih { simp, apply exists.intro (stmt.ite b (S ;; stmt.while b S) stmt.skip), apply exists.intro s, exact small_step.while } end lemma small_step_deterministic {S s Ll Rr} (hl : (S, s) ⇒ Ll) (hr : (S, s) ⇒ Rr) : Ll = Rr := begin induction' hl, case assign : x a s { cases' hr, refl }, case seq_step : S S₁ T s s₁ hS₁ ih { cases' hr, case seq_step : S S₂ _ _ s₂ hS₂ { have hSs₁₂ := ih hS₂, cc }, case seq_skip { cases' hS₁ } }, case seq_skip : T s { cases' hr, { cases' hr }, { refl } }, case ite_true : b S T s hcond { cases' hr, case ite_true { refl }, case ite_false { cc } }, case ite_false : b S T s hcond { cases' hr, case ite_true { cc }, case ite_false { refl } }, case while : b S s { cases' hr, refl } end /- We can define inversion rules also about the small-step semantics. Here are three examples: -/ lemma small_step_skip {S s t} : ¬ ((stmt.skip, s) ⇒ (S, t)) := by intro h; cases' h @[simp] lemma small_step_seq_iff {S T s Ut} : (S ;; T, s) ⇒ Ut ↔ (∃S' t, (S, s) ⇒ (S', t) ∧ Ut = (S' ;; T, t)) ∨ (S = stmt.skip ∧ Ut = (T, s)) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, apply exists.intro S', apply exists.intro s', cc }, { apply or.intro_right, cc } }, { intro h, cases' h, { cases' h, cases' h, cases' h, rw right, apply small_step.seq_step, assumption }, { cases' h, rw left, rw right, apply small_step.seq_skip } } end @[simp] lemma small_step_ite_iff {b S T s Us} : (stmt.ite b S T, s) ⇒ Us ↔ (b s ∧ Us = (S, s)) ∨ (¬ b s ∧ Us = (T, s)) := begin apply iff.intro, { intro h, cases' h, { apply or.intro_left, cc }, { apply or.intro_right, cc } }, { intro h, cases' h, { cases' h, rw right, apply small_step.ite_true, assumption }, { cases' h, rw right, apply small_step.ite_false, assumption } } end /- ### Equivalence of the Big-Step and the Small-Step Semantics (**optional**) A more important result is the connection between the big-step and the small-step semantics: `(S, s) ⟹ t ↔ (S, s) ⇒* (stmt.skip, t)` Its proof, given below, is beyond the scope of this course. -/ lemma star_small_step_seq {S T s u} (h : (S, s) ⇒* (stmt.skip, u)) : (S ;; T, s) ⇒* (stmt.skip ;; T, u) := begin apply star.lift (λSs, (prod.fst Ss ;; T, prod.snd Ss)) _ h, intros Ss Ss' h, cases' Ss, cases' Ss', apply small_step.seq_step, assumption end lemma star_small_step_of_big_step {S s t} (h : (S, s) ⟹ t) : (S, s) ⇒* (stmt.skip, t) := begin induction' h, case skip { refl }, case assign { exact star.single small_step.assign }, case seq : S T s t u hS hT ihS ihT { transitivity, exact star_small_step_seq ihS, apply star.head small_step.seq_skip ihT }, case ite_true : b S T s t hs hst ih { exact star.head (small_step.ite_true hs) ih }, case ite_false : b S T s t hs hst ih { exact star.head (small_step.ite_false hs) ih }, case while_true : b S s t u hb hS hw ihS ihw { exact (star.head small_step.while (star.head (small_step.ite_true hb) (star.trans (star_small_step_seq ihS) (star.head small_step.seq_skip ihw)))) }, case while_false : b S s hb { exact star.tail (star.single small_step.while) (small_step.ite_false hb) } end lemma big_step_of_small_step_of_big_step {S₀ S₁ s₀ s₁ s₂} (h₁ : (S₀, s₀) ⇒ (S₁, s₁)) : (S₁, s₁) ⟹ s₂ → (S₀, s₀) ⟹ s₂ := begin induction' h₁; simp [*, big_step_while_true_iff] {contextual := tt}, case seq_step { intros u hS' hT, apply exists.intro u, exact and.intro (ih hS') hT } end lemma big_step_of_star_small_step {S s t} : (S, s) ⇒* (stmt.skip, t) → (S, s) ⟹ t := begin generalize hSs : (S, s) = Ss, intro h, induction h using LoVe.rtc.star.head_induction_on with _ S's' h h' ih generalizing S s; cases' hSs, { exact big_step.skip }, { cases' S's' with S' s', apply big_step_of_small_step_of_big_step h, apply ih, refl } end lemma big_step_iff_star_small_step {S s t} : (S, s) ⟹ t ↔ (S, s) ⇒* (stmt.skip, t) := iff.intro star_small_step_of_big_step big_step_of_star_small_step /- ## Parallelism (**optional**) -/ inductive par_step : nat → list stmt × state → list stmt × state → Prop | intro {Ss Ss' S S' s s' i} (hi : i < list.length Ss) (hS : S = list.nth_le Ss i hi) (hs : (S, s) ⇒ (S', s')) (hS' : Ss' = list.update_nth Ss i S') : par_step i (Ss, s) (Ss', s') lemma par_step_diamond {i j Ss Ts Ts' s t t'} (hi : i < list.length Ss) (hj : j < list.length Ss) (hij : i ≠ j) (hT : par_step i (Ss, s) (Ts, t)) (hT' : par_step j (Ss, s) (Ts', t')) : ∃u Us, par_step j (Ts, t) (Us, u) ∧ par_step i (Ts', t') (Us, u) := sorry -- unprovable def stmt.W : stmt → set string | stmt.skip := ∅ | (stmt.assign x _) := {x} | (stmt.seq S T) := stmt.W S ∪ stmt.W T | (stmt.ite _ S T) := stmt.W S ∪ stmt.W T | (stmt.while _ S) := stmt.W S def exp.R {α : Type} : (state → α) → set string | f := {x | ∀s n, f (s{x ↦ n}) ≠ f s} def stmt.R : stmt → set string | stmt.skip := ∅ | (stmt.assign _ a) := exp.R a | (stmt.seq S T) := stmt.R S ∪ stmt.R T | (stmt.ite b S T) := exp.R b ∪ stmt.R S ∪ stmt.R T | (stmt.while b S) := exp.R b ∪ stmt.R S def stmt.V : stmt → set string | S := stmt.W S ∪ stmt.R S lemma par_step_diamond_VW_disjoint {i j Ss Ts Ts' s t t'} (hiS : i < list.length Ss) (hjT : j < list.length Ts) (hij : i ≠ j) (hT : par_step i (Ss, s) (Ts, t)) (hT' : par_step j (Ss, s) (Ts', t')) (hWV : stmt.W (list.nth_le Ss i hiS) ∩ stmt.V (list.nth_le Ts j hjT) = ∅) (hVW : stmt.V (list.nth_le Ss i hiS) ∩ stmt.W (list.nth_le Ts j hjT) = ∅) : ∃u Us, par_step j (Ts, t) (Us, u) ∧ par_step i (Ts', t') (Us, u) := sorry -- this should be provable end LoVe
39b63c5d192af3dfef944146c5b9e844dfeb72b2
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/int/order.lean
b2b8283141ce3aa3760a59d33ad6db60c91ff786
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
17,708
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad The order relation on the integers. We show that int is an instance of linear_comm_ordered_ring and transfer the results. -/ import .basic algebra.ordered_ring open nat open decidable open int eq.ops namespace int private definition nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false) protected definition le (a b : ℤ) : Prop := nonneg (b - a) definition int_has_le [instance] [reducible] [priority int.prio]: has_le int := has_le.mk int.le protected definition lt (a b : ℤ) : Prop := (a + 1) ≤ b definition int_has_lt [instance] [reducible] [priority int.prio]: has_lt int := has_lt.mk int.lt local attribute nonneg [reducible] private definition decidable_nonneg [instance] (a : ℤ) : decidable (nonneg a) := int.cases_on a _ _ definition decidable_le [instance] (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _ definition decidable_lt [instance] (a b : ℤ) : decidable (a < b) := decidable_nonneg _ private theorem nonneg.elim {a : ℤ} : nonneg a → ∃n : ℕ, a = n := int.cases_on a (take n H, exists.intro n rfl) (take n', false.elim) private theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial) theorem le.intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b := have n = b - a, from eq_add_neg_of_add_eq (begin rewrite [add.comm, H] end), -- !add.comm ▸ H), show nonneg (b - a), from this ▸ trivial theorem le.elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b := obtain (n : ℕ) (H1 : b - a = n), from nonneg.elim H, exists.intro n (!add.comm ▸ iff.mpr !add_eq_iff_eq_add_neg (H1⁻¹)) protected theorem le_total (a b : ℤ) : a ≤ b ∨ b ≤ a := or.imp_right (assume H : nonneg (-(b - a)), have -(b - a) = a - b, from !neg_sub, show nonneg (a - b), from this ▸ H) (nonneg_or_nonneg_neg (b - a)) theorem of_nat_le_of_nat_of_le {m n : ℕ} (H : #nat m ≤ n) : of_nat m ≤ of_nat n := obtain (k : ℕ) (Hk : m + k = n), from nat.le.elim H, le.intro (Hk ▸ (of_nat_add m k)⁻¹) theorem le_of_of_nat_le_of_nat {m n : ℕ} (H : of_nat m ≤ of_nat n) : (#nat m ≤ n) := obtain (k : ℕ) (Hk : of_nat m + of_nat k = of_nat n), from le.elim H, have m + k = n, from of_nat.inj (of_nat_add m k ⬝ Hk), nat.le.intro this theorem of_nat_le_of_nat_iff (m n : ℕ) : of_nat m ≤ of_nat n ↔ m ≤ n := iff.intro le_of_of_nat_le_of_nat of_nat_le_of_nat_of_le theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n := le.intro (show a + 1 + n = a + succ n, from calc a + 1 + n = a + (1 + n) : add.assoc ... = a + (n + 1) : by rewrite (int.add_comm 1 n) ... = a + succ n : rfl) theorem lt.intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b := H ▸ lt_add_succ a n theorem lt.elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b := obtain (n : ℕ) (Hn : a + 1 + n = b), from le.elim H, have a + succ n = b, from calc a + succ n = a + 1 + n : by rewrite [add.assoc, int.add_comm 1 n] ... = b : Hn, exists.intro n this theorem of_nat_lt_of_nat_iff (n m : ℕ) : of_nat n < of_nat m ↔ n < m := calc of_nat n < of_nat m ↔ of_nat n + 1 ≤ of_nat m : iff.refl ... ↔ of_nat (nat.succ n) ≤ of_nat m : of_nat_succ n ▸ !iff.refl ... ↔ nat.succ n ≤ m : of_nat_le_of_nat_iff ... ↔ n < m : iff.symm (lt_iff_succ_le _ _) theorem lt_of_of_nat_lt_of_nat {m n : ℕ} (H : of_nat m < of_nat n) : #nat m < n := iff.mp !of_nat_lt_of_nat_iff H theorem of_nat_lt_of_nat_of_lt {m n : ℕ} (H : #nat m < n) : of_nat m < of_nat n := iff.mpr !of_nat_lt_of_nat_iff H /- show that the integers form an ordered additive group -/ protected theorem le_refl (a : ℤ) : a ≤ a := le.intro (add_zero a) protected theorem le_trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := obtain (n : ℕ) (Hn : a + n = b), from le.elim H1, obtain (m : ℕ) (Hm : b + m = c), from le.elim H2, have a + of_nat (n + m) = c, from calc a + of_nat (n + m) = a + (of_nat n + m) : {of_nat_add n m} ... = a + n + m : (add.assoc a n m)⁻¹ ... = b + m : {Hn} ... = c : Hm, le.intro this protected theorem le_antisymm : ∀ {a b : ℤ}, a ≤ b → b ≤ a → a = b := take a b : ℤ, assume (H₁ : a ≤ b) (H₂ : b ≤ a), obtain (n : ℕ) (Hn : a + n = b), from le.elim H₁, obtain (m : ℕ) (Hm : b + m = a), from le.elim H₂, have a + of_nat (n + m) = a + 0, from calc a + of_nat (n + m) = a + (of_nat n + m) : by rewrite of_nat_add ... = a + n + m : by rewrite add.assoc ... = b + m : by rewrite Hn ... = a : by rewrite Hm ... = a + 0 : by rewrite add_zero, have of_nat (n + m) = of_nat 0, from add.left_cancel this, have n + m = 0, from of_nat.inj this, assert n = 0, from nat.eq_zero_of_add_eq_zero_right this, show a = b, from calc a = a + 0 : add_zero ... = a + n : by rewrite this ... = b : Hn protected theorem lt_irrefl (a : ℤ) : ¬ a < a := (suppose a < a, obtain (n : ℕ) (Hn : a + succ n = a), from lt.elim this, have a + succ n = a + 0, from Hn ⬝ !add_zero⁻¹, !succ_ne_zero (of_nat.inj (add.left_cancel this))) protected theorem ne_of_lt {a b : ℤ} (H : a < b) : a ≠ b := (suppose a = b, absurd (this ▸ H) (int.lt_irrefl b)) theorem le_of_lt {a b : ℤ} (H : a < b) : a ≤ b := obtain (n : ℕ) (Hn : a + succ n = b), from lt.elim H, le.intro Hn protected theorem lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (assume H, and.intro (le_of_lt H) (int.ne_of_lt H)) (assume H, have a ≤ b, from and.elim_left H, have a ≠ b, from and.elim_right H, obtain (n : ℕ) (Hn : a + n = b), from le.elim `a ≤ b`, have n ≠ 0, from (assume H' : n = 0, `a ≠ b` (!add_zero ▸ H' ▸ Hn)), obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero this, lt.intro (Hk ▸ Hn)) protected theorem le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) := iff.intro (assume H, by_cases (suppose a = b, or.inr this) (suppose a ≠ b, obtain (n : ℕ) (Hn : a + n = b), from le.elim H, have n ≠ 0, from (assume H' : n = 0, `a ≠ b` (!add_zero ▸ H' ▸ Hn)), obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero this, or.inl (lt.intro (Hk ▸ Hn)))) (assume H, or.elim H (assume H1, le_of_lt H1) (assume H1, H1 ▸ !int.le_refl)) theorem lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected theorem add_le_add_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b := obtain (n : ℕ) (Hn : a + n = b), from le.elim H, have H2 : c + a + n = c + b, from calc c + a + n = c + (a + n) : add.assoc c a n ... = c + b : {Hn}, le.intro H2 protected theorem add_lt_add_left {a b : ℤ} (H : a < b) (c : ℤ) : c + a < c + b := let H' := le_of_lt H in (iff.mpr (int.lt_iff_le_and_ne _ _)) (and.intro (int.add_le_add_left H' _) (take Heq, let Heq' := add_left_cancel Heq in !int.lt_irrefl (Heq' ▸ H))) protected theorem mul_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a * b := obtain (n : ℕ) (Hn : 0 + n = a), from le.elim Ha, obtain (m : ℕ) (Hm : 0 + m = b), from le.elim Hb, le.intro (eq.symm (calc a * b = (0 + n) * b : by rewrite Hn ... = n * b : by rewrite zero_add ... = n * (0 + m) : by rewrite Hm ... = n * m : by rewrite zero_add ... = 0 + n * m : by rewrite zero_add)) protected theorem mul_pos {a b : ℤ} (Ha : 0 < a) (Hb : 0 < b) : 0 < a * b := obtain (n : ℕ) (Hn : 0 + nat.succ n = a), from lt.elim Ha, obtain (m : ℕ) (Hm : 0 + nat.succ m = b), from lt.elim Hb, lt.intro (eq.symm (calc a * b = (0 + nat.succ n) * b : by rewrite Hn ... = nat.succ n * b : by rewrite zero_add ... = nat.succ n * (0 + nat.succ m) : by rewrite Hm ... = nat.succ n * nat.succ m : by rewrite zero_add ... = of_nat (nat.succ n * nat.succ m) : by rewrite of_nat_mul ... = of_nat (nat.succ n * m + nat.succ n) : by rewrite nat.mul_succ ... = of_nat (nat.succ (nat.succ n * m + n)) : by rewrite nat.add_succ ... = 0 + nat.succ (nat.succ n * m + n) : by rewrite zero_add)) protected theorem zero_lt_one : (0 : ℤ) < 1 := trivial protected theorem not_le_of_gt {a b : ℤ} (H : a < b) : ¬ b ≤ a := assume Hba, let Heq := int.le_antisymm (le_of_lt H) Hba in !int.lt_irrefl (Heq ▸ H) protected theorem lt_of_lt_of_le {a b c : ℤ} (Hab : a < b) (Hbc : b ≤ c) : a < c := let Hab' := le_of_lt Hab in let Hac := int.le_trans Hab' Hbc in (iff.mpr !int.lt_iff_le_and_ne) (and.intro Hac (assume Heq, int.not_le_of_gt (Heq ▸ Hab) Hbc)) protected theorem lt_of_le_of_lt {a b c : ℤ} (Hab : a ≤ b) (Hbc : b < c) : a < c := let Hbc' := le_of_lt Hbc in let Hac := int.le_trans Hab Hbc' in (iff.mpr !int.lt_iff_le_and_ne) (and.intro Hac (assume Heq, int.not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab)) protected definition linear_ordered_comm_ring [reducible] [trans_instance] : linear_ordered_comm_ring int := ⦃linear_ordered_comm_ring, int.integral_domain, le := int.le, le_refl := int.le_refl, le_trans := @int.le_trans, le_antisymm := @int.le_antisymm, lt := int.lt, le_of_lt := @int.le_of_lt, lt_irrefl := int.lt_irrefl, lt_of_lt_of_le := @int.lt_of_lt_of_le, lt_of_le_of_lt := @int.lt_of_le_of_lt, add_le_add_left := @int.add_le_add_left, mul_nonneg := @int.mul_nonneg, mul_pos := @int.mul_pos, le_iff_lt_or_eq := int.le_iff_lt_or_eq, le_total := int.le_total, zero_ne_one := int.zero_ne_one, zero_lt_one := int.zero_lt_one, add_lt_add_left := @int.add_lt_add_left⦄ protected definition decidable_linear_ordered_comm_ring [reducible] [instance] : decidable_linear_ordered_comm_ring int := ⦃decidable_linear_ordered_comm_ring, int.linear_ordered_comm_ring, decidable_lt := decidable_lt⦄ /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial theorem of_nat_pos {n : ℕ} (Hpos : #nat n > 0) : of_nat n > 0 := of_nat_lt_of_nat_of_lt Hpos theorem of_nat_succ_pos (n : nat) : of_nat (nat.succ n) > 0 := of_nat_pos !nat.succ_pos theorem exists_eq_of_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = of_nat n := obtain (n : ℕ) (H1 : 0 + of_nat n = a), from le.elim H, exists.intro n (!zero_add ▸ (H1⁻¹)) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(of_nat n) := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, obtain (n : ℕ) (Hn : -a = of_nat n), from exists_eq_of_nat this, exists.intro n (eq_neg_of_eq_neg (Hn⁻¹)) theorem of_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : of_nat (nat_abs a) = a := obtain (n : ℕ) (Hn : a = of_nat n), from exists_eq_of_nat H, Hn⁻¹ ▸ congr_arg of_nat (nat_abs_of_nat n) theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : of_nat (nat_abs a) = -a := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, calc of_nat (nat_abs a) = of_nat (nat_abs (-a)) : nat_abs_neg ... = -a : of_nat_nat_abs_of_nonneg this theorem of_nat_nat_abs (b : ℤ) : nat_abs b = abs b := or.elim (le.total 0 b) (assume H : b ≥ 0, of_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹) (assume H : b ≤ 0, of_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹) theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := abs.by_cases rfl !nat_abs_neg theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := obtain (n : nat) (H1 : a + 1 + n = b), from le.elim H, have a + succ n = b, by rewrite [-H1, add.assoc, add.comm 1], lt.intro this theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := obtain (n : nat) (H1 : a + succ n = b), from lt.elim H, have a + 1 + n = b, by rewrite [-H1, add.assoc, add.comm 1], le.intro this theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := lt_add_of_le_of_pos H trivial theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H, le_of_add_le_add_right H1 theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := lt_of_add_one_le (begin rewrite sub_add_cancel, exact H end) theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := !sub_add_cancel ▸ add_one_le_of_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_of_lt_add_one begin rewrite sub_add_cancel, exact H end theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := !sub_add_cancel ▸ (lt_add_one_of_le H) theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := sign_of_pos (of_nat_pos !nat.succ_pos) theorem exists_eq_neg_succ_of_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[1+m] := int.cases_on a (take (m : nat) H, absurd (of_nat_nonneg m : 0 ≤ m) (not_le_of_gt H)) (take (m : nat) H, exists.intro m rfl) theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := have a * b > 0, by rewrite H'; apply trivial, have b > 0, from pos_of_mul_pos_left this H, have a > 0, from pos_of_mul_pos_right `a * b > 0` (le_of_lt `b > 0`), or.elim (le_or_gt a 1) (suppose a ≤ 1, show a = 1, from le.antisymm this (add_one_le_of_lt `a > 0`)) (suppose a > 1, assert a * b ≥ 2 * 1, from mul_le_mul (add_one_le_of_lt `a > 1`) (add_one_le_of_lt `b > 0`) trivial H, have false, by rewrite [H' at this]; exact this, false.elim this) theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (!mul.comm ▸ H') theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul a)⁻¹) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := dvd.elim H' (take b, suppose 1 = a * b, eq_one_of_mul_eq_one_right H this⁻¹) theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≤ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b + of_nat (least (λ n, P (b + of_nat n)) (nat.succ (nat_abs (elt - b)))), have Heltb : elt > b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b + of_nat (nat_abs (elt - b))), begin rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), add.comm, sub_add_cancel], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≤ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b + of_nat (nat_abs (z - b)), by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.add_comm, sub_add_cancel], have Hk : nat_abs (z - b) < least (λ n, P (b + of_nat n)) (nat.succ (nat_abs (elt - b))), begin note Hz' := iff.mp !lt_add_iff_sub_lt_left Hz, rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_of_nat_lt_of_nat Hz' end, let Hk' := not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≥ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b - of_nat (least (λ n, P (b - of_nat n)) (nat.succ (nat_abs (b - elt)))), have Heltb : elt < b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b - of_nat (nat_abs (b - elt))), begin rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), sub_sub_self], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≥ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b - of_nat (nat_abs (b - z)), by rewrite [of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), sub_sub_self], have Hk : nat_abs (b - z) < least (λ n, P (b - of_nat n)) (nat.succ (nat_abs (b - elt))), begin note Hz' := iff.mp !lt_add_iff_sub_lt_left (iff.mpr !lt_add_iff_sub_lt_right Hz), rewrite [-of_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_of_nat_lt_of_nat Hz' end, let Hk' := not_le_of_gt Hk, rewrite Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end end int
c5328f8645efb70b1a1c5d556aace9fd8b41f4c1
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_3/Part_A_limits.lean
7e38378ec55eeeda03b17b84bc0d4e6ad6a0fbb0
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
23,453
lean
-- need the real numbers import data.real.basic -- need the tactics import tactic /- # Limits We develop a theory of limits of sequences a₀, a₁, a₂, … of reals, following the way is it traditionally done in a first year undergraduate mathematics course. ## Overview of the file This file contains the basic definition of the limit of a sequence, and proves basic properties about it. The `data.real.basic` import imports the definition and basic properties of the real numbers, including, for example, the absolute value function `abs : ℝ → ℝ`, and the proof that `ℝ` is a complete totally ordered archimedean field. To get `ℝ` in Lean, type `\R`. We define the predicate `is_limit (a : ℕ → ℝ) (l : ℝ)` to mean that `aₙ → l` in the usual way: `∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε` We then develop the basic theory of limits. ## Main theorems variables (a b c : ℕ → ℝ) (c l m : ℝ) * `is_limit_const : is_limit (λ n, c) c` * `is_limit_subsingleton (hl : is_limit a l) (hm : is_limit a m) : l = m` * `is_limit_add (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a + b) (l + m)` * `is_limit_mul (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a * b) (l * m)` * `is_limit_le_of_le (hl : is_limit a l) (hm : is_limit b m) (hle : ∀ n, a n ≤ b n) : l ≤ m` * `sandwich (ha : is_limit a l) (hc : is_limit c l) (hab : ∀ n, a n ≤ b n) (hbc : ∀ n, b n ≤ c n) : is_limit b l` -/ namespace xena -- the maths starts here. -- We introduce the usual mathematical notation for absolute value local notation `|` x `|` := abs x -- We model a sequence a₀, a₁, a₂,... of real numbers as a function -- from ℕ := {0,1,2,...} to ℝ, sending n to aₙ . So in the below -- definition of the limit of a sequence, a : ℕ → ℝ is the sequence. /-- `l` is the limit of the sequence `a` of reals -/ definition is_limit (a : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε /- Note that `is_limit` is not a *function* (ℕ → ℝ) → ℝ! It is a _binary relation_ on (ℕ → ℝ) and ℝ, i.e. it's a function which takes as input a sequence and a candidate limit, and returns the true-false statement saying that the sequence converges to the limit. The reason we can't use a "limit" function, which takes in a sequence and returns its limit, is twofold: (1) some sequences (like 0, 1, 0, 1, 0, 1,…) don't have a limit at all, and (2) at this point in the development, some sequences might in theory have more than one limit (and if we were working with a non-Hausdorff topological space rather than `ℝ` this could of course actually happen, although we will see below that it can't happen here). -/ /- Let's start with a warmup : the constant sequence with value c tends to c. Before we start though, I need to talk about this weird `λ` notation which functional programmers use. ### λ notation for functions This is a lot less scary than it looks. The notation `λ n, f n` in Lean just means what we mathematicians would call `f` or `f(x)`. Literally, it means "the function sending `n` to `f n`, with this added twist that we don't need to write the brackets (although `λ n, f(n)` would also work fine). Another way of rewriting it in a more familiar manner: `λ n, f n` is the function `n ↦ f n`. So, for example, `λ n, 2 * n` is just the function `f(x)=2*x`. It's sometimes called "anonymous function notation" because we do not need to introduce a name for the function if we use lambda notation. So you need to know a trick here. What happens if we have such a function defined by lambda notation, and then we actually try to evaluate it! You have to know how to change `(λ n, f n) (37)` into `f(37)` (or, as Lean would call it, `f 37`). Computer scientists call this transformation "beta reduction". In Lean, beta reduction is true definitionally, so if you are using `apply` or `intro` or other tactics which work up to definitional equality then you might not even have to change it at all. But if your goal contains an "evaluated λ" like `⊢ (λ n, f n) 37` and you have a hypothesis `h1 : f 37 = 100` then `rw h1` will fail, because `rw` is pickier and only worked up to syntactic equality. So you need to know the trick to change this goal to `f 37`, which is the tactic `dsimp only`. It works on hypotheses too -- `dsimp only at h` will remove an evaluated `λ` from hypothesis `h`. We will now prove that the limit of a constant sequence `aₙ = c` is `c`. The definition of the constant sequence is `λ n, c`, the function sending every `n` to `c`. I have given you the proof. Step through it by moving your cursor through it line by line and watch the tactic state changing. -/ /-- The limit of a constant sequence is the constant. -/ lemma is_limit_const (c : ℝ) : is_limit (λ n, c) c := begin -- is_limit a l is *by definition* "∀ ε, ε > 0 → ..." so we -- can just start with `intros`. intros ε εpos, -- we need to come up with some N such that n ≥ N implies |c - c| < ε. -- We have some flexibility here :-) use 37, -- Now assume n is a natural which is at least 37, but we may as -- well just forget the fact that n ≥ 37 because we're not going to use it. rintro n -, -- Now we have an "unreduced lambda term" in the goal, so let's -- beta reduce it. dsimp only, -- the simplifier is bound to know that `c - c = 0` simp, -- finally, `a > b` is *definitionally* `b < a`, and the `exact` -- tactic works up to definitional equality. exact εpos, end /- I am going to walk you through the next proof as well. It's a proof that if `aₙ → l` and `aₙ → m` then `l = m`. Here is how it is stated in Lean: ``` theorem is_limit_subsingleton {a : ℕ → ℝ} {l m : ℝ} (hl : is_limit a l) (hm : is_limit a m) : l = m := ... ``` Before we go through this proof, I think it's time I explained these squiggly brackets properly. How come I've written `{a : ℕ → ℝ}` and not `(a : ℕ → ℝ)`? ### Squiggly brackets {} in function inputs, and dependent functions. `is_limit_subsingleton` is a proof that a sequence can have at most one limit. It is also a function. Learning to think about proofs as functions is an important skill for proving the theorems in this workshop. So let's talk a bit about how a proof can be a function. In Lean's dependent type theory, there are types and terms, and every term has a unique type. Types and terms are used to unify two ideas which mathematicians usually regard as completely different: that of sets and elements, and that of theorems and proofs. Let's take a close look at what exactly this function `is_limit_subsingleton` does. Let's take a closer look at `is_limit_subsingleton` (the theorem is stated 20 lines above here). It is a function with five inputs. The first input is a sequence `a : ℕ → ℝ`. The second and third are real numbers `l` and `m`. The fourth input is a proof that `a(n)` tends to `l`, and the fifth is a proof that `a(n)` tends to `m`. The output of the function (after the colon) is a proof that `l = m`. This is how Lean thinks about proofs internally, and it's important that you internalise this point of view because you will be treating proofs as functions and evaluating them on inputs to get other proofs quite a bit today. If you still think it's a bit weird having proofs as inputs and outputs to functions, just think of a true-false statement (e.g. a theorem statement) as being a set, and the elements of that set are the proofs of the theorem. For example `2 + 2 = 5` is a set with no elements, because there are no proofs of this theorem (assuming that mathematics is consistent). Now if you think about these inputs carefully, and you think about your mental model of a function, you may realised that there is something else a bit fishy going on here. Usually you would think of a function with five inputs as a function from `A × B × C × D × E` to `X`, where `A`, `B`, `C`, `D` and `E` are all sets. The first three inputs `a` (of type `ℕ → ℝ`) and `l` and `m` (of type `ℝ`) are uncontroversial: we can just set `A = ℕ → ℝ` and `B = C = ℝ`. But the fourth input to `is_limit_singleton` is an element of the set of proofs of `is_limit a l`, the statement that `a(n)` tends to `l`, and in particular this set itself *depends on the first two inputs*. The set `D` itself is a function of `a` and `l` -- the actual inputs themselves, rather than the sets `A` and `B` that they belong to. The same is true for the set `E`, which is a function of `a` and `m`. This slightly bizarre set-up has the even more bizarre consequence that actually, if Lean knows the fourth and fifth inputs (in this case, proofs of `is_limit a l` and `is_limit a m`) then it *does not actually even need to know what the first three inputs are*, because Lean can work them out from the *type* of the fourth and fifth inputs. In summary then, the five inputs to this functions are: `a` of type `ℕ → ℝ`, `l` and `m` of type `ℝ`, `h1` of type `is_limit a l` `h2` of type `is_limit a m`. In particular, if we know the fourth and fifth inputs `h1` and `h2`, then by looking at the types of these terms, we can actually work out what the first three inputs *have to be* in order to make everything make sense. This is why we put the first three inputs in `{}` brackets. This means "these inputs are part of the function, but Lean's *unification system* (the part of the system which checks that everything has the right type) will work them out automatically, so we will not trouble the user by asking for them". In short, if we ever run this function of five inputs, we can just give `h1` and `h2` and let Lean figure out the first three inputs itself. In general if a function input has `{}` brackets then the user does not have to supply those inputs, the user can trust the system to fill them in automatically. That's quite enough about the statement! Let's get back to mathematics and I will talk you through the proof. Step through the proof line by line and watch the tactic state change. -/ theorem is_limit_subsingleton {a : ℕ → ℝ} {l m : ℝ} (hl : is_limit a l) (hm : is_limit a m) : l = m := begin -- There are several ways to prove this, but let's prove it -- by contradiction. Let's assume `h : l ≠ m` and prove `false`. by_contra h, -- The idea is that if `ε = |l - m|` then the sequence `a` will -- eventually be within `ε/2` of `l` and `ε/2` of `m`, which -- will be a contradiction. To make life easier let's break -- the symmetry and assume WLOG that `l < m`, because then -- we can just let `ε` be `m - l`. wlog hlm : l < m, -- Lean checks that everything is symmetric in `l` and `m` so -- this tactic succeeds, but asks us to prove that either -- `l < m` or `m < l`. We now have two goals so let's -- put a `{` `}` pair to get back to one goal. { -- now we just have the one easy goal `l < m ∨ m < l`. -- First we note that the reals are totally ordered so -- we can add `l < m ∨ l = m ∨ m < l` to the list of -- hypotheses with the `have` tactic: have : l < m ∨ l = m ∨ m < l := lt_trichotomy l m, -- Now the result follows from pure logic. tauto }, -- Now let's define ε to be m - l. set ε := m - l with hε, -- Mathematically, the plan is to now find big natural numbers `L` and `M` -- such that `n ≥ L → |a n - l| < ε/2`, and `n ≥ M → |a n - m| < ε/2`, -- and then set `n = max L M` to get a contradiction. How do we do this -- in Lean? -- Well, let's think about `hl` as a function. Its type is -- `is_limit a l` which is definitionally `∀ ε, ε > 0 → ...`. -- So `hl` is a function which wants as an input a real number -- and a proof that it is positive. Let's first give `hl` the -- real number `ε/2` once and for all (it's the only time we'll -- be using `hl` in the proof so we can change its definition) specialize hl (ε/2), -- Now `hl` is a function which wants a proof by `ε/2>0` as its input. -- Mathematically, this is obvious: `ε/2=(m-l)/2` and `l < m`. -- Lean's `linarith` (linear arithmetic) tactic can solve this sort of goal: have hε2 : ε/2 > 0 := by linarith, -- Now we can specialize `hl` further: specialize hl hε2, -- Now `hl` isn't a function any more. In the lingo, it's an inductive -- type rather than a pi type. -- `hl : ∃ (N : ℕ), ∀ (n : ℕ), n ≥ N → |a n - l| < ε / 2` -- `hl` is now a made from a pair of pieces of information: first a natural -- number `N`, and second a proof of some fact about `N`. We can take -- `hl` apart into these two pieces with the `cases` tactic: cases hl with L hL, -- Now `L` is the natural and `hL` is a proof of a theorem about it: -- `hL : ∀ (n : ℕ), n ≥ L → |a n - l| < ε / 2` -- We now need to do the same thing with `hm`. Let's just do it all in one -- go. Check that you understand why this one line does the same sort of thing -- as the four lines above. cases hm (ε/2) (by linarith) with M hM, -- Now let's get back to the maths proof. Let N be the max of L and M. set N := max L M with hN, -- Let's record here the fact that `L ≤ N` and `M ≤ N`. I found -- these proofs by using `library_search` and then clicking on "Try this!". -- For example -- `have hLN : L ≤ N := by library_search`, have hLN : L ≤ N := le_max_left L M, have hMN : M ≤ N := le_max_right L M, -- We're going to set `n = N` in `hL` and `hM`. Again I'm thinking -- of these things as functions. specialize hL N hLN, specialize hM N hMN, -- It looks like we should be done now: everything should follow -- now from chasing inequalities. We need to give Lean one more hint -- though, because `linarith` doesn't know anything about the `abs` function; -- we need to know that |x|<ε/2 is the same as `-ε/2 < x ∧ x < ε/2`. -- This theorem is called `abs_lt` ("absolute value is less than"). rw abs_lt at hL hM, -- As a challenge, can you now look at the tactic state and finish the proof -- on paper? Lean's `linarith` tactic can see its way through the inequality -- maze. Let's finish this proof and talk about `linarith` and another -- high-powered tactic, `ring`. linarith, end /- Two quick comments on some other new things in the above proof: 1) We will be using `max` a lot in this workshop. `max A B` is the max of `A` and `B`. `max` is a definition, not a theorem, so that means that there will be an API associated with it, i.e. a list of little theorems which make `max` possible to use. We just saw the two important theorems which we'll be using: `le_max_left A B : A ≤ max A B` and `le_max-right A B : B ≤ max A B`. There are other cool functions in the `max` API, for example `max_le : A ≤ C → B ≤ C → max A B ≤ C`. The easiest way to find your way around the `max` API is to *guess* what the names of the theorems are! For example what do you think `max A B < C ↔ A < C ∧ B < C` is called? If you can't work it out, then cheat by running ``` example (A B C : ℝ) : max A B < C ↔ A < C ∧ B < C := begin library_search end ``` 2) `specialize` is a tactic which changes a function by fixing once and for all the first inputs. For example, say `f : A → B → C → D` is a function. Because `→` is right associative in Lean, `f` is a function which wants an input from `A`, and then spits out a function which wants an input from `B`, and spits out a function which wants an input from `C` and spits out an element of `D`. So really it's just a function which takes three inputs, one from `A`, one from `B` and one from `C`, and spits out something in `D`. This is what computer scientists call "currying". Now say I have `a : A` and I want this to be my first input to `f`, and I never want to run `f` again with any other inputs from `A`. Then `specialize f a` will feed `a` into `f` and then rename `f` to be the resulting new function `B → C → D`. -/ -- Before we go on, I need to explain two more high-powered tactics. /- ## `linarith` and `ring` `linarith` and `ring` are two high-powered tactics. It's important to know their "scope". ### `ring` Let's start with `ring`. The `ring` tactic will prove any goal which can be deduced from the axioms of a commutative ring (or even a commutative semiring like `ℕ`). For example if `(x y : ℝ)` and the goal is `(x+y)^3=x^3+3*x^2*y+3*x*y^2+y^3` then `ring` will close this goal. In the proof of `is_limit_add` below in my solutions file, I use `ring` to prove `a n + b n - (l + m) = (a n - l) + (b n - m)` and to prove `ε/2 + ε/2 = ε`. Note that `ring` will get confused if it sees `λ` terms and so on, it works up to syntactic equality. `ring` wants to see a clean statement about elements of a ring involving only `+`, `-` and `*`. Note also that `ring` does not look at hypotheses -- it works on the goal only. So for example `ring` will not solve this goal directly: ``` a b c : ℝ ha : a = b + c ⊢ 2 * a = b + b + c + c ``` To solve this goal you need to do `rw ha` and then `ring`. ### `linarith` `linarith` solves linear inequalities. For example it will solve this goal: ``` a b c : ℝ hab : a ≤ b hbc : b < c ⊢ a ≤ c + 1 ``` Note that it will not do your logic for you though. For example it will not solve this goal: ``` a b c : ℝ hab : a ≤ b hbc : a ≤ b → b < c ⊢ a ≤ c + 1 ``` even though `b < c` is "obviously true because of `hab`", `linarith` can't see it. The *one* thing it can see through is `∧` in hypotheses: it will solve this goal. ``` a b c : ℝ h : a ≤ b ∧ b < c ⊢ a ≤ c + 1 ``` However it will not see through `∧` in goals; it will not solve this. ``` a b c : ℝ h : a ≤ b ∧ b < c ⊢ a ≤ c + 1 ∧ a ≤ c + 1 ``` To solve this goal, use `split; linarith`. The semicolon means "apply the next tactic to all goals created by the previous tactic". If you're unsure whether `linarith` can see an inequality, just isolate it as a hypothesis or goal all by itself. Then `linarith` can definitely see it. -/ /- ## convert While we're here, here is an explanation of one more high-powered tactic. If your goal is `⊢ P` and you have a hypothesis `h : P'` where `P` and `P'` only differ slightly, then `convert h'` will replace the goal with new goals asking for justification that all the places where `P` and `P'` differ are equal. Here's an example: -/ example (a b : ℝ) (h : a * 2 = b + 1) : a + a = b - (-1) := begin -- rw `h` won't work because we don't have a complete match on either -- side of the equality. convert h, -- now two goals: `a + a = a * 2` and `b - -1 = b + 1` { ring }, { ring } end /- An example where things can go a bit wrong is below. Uncomment the `convert h` line to see a failure, and then you'll understand the fix. -/ example (a b : ℝ) (h : a * 2 = b + 1) : a + a = 1 + b := begin -- uncomment this to see something unfortunate happen: -- convert h, convert h using 1, -- change to 2 or more to see the unfortunate thing again { ring }, { ring } end /- OK it's time to actually do some mathematics! Why don't we start by looking at what happens when we change a sequence or limit by adding a constant. -/ lemma is_limit_add_const {a : ℕ → ℝ} {l : ℝ} (c : ℝ) (ha : is_limit a l) : is_limit (λ i, a i + c) (l + c) := begin sorry end lemma is_limit_add_const_iff {a : ℕ → ℝ} {l : ℝ} (c : ℝ) : is_limit a l ↔ is_limit (λ i, a i + c) (l + c) := begin sorry, end lemma is_limit_iff_is_limit_sub_eq_zero (a : ℕ → ℝ) (l : ℝ) : is_limit a l ↔ is_limit (λ i, a i - l) 0 := begin sorry, end /- We now prove that if aₙ → l and bₙ → m then aₙ + bₙ → l + m. Here is the proof that I recommend you formalise: choose L large enough so that n ≥ L implies |aₙ - l|<ε/2 choose M large enough so that n ≥ M implies |bₙ - m|<ε/2 Now N := max M₁ M₂ works. Some extra things you may need to know: `pi.add_apply a b : (a + b) n = a n + b n` `abs_add x y : |x + y| ≤ |x| + |y|` Good luck! -/ theorem is_limit_add {a b : ℕ → ℝ} {l m : ℝ} (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a + b) (l + m) := begin sorry, end -- We have proved `is_limit` behaves well under `+`. If we also -- prove that it behaves well under scalar multiplication, we can -- deduce that it's linear. So let's do this next. -- Helpful things: -- `abs_pos : 0 < |a| ↔ a ≠ 0` -- `div_pos : 0 < a → 0 < b → 0 < a / b` -- `abs_mul x y : |x * y| = |x| * |y|` -- `lt_div_iff' : 0 < c → (a < b / c ↔ c * a < b)` -- I typically find these things myself with a combination of -- the "guess the name of the lemma" game (and ctrl-space), and `library_search` -- A hint for starting: -- It might be worth dealing with `c = 0` as a special case. You -- can start with -- `by_cases hc : c = 0` lemma is_limit_mul_const_left {a : ℕ → ℝ} {l c : ℝ} (h : is_limit a l) : is_limit (λ n, c * (a n)) (c * l) := begin sorry, end -- This should just be a couple of lines now. lemma is_limit_linear (a : ℕ → ℝ) (b : ℕ → ℝ) (α β c d : ℝ) (ha : is_limit a α) (hb : is_limit b β) : is_limit ( λ n, c * (a n) + d * (b n) ) (c * α + d * β) := begin sorry, end -- We need the below result to prove that product of limits is limit -- of products. -- Rather than using `√ε`, just choose `N` large enough such that `|a n| ≤ ε` -- and `|b n| ≤ 1` if `n ≥ N`; this will work. lemma is_limit_mul_eq_zero_of_is_limit_eq_zero {a : ℕ → ℝ} {b : ℕ → ℝ} (ha : is_limit a 0) (hb : is_limit b 0) : is_limit (a * b) 0 := begin sorry, end -- The limit of the product is the product of the limits. -- If aₙ → l and bₙ → m then aₙ * bₙ → l * m. -- Here's the proof I recommend. Start with -- `suffices : is_limit (λ i, (a i - l) * (b i - m) + (l * (b i - m)) + m * (a i - l)) 0,` -- (note: this multiplies out to `a i * b i - l * m`) -- and then prove that all three terms in the sum tend to zero. theorem is_limit_mul (a : ℕ → ℝ) (b : ℕ → ℝ) (l m : ℝ) (h1 : is_limit a l) (h2 : is_limit b m) : is_limit (a * b) (l * m) := begin sorry, end -- If aₙ → l and bₙ → m, and aₙ ≤ bₙ for all n, then l ≤ m theorem is_limit_le_of_le (a : ℕ → ℝ) (b : ℕ → ℝ) (l : ℝ) (m : ℝ) (hl : is_limit a l) (hm : is_limit b m) (hle : ∀ n, a n ≤ b n) : l ≤ m := begin sorry, end -- sandwich theorem sandwich (a b c : ℕ → ℝ) (l : ℝ) (ha : is_limit a l) (hc : is_limit c l) (hab : ∀ n, a n ≤ b n) (hbc : ∀ n, b n ≤ c n) : is_limit b l := begin sorry, end -- Let's make a new definition. definition is_bounded (a : ℕ → ℝ) := ∃ B, ∀ n, |a n| ≤ B -- Now try this: lemma tendsto_bounded_mul_zero {a : ℕ → ℝ} {b : ℕ → ℝ} (hA : is_bounded a) (hB : is_limit b 0) : is_limit (a*b) 0 := begin sorry, end -- we can make more definitions def is_cauchy (a : ℕ → ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ m ≥ N, ∀ n ≥ N, |a m - a n| < ε -- and of course one can go on and on and on end xena -- Take a look at `Part_A_limits_appendix.lean` to see some rather -- shorter proofs! We will talk about these proofs next week. Perhaps -- you can try and investigate what is going on, by hovering on things -- like `tendsto`. Hint: filters.
a8f67fb226b79115a14c58d8317f001947d947e4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/special_functions/pow/complex.lean
9a4fc47cb086b5ee1d17de5bdf409aea8a228c89
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,994
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne, David Loeffler -/ import analysis.special_functions.complex.log /-! # Power function on `ℂ` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We construct the power functions `x ^ y`, where `x` and `y` are complex numbers. -/ open_locale classical real topology filter complex_conjugate open filter finset set namespace complex /-- The complex power function `x ^ y`, given by `x ^ y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] lemma zero_cpow_eq_iff {x : ℂ} {a : ℂ} : 0 ^ x = a ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := begin split, { intros hyp, simp only [cpow_def, eq_self_iff_true, if_true] at hyp, by_cases x = 0, { subst h, simp only [if_true, eq_self_iff_true] at hyp, right, exact ⟨rfl, hyp.symm⟩}, { rw if_neg h at hyp, left, exact ⟨h, hyp.symm⟩, }, }, { rintro (⟨h, rfl⟩|⟨rfl,rfl⟩), { exact zero_cpow h, }, { exact cpow_zero _, }, }, end lemma eq_zero_cpow_iff {x : ℂ} {a : ℂ} : a = 0 ^ x ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := by rw [←zero_cpow_eq_iff, eq_comm] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp only [cpow_def, ite_mul, boole_mul, mul_ite, mul_boole]; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp only [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp only [cpow_def, neg_eq_zero, mul_neg]; split_ifs; simp [exp_neg] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp, norm_cast] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_two (x : ℂ) : x ^ (2 : ℂ) = x ^ 2 := by { rw ← cpow_nat_cast, simp only [nat.cast_bit0, nat.cast_one] } @[simp, norm_cast] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp | -[1+ n] := by rw zpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : n ≠ 0) : (x ^ (n⁻¹ : ℂ)) ^ n = x := begin suffices : im (log x * n⁻¹) ∈ Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, of_real_mul_im, ← div_eq_inv_mul], rw [← pos_iff_ne_zero] at hn, have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end lemma mul_cpow_of_real_nonneg {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (r : ℂ) : ((a : ℂ) * (b : ℂ)) ^ r = (a : ℂ) ^ r * (b : ℂ) ^ r := begin rcases eq_or_ne r 0 with rfl | hr, { simp only [cpow_zero, mul_one] }, rcases eq_or_lt_of_le ha with rfl | ha', { rw [of_real_zero, zero_mul, zero_cpow hr, zero_mul] }, rcases eq_or_lt_of_le hb with rfl | hb', { rw [of_real_zero, mul_zero, zero_cpow hr, mul_zero] }, have ha'' : (a : ℂ) ≠ 0 := of_real_ne_zero.mpr ha'.ne', have hb'' : (b : ℂ) ≠ 0 := of_real_ne_zero.mpr hb'.ne', rw [cpow_def_of_ne_zero (mul_ne_zero ha'' hb''), log_of_real_mul ha' hb'', of_real_log ha, add_mul, exp_add, ←cpow_def_of_ne_zero ha'', ←cpow_def_of_ne_zero hb''] end lemma inv_cpow_eq_ite (x : ℂ) (n : ℂ) : x⁻¹ ^ n = if x.arg = π then conj (x ^ conj n)⁻¹ else (x ^ n)⁻¹ := begin simp_rw [complex.cpow_def, log_inv_eq_ite, inv_eq_zero, map_eq_zero, ite_mul, neg_mul, is_R_or_C.conj_inv, apply_ite conj, apply_ite exp, apply_ite has_inv.inv, map_zero, map_one, exp_neg, inv_one, inv_zero, ←exp_conj, map_mul, conj_conj], split_ifs with hx hn ha ha; refl, end lemma inv_cpow (x : ℂ) (n : ℂ) (hx : x.arg ≠ π) : x⁻¹ ^ n = (x ^ n)⁻¹ := by rw [inv_cpow_eq_ite, if_neg hx] /-- `complex.inv_cpow_eq_ite` with the `ite` on the other side. -/ lemma inv_cpow_eq_ite' (x : ℂ) (n : ℂ) : (x ^ n)⁻¹ = if x.arg = π then conj (x⁻¹ ^ conj n) else x⁻¹ ^ n := begin rw [inv_cpow_eq_ite, apply_ite conj, conj_conj, conj_conj], split_ifs, { refl }, { rw inv_cpow _ _ h } end lemma conj_cpow_eq_ite (x : ℂ) (n : ℂ) : conj x ^ n = if x.arg = π then x ^ n else conj (x ^ conj n) := begin simp_rw [cpow_def, map_eq_zero, apply_ite conj, map_one, map_zero, ←exp_conj, map_mul, conj_conj, log_conj_eq_ite], split_ifs with hcx hn hx; refl end lemma conj_cpow (x : ℂ) (n : ℂ) (hx : x.arg ≠ π) : conj x ^ n = conj (x ^ conj n) := by rw [conj_cpow_eq_ite, if_neg hx] lemma cpow_conj (x : ℂ) (n : ℂ) (hx : x.arg ≠ π) : x ^ conj n = conj (conj x ^ n) := by rw [conj_cpow _ _ hx, conj_conj] end complex section tactics /-! ## Tactic extensions for complex powers -/ namespace norm_num theorem cpow_pos (a b : ℂ) (b' : ℕ) (c : ℂ) (hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, complex.cpow_nat_cast] theorem cpow_neg (a b : ℂ) (b' : ℕ) (c c' : ℂ) (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' := by rw [← hc, ← h, hb, complex.cpow_neg, complex.cpow_nat_cast] open tactic /-- Generalized version of `prove_cpow`, `prove_nnrpow`, `prove_ennrpow`. -/ meta def prove_rpow' (pos neg zero : name) (α β one a b : expr) : tactic (expr × expr) := do na ← a.to_rat, icα ← mk_instance_cache α, icβ ← mk_instance_cache β, match match_sign b with | sum.inl b := do nc ← mk_instance_cache `(ℕ), (icβ, nc, b', hb) ← prove_nat_uncast icβ nc b, (icα, c, h) ← prove_pow a na icα b', cr ← c.to_rat, (icα, c', hc) ← prove_inv icα c cr, pure (c', (expr.const neg []).mk_app [a, b, b', c, c', hb, h, hc]) | sum.inr ff := pure (one, expr.const zero [] a) | sum.inr tt := do nc ← mk_instance_cache `(ℕ), (icβ, nc, b', hb) ← prove_nat_uncast icβ nc b, (icα, c, h) ← prove_pow a na icα b', pure (c, (expr.const pos []).mk_app [a, b, b', c, hb, h]) end /-- Evaluate `complex.cpow a b` where `a` is a rational numeral and `b` is an integer. -/ meta def prove_cpow : expr → expr → tactic (expr × expr) := prove_rpow' ``cpow_pos ``cpow_neg ``complex.cpow_zero `(ℂ) `(ℂ) `(1:ℂ) /-- Evaluates expressions of the form `cpow a b` and `a ^ b` in the special case where `b` is an integer and `a` is a positive rational (so it's really just a rational power). -/ @[norm_num] meta def eval_cpow : expr → tactic (expr × expr) | `(@has_pow.pow _ _ complex.has_pow %%a %%b) := b.to_int >> prove_cpow a b | `(complex.cpow %%a %%b) := b.to_int >> prove_cpow a b | _ := tactic.failed end norm_num end tactics
4eea1ad8b56d6ef1dfd4800be35c2db03e5360a9
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/field_theory/polynomial_galois_group.lean
ece57a833990bc57c9858e8509658fa6949bbff2
[ "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
21,894
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import analysis.complex.polynomial import field_theory.galois import group_theory.perm.cycle_type import ring_theory.eisenstein_criterion /-! # Galois Groups of Polynomials In this file, we introduce the Galois group of a polynomial `p` over a field `F`, defined as the automorphism group of its splitting field. We also provide some results about some extension `E` above `p.splitting_field`, and some specific results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots. ## Main definitions - `polynomial.gal p`: the Galois group of a polynomial p. - `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful. - `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. - `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. - `polynomial.gal.gal_action_hom_bijective_of_prime_degree`: An irreducible polynomial of prime degree with two non-real roots has full Galois group. ## Other results - `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ noncomputable theory open_locale classical open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : polynomial F) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial. -/ @[derive [has_coe_to_fun, group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_roots, algebra.adjoin_le_iff], end /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := unique_gal_of_splits _ (h.1) instance unique_gal_zero : unique (0 : polynomial F).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : polynomial F).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : polynomial F).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : polynomial F).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) -- The `algebra p.splitting_field E` instance above behaves badly when -- `E := p.splitting_field`, since it may result in a unification problem -- `is_splitting_field.lift.to_ring_hom.to_algebra =?= algebra.id`, -- which takes an extremely long time to resolve, causing timeouts. -- Since we don't really care about this definition, marking it as irreducible -- causes that unification to error out early. attribute [irreducible] gal.algebra /-- Restrict from a superfield automorphism into a member of `gal p`. -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection, see `polynomial.gal.map_roots_bijective`. -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := λ x, ⟨is_scalar_tower.to_alg_hom F p.splitting_field E x, begin have key := subtype.mem x, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw [mem_root_set h, aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, -- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, multiset.mem_to_finset.mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ x, ⟨ϕ x, begin have key := subtype.mem x, --simp only [root_set, finset.mem_coe, multiset.mem_to_finset] at *, by_cases p = 0, { simp only [h, root_set_zero] at key, exact false.rec _ key }, { rw mem_root_set h, change aeval (ϕ.to_alg_hom x) p = 0, rw [aeval_alg_hom_apply, (mem_root_set h).mp key, alg_hom.map_zero] } end⟩, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } /-- The action of `gal p` on the roots of `p` in `E`. -/ instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} /-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/ @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `polynomial.gal.gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := { to_fun := λ ϕ, equiv.mk (λ x, ϕ • x) (λ x, ϕ⁻¹ • x) (λ x, inv_smul_smul ϕ x) (λ x, smul_inv_smul ϕ x), map_one' := by { ext1 x, exact mul_action.one_smul x }, map_mul' := λ x y, by { ext1 z, exact mul_action.mul_smul x y z } } lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x := restrict_smul ϕ x /-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/ lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw monoid_hom.injective_iff, intros ϕ hϕ, ext x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by simp only [restrict_dvd, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product maps into the product of the Galois groups. -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) /-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/ lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal, { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, dsimp only [restrict_prod, restrict_dvd] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, ext x hx, rw [root_set, map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, multiset.mem_to_finset.mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : polynomial F} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁, }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd _ (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂, }, end /-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/ lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : polynomial F → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : polynomial F}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) ((minpoly.irreducible qx_int).dvd_symm hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : polynomial F}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- `polynomial.gal.restrict` for the composition of polynomials. -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := @restrict F _ p _ _ _ ⟨splits_in_splitting_field_of_comp p q hq⟩ lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} /-- For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. -/ lemma card_of_separable (hp : p.separable) : fintype.card p.gal = finrank F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_finrank F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := (is_algebraic_iff_is_integral F).mp (algebra.is_algebraic_of_finite α), use finite_dimensional.finrank F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.finrank hα, this] }, suffices : minpoly F α ∣ p, { have key := (minpoly.irreducible hα).dvd_symm p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end section rationals lemma splits_ℚ_ℂ {p : polynomial ℚ} : fact (p.splits (algebra_map ℚ ℂ)) := ⟨is_alg_closed.splits_codomain p⟩ local attribute [instance] splits_ℚ_ℂ /-- The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : polynomial ℚ) : (p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card + (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card := begin by_cases hp : p = 0, { simp_rw [hp, root_set_zero, set.to_finset_eq_empty_iff.mpr rfl, finset.card_empty, zero_add], refine eq.symm (nat.le_zero_iff.mp ((finset.card_le_univ _).trans (le_of_eq _))), simp_rw [hp, root_set_zero, fintype.card_eq_zero_iff], apply_instance }, have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective, rw [←finset.card_image_of_injective _ subtype.coe_injective, ←finset.card_image_of_injective _ inj], let a : finset ℂ := _, let b : finset ℂ := _, let c : finset ℂ := _, change a.card = b.card + c.card, have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0 := λ z, by rw [set.mem_to_finset, mem_root_set hp], have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0, { intro z, simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set hp], split, { rintros ⟨w, hw, rfl⟩, exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ }, { rintros ⟨hz1, hz2⟩, have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl }, exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } }, have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ)) w = w ↔ w.val.im = 0, { intro w, rw [subtype.ext_iff, gal_action_hom_restrict], exact complex.eq_conj_iff_im }, have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0, { intro z, simp_rw [finset.mem_image, exists_prop], split, { rintros ⟨w, hw, rfl⟩, exact ⟨(mem_root_set hp).mp w.2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ }, { rintros ⟨hz1, hz2⟩, exact ⟨⟨z, (mem_root_set hp).mpr hz1⟩, equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } }, rw ← finset.card_disjoint_union, { apply congr_arg finset.card, simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc], tauto }, { intro z, rw [finset.inf_eq_inter, finset.mem_inter, hb, hc], tauto }, { apply_instance }, end /-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree {p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) : function.bijective (gal_action_hom p ℂ) := begin have h1 : fintype.card (p.root_set ℂ) = p.nat_degree, { simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots], { exact is_alg_closed.splits_codomain p }, { exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } }, have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range := fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv, let conj := restrict p ℂ (complex.conj_ae.restrict_scalars ℚ), refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x) (show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩, apply equiv.perm.subgroup_eq_top_of_swap_mem, { rwa h1 }, { rw h1, convert prime_degree_dvd_card p_irr p_deg using 1, convert h2.symm }, { exact ⟨conj, rfl⟩ }, { rw ← equiv.perm.card_support_eq_two, apply nat.add_left_cancel, rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)], exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm }, end /-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree' {p : polynomial ℚ} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ)) (p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) : function.bijective (gal_action_hom p ℂ) := begin apply gal_action_hom_bijective_of_prime_degree p_irr p_deg, let n := (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card, have hn : 2 ∣ n := equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow, show alg_equiv.restrict_scalars ℚ complex.conj_ae ^ 2 = 1, from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]), have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p, simp_rw [set.to_finset_card] at key, rw [key, add_le_add_iff_left] at p_roots1 p_roots2, rw [key, add_right_inj], suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2, { exact this n hn p_roots1 p_roots2 }, rintros m ⟨k, rfl⟩ h2 h3, exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1, from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2 (show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))), end end rationals end gal end polynomial
2d674063d786403c56010e72c4b03aeab9b8b711
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/nat/nth.lean
18e2db160b439f27e959da7a20f041ea0f37e242
[ "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
15,240
lean
/- Copyright (c) 2021 Vladimir Goryachev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Vladimir Goryachev, Kyle Miller, Scott Morrison, Eric Rodriguez -/ import data.nat.count import order.order_iso_nat /-! # The `n`th Number Satisfying a Predicate This file defines a function for "what is the `n`th number that satisifies a given predicate `p`", and provides lemmas that deal with this function and its connection to `nat.count`. ## Main definitions * `nth p n`: The `n`-th natural `k` (zero-indexed) such that `p k`. If there is no such natural (that is, `p` is true for at most `n` naturals), then `nth p n = 0`. ## Main results * `nat.nth_set_card`: For a fintely-often true `p`, gives the cardinality of the set of numbers satisfying `p` above particular values of `nth p` * `nat.count_nth_gc`: Establishes a Galois connection between `nth p` and `count p`. * `nat.nth_eq_order_iso_of_nat`: For an infinitely-ofter true predicate, `nth` agrees with the order-isomorphism of the subtype to the natural numbers. There has been some discussion on the subject of whether both of `nth` and `nat.subtype.order_iso_of_nat` should exist. See discussion [here](https://github.com/leanprover-community/mathlib/pull/9457#pullrequestreview-767221180). Future work should address how lemmas that use these should be written. -/ open finset namespace nat variable (p : ℕ → Prop) /-- Find the `n`-th natural number satisfying `p` (indexed from `0`, so `nth p 0` is the first natural number satisfying `p`), or `0` if there is no such number. See also `subtype.order_iso_of_nat` for the order isomorphism with ℕ when `p` is infinitely often true. -/ noncomputable def nth : ℕ → ℕ | n := Inf { i : ℕ | p i ∧ ∀ k < n, nth k < i } lemma nth_zero : nth p 0 = Inf { i : ℕ | p i } := by { rw nth, simp } @[simp] lemma nth_zero_of_zero (h : p 0) : nth p 0 = 0 := by simp [nth_zero, h] lemma nth_zero_of_exists [decidable_pred p] (h : ∃ n, p n) : nth p 0 = nat.find h := by { rw [nth_zero], convert nat.Inf_def h } lemma nth_set_card_aux {n : ℕ} (hp : (set_of p).finite) (hp' : {i : ℕ | p i ∧ ∀ t < n, nth p t < i}.finite) (hle : n ≤ hp.to_finset.card) : hp'.to_finset.card = hp.to_finset.card - n := begin unfreezingI { induction n with k hk }, { congr, simp only [is_empty.forall_iff, nat.not_lt_zero, forall_const, and_true] }, have hp'': {i : ℕ | p i ∧ ∀ t, t < k → nth p t < i}.finite, { refine hp.subset (λ x hx, _), rw set.mem_set_of_eq at hx, exact hx.left }, have hle' := nat.sub_pos_of_lt hle, specialize hk hp'' (k.le_succ.trans hle), rw [nat.sub_succ', ←hk], convert_to (finset.erase hp''.to_finset (nth p k)).card = _, { congr, ext a, simp only [set.finite.mem_to_finset, ne.def, set.mem_set_of_eq, finset.mem_erase], refine ⟨λ ⟨hp, hlt⟩, ⟨(hlt _ (lt_add_one k)).ne', ⟨hp, λ n hn, hlt n (hn.trans_le k.le_succ)⟩⟩, _⟩, rintro ⟨hak : _ ≠ _, hp, hlt⟩, refine ⟨hp, λ n hn, _⟩, rw lt_succ_iff at hn, obtain hnk | rfl := hn.lt_or_eq, { exact hlt _ hnk }, { refine lt_of_le_of_ne _ (ne.symm hak), rw nth, apply nat.Inf_le, simpa [hp] using hlt } }, apply finset.card_erase_of_mem, rw [nth, set.finite.mem_to_finset], apply Inf_mem, rwa [←hp''.to_finset_nonempty, ←finset.card_pos, hk], end lemma nth_set_card {n : ℕ} (hp : (set_of p).finite) (hp' : {i : ℕ | p i ∧ ∀ k < n, nth p k < i}.finite) : hp'.to_finset.card = hp.to_finset.card - n := begin obtain hn | hn := le_or_lt n hp.to_finset.card, { exact nth_set_card_aux p hp _ hn }, rw nat.sub_eq_zero_of_le hn.le, simp only [finset.card_eq_zero, set.finite.to_finset_eq_empty, ←set.subset_empty_iff], convert_to _ ⊆ {i : ℕ | p i ∧ ∀ (k : ℕ), k < hp.to_finset.card → nth p k < i}, { symmetry, rw [←set.finite.to_finset_eq_empty, ←finset.card_eq_zero, ←nat.sub_self hp.to_finset.card], { apply nth_set_card_aux p hp _ le_rfl }, { exact hp.subset (λ x hx, hx.1) } }, exact λ x hx, ⟨hx.1, λ k hk, hx.2 _ (hk.trans hn)⟩, end lemma nth_set_nonempty_of_lt_card {n : ℕ} (hp : (set_of p).finite) (hlt: n < hp.to_finset.card) : {i : ℕ | p i ∧ ∀ k < n, nth p k < i}.nonempty := begin have hp': {i : ℕ | p i ∧ ∀ (k : ℕ), k < n → nth p k < i}.finite, { exact hp.subset (λ x hx, hx.1) }, rw [←hp'.to_finset_nonempty, ←finset.card_pos, nth_set_card p hp], exact nat.sub_pos_of_lt hlt, end lemma nth_mem_of_lt_card_finite_aux (n : ℕ) (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) : nth p n ∈ {i : ℕ | p i ∧ ∀ k < n, nth p k < i} := begin rw nth, apply Inf_mem, exact nth_set_nonempty_of_lt_card _ _ hlt, end lemma nth_mem_of_lt_card_finite {n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) : p (nth p n) := (nth_mem_of_lt_card_finite_aux p n hp hlt).1 lemma nth_strict_mono_of_finite {m n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) (hmn : m < n) : nth p m < nth p n := (nth_mem_of_lt_card_finite_aux p _ hp hlt).2 _ hmn lemma nth_mem_of_infinite_aux (hp : (set_of p).infinite) (n : ℕ) : nth p n ∈ { i : ℕ | p i ∧ ∀ k < n, nth p k < i } := begin rw nth, apply Inf_mem, let s : set ℕ := ⋃ (k < n), { i : ℕ | nth p k ≥ i }, convert_to ((set_of p) \ s).nonempty, { ext i, simp }, refine (hp.diff $ (set.finite_lt_nat _).bUnion _).nonempty, exact λ k h, set.finite_le_nat _, end lemma nth_mem_of_infinite (hp : (set_of p).infinite) (n : ℕ) : p (nth p n) := (nth_mem_of_infinite_aux p hp n).1 lemma nth_strict_mono (hp : (set_of p).infinite) : strict_mono (nth p) := λ a b, (nth_mem_of_infinite_aux p hp b).2 _ lemma nth_injective_of_infinite (hp : (set_of p).infinite) : function.injective (nth p) := begin intros m n h, wlog h' : m ≤ n, { exact (this p hp h.symm (le_of_not_le h')).symm }, rw le_iff_lt_or_eq at h', obtain (h' | rfl) := h', { simpa [h] using nth_strict_mono p hp h' }, { refl }, end lemma nth_monotone (hp : (set_of p).infinite) : monotone (nth p) := (nth_strict_mono p hp).monotone lemma nth_mono_of_finite {a b : ℕ} (hp : (set_of p).finite) (hb : b < hp.to_finset.card) (hab : a ≤ b) : nth p a ≤ nth p b := begin obtain rfl | h := hab.eq_or_lt, { exact le_rfl }, { exact (nth_strict_mono_of_finite p hp hb h).le } end lemma le_nth_of_lt_nth_succ_finite {k a : ℕ} (hp : (set_of p).finite) (hlt : k.succ < hp.to_finset.card) (h : a < nth p k.succ) (ha : p a) : a ≤ nth p k := begin by_contra' hak, refine h.not_le _, rw nth, apply nat.Inf_le, refine ⟨ha, λ n hn, lt_of_le_of_lt _ hak⟩, exact nth_mono_of_finite p hp (k.le_succ.trans_lt hlt) (le_of_lt_succ hn), end lemma le_nth_of_lt_nth_succ_infinite {k a : ℕ} (hp : (set_of p).infinite) (h : a < nth p k.succ) (ha : p a) : a ≤ nth p k := begin by_contra' hak, refine h.not_le _, rw nth, apply nat.Inf_le, exact ⟨ha, λ n hn, (nth_monotone p hp (le_of_lt_succ hn)).trans_lt hak⟩, end section count variables [decidable_pred p] @[simp] lemma count_nth_zero : count p (nth p 0) = 0 := begin rw [count_eq_card_filter_range, finset.card_eq_zero, nth_zero], ext a, simp_rw [not_mem_empty, mem_filter, mem_range, iff_false], rintro ⟨ha, hp⟩, exact ha.not_le (nat.Inf_le hp), end lemma filter_range_nth_eq_insert_of_finite (hp : (set_of p).finite) {k : ℕ} (hlt : k.succ < hp.to_finset.card) : finset.filter p (finset.range (nth p k.succ)) = insert (nth p k) (finset.filter p (finset.range (nth p k))) := begin ext a, simp_rw [mem_insert, mem_filter, mem_range], split, { rintro ⟨ha, hpa⟩, refine or_iff_not_imp_left.mpr (λ h, ⟨lt_of_le_of_ne _ h, hpa⟩), exact le_nth_of_lt_nth_succ_finite p hp hlt ha hpa }, { rintro (ha | ⟨ha, hpa⟩), { rw ha, refine ⟨nth_strict_mono_of_finite p hp hlt (lt_add_one _), _⟩, apply nth_mem_of_lt_card_finite p hp, exact (k.le_succ).trans_lt hlt }, refine ⟨ha.trans _, hpa⟩, exact nth_strict_mono_of_finite p hp hlt (lt_add_one _) } end lemma count_nth_of_lt_card_finite {n : ℕ} (hp : (set_of p).finite) (hlt : n < hp.to_finset.card) : count p (nth p n) = n := begin induction n with k hk, { exact count_nth_zero _ }, { rw [count_eq_card_filter_range, filter_range_nth_eq_insert_of_finite p hp hlt, finset.card_insert_of_not_mem, ←count_eq_card_filter_range, hk (lt_of_succ_lt hlt)], simp, }, end lemma filter_range_nth_eq_insert_of_infinite (hp : (set_of p).infinite) (k : ℕ) : (finset.range (nth p k.succ)).filter p = insert (nth p k) ((finset.range (nth p k)).filter p) := begin ext a, simp_rw [mem_insert, mem_filter, mem_range], split, { rintro ⟨ha, hpa⟩, rw nth at ha, refine or_iff_not_imp_left.mpr (λ hne, ⟨(le_of_not_lt $ λ h, _).lt_of_ne hne, hpa⟩), exact ha.not_le (nat.Inf_le ⟨hpa, λ b hb, (nth_monotone p hp (le_of_lt_succ hb)).trans_lt h⟩) }, { rintro (rfl | ⟨ha, hpa⟩), { exact ⟨nth_strict_mono p hp (lt_succ_self k), nth_mem_of_infinite p hp _⟩ }, { exact ⟨ha.trans (nth_strict_mono p hp (lt_succ_self k)), hpa⟩ } } end lemma count_nth_of_infinite (hp : (set_of p).infinite) (n : ℕ) : count p (nth p n) = n := begin induction n with k hk, { exact count_nth_zero _ }, { rw [count_eq_card_filter_range, filter_range_nth_eq_insert_of_infinite p hp, finset.card_insert_of_not_mem, ←count_eq_card_filter_range, hk], simp, }, end @[simp] lemma nth_count {n : ℕ} (hpn : p n) : nth p (count p n) = n := begin obtain hp | hp := em (set_of p).finite, { refine count_injective _ hpn _, { apply nth_mem_of_lt_card_finite p hp, exact count_lt_card hp hpn }, { exact count_nth_of_lt_card_finite _ _ (count_lt_card hp hpn) } }, { apply count_injective (nth_mem_of_infinite _ hp _) hpn, apply count_nth_of_infinite p hp } end lemma nth_count_eq_Inf {n : ℕ} : nth p (count p n) = Inf {i : ℕ | p i ∧ n ≤ i} := begin rw nth, congr, ext a, simp only [set.mem_set_of_eq, and.congr_right_iff], intro hpa, refine ⟨λ h, _, λ hn k hk, lt_of_lt_of_le _ hn⟩, { by_contra ha, simp only [not_le] at ha, have hn : nth p (count p a) < a := h _ (count_strict_mono hpa ha), rwa [nth_count p hpa, lt_self_iff_false] at hn }, { apply (count_monotone p).reflect_lt, convert hk, obtain hp | hp : (set_of p).finite ∨ (set_of p).infinite := em (set_of p).finite, { rw count_nth_of_lt_card_finite _ hp, exact hk.trans ((count_monotone _ hn).trans_lt (count_lt_card hp hpa)) }, { apply count_nth_of_infinite p hp } } end lemma nth_count_le (hp : (set_of p).infinite) (n : ℕ) : n ≤ nth p (count p n) := begin rw nth_count_eq_Inf, suffices h : Inf {i : ℕ | p i ∧ n ≤ i} ∈ {i : ℕ | p i ∧ n ≤ i}, { exact h.2 }, apply Inf_mem, obtain ⟨m, hp, hn⟩ := hp.exists_gt n, exact ⟨m, hp, hn.le⟩ end lemma count_nth_gc (hp : (set_of p).infinite) : galois_connection (count p) (nth p) := begin rintro x y, rw [nth, le_cInf_iff ⟨0, λ _ _, nat.zero_le _⟩ ⟨nth p y, nth_mem_of_infinite_aux p hp y⟩], dsimp, refine ⟨_, λ h, _⟩, { rintro hy n ⟨hn, h⟩, obtain hy' | rfl := hy.lt_or_eq, { exact (nth_count_le p hp x).trans (h (count p x) hy').le }, { specialize h (count p n), replace hn : nth p (count p n) = n := nth_count _ hn, replace h : count p x ≤ count p n := by rwa [hn, lt_self_iff_false, imp_false, not_lt] at h, refine (nth_count_le p hp x).trans _, rw ← hn, exact nth_monotone p hp h }, }, { rw ←count_nth_of_infinite p hp y, exact count_monotone _ (h (nth p y) ⟨nth_mem_of_infinite p hp y, λ k hk, nth_strict_mono p hp hk⟩) } end lemma count_le_iff_le_nth (hp : (set_of p).infinite) {a b : ℕ} : count p a ≤ b ↔ a ≤ nth p b := count_nth_gc p hp _ _ lemma lt_nth_iff_count_lt (hp : (set_of p).infinite) {a b : ℕ} : a < count p b ↔ nth p a < b := lt_iff_lt_of_le_iff_le $ count_le_iff_le_nth p hp lemma nth_lt_of_lt_count (n k : ℕ) (h : k < count p n) : nth p k < n := begin obtain hp | hp := em (set_of p).finite, { refine (count_monotone p).reflect_lt _, rwa count_nth_of_lt_card_finite p hp, refine h.trans_le _, rw count_eq_card_filter_range, exact finset.card_le_of_subset (λ x hx, hp.mem_to_finset.2 (mem_filter.1 hx).2) }, { rwa ← lt_nth_iff_count_lt _ hp } end lemma le_nth_of_count_le (n k : ℕ) (h: n ≤ nth p k) : count p n ≤ k := begin by_contra hc, apply not_lt.mpr h, apply nth_lt_of_lt_count, simpa using hc end end count lemma nth_zero_of_nth_zero (h₀ : ¬p 0) {a b : ℕ} (hab : a ≤ b) (ha : nth p a = 0) : nth p b = 0 := begin rw [nth, Inf_eq_zero] at ⊢ ha, cases ha, { exact (h₀ ha.1).elim }, { refine or.inr (set.eq_empty_of_subset_empty $ λ x hx, _), rw ←ha, exact ⟨hx.1, λ k hk, hx.2 k $ hk.trans_le hab⟩ } end /-- When `p` is true infinitely often, `nth` agrees with `nat.subtype.order_iso_of_nat`. -/ lemma nth_eq_order_iso_of_nat (i : infinite (set_of p)) (n : ℕ) : nth p n = nat.subtype.order_iso_of_nat (set_of p) n := begin classical, have hi := set.infinite_coe_iff.mp i, induction n with k hk; simp only [subtype.order_iso_of_nat_apply, subtype.of_nat, nat_zero_eq_zero], { rw [nat.subtype.coe_bot, nth_zero_of_exists], }, { simp only [nat.subtype.succ, set.mem_set_of_eq, subtype.coe_mk, subtype.val_eq_coe], rw [subtype.order_iso_of_nat_apply] at hk, set b := nth p k.succ - nth p k - 1 with hb, replace hb : p (↑(subtype.of_nat (set_of p) k) + b + 1), { rw [hb, ←hk, tsub_right_comm], have hn11: nth p k.succ - 1 + 1 = nth p k.succ, { rw tsub_add_cancel_iff_le, exact succ_le_of_lt (pos_of_gt (nth_strict_mono p hi (lt_add_one k))), }, rw add_tsub_cancel_of_le, { rw hn11, apply nth_mem_of_infinite p hi }, { rw [← lt_succ_iff, ← nat.add_one, hn11], apply nth_strict_mono p hi, exact lt_add_one k } }, have H : (∃ n: ℕ , p (↑(subtype.of_nat (set_of p) k) + n + 1)) := ⟨b, hb⟩, set t := nat.find H with ht, obtain ⟨hp, hmin⟩ := (nat.find_eq_iff _).mp ht, rw [←ht, ←hk] at hp hmin ⊢, rw [nth, Inf_def ⟨_, nth_mem_of_infinite_aux p hi k.succ⟩, nat.find_eq_iff], refine ⟨⟨by convert hp, λ r hr, _⟩, λ n hn, _⟩, { rw lt_succ_iff at ⊢ hr, exact (nth_monotone p hi hr).trans (by simp) }, simp only [exists_prop, not_and, not_lt, set.mem_set_of_eq, not_forall], refine λ hpn, ⟨k, lt_add_one k, _⟩, by_contra' hlt, replace hn : n - nth p k - 1 < t, { rw tsub_lt_iff_left, { rw tsub_lt_iff_left hlt.le, convert hn using 1, ac_refl }, exact le_tsub_of_add_le_left (succ_le_of_lt hlt) }, refine hmin (n - nth p k - 1) hn _, convert hpn, have hn11 : n - 1 + 1 = n := nat.sub_add_cancel (pos_of_gt hlt), rwa [tsub_right_comm, add_tsub_cancel_of_le], rwa [←hn11, lt_succ_iff] at hlt }, end end nat
0c2551fedc5e34fa9276d317d78bc4cc37710948
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/AuxLemma.lean
1db2403fa42cf1a5e6d0f354e9836deb2d271af4
[ "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,624
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean.Meta structure AuxLemmas where idx : Nat := 1 lemmas : Std.PHashMap Expr (Name × List Name) := {} deriving Inhabited builtin_initialize auxLemmasExt : EnvExtension AuxLemmas ← registerEnvExtension (pure {}) /-- Helper method for creating auxiliary lemmas in the environment. It uses a cache that maps `type` to declaration name. The cache is not stored in `.olean` files. It is useful to make sure the same auxiliary lemma is not created over and over again in the same file. This method is useful for tactics (e.g., `simp`) that may perform preprocessing steps to lemmas provided by users. For example, `simp` preprocessor may convert a lemma into multiple ones. -/ def mkAuxLemma (levelParams : List Name) (type : Expr) (value : Expr) : MetaM Name := do let env ← getEnv let s ← auxLemmasExt.getState env let mkNewAuxLemma := do let auxName := Name.mkNum (env.mainModule ++ `_auxLemma) s.idx addDecl <| Declaration.thmDecl { name := auxName levelParams := levelParams type := type value := value } modifyEnv fun env => auxLemmasExt.modifyState env fun ⟨idx, lemmas⟩ => ⟨idx + 1, lemmas.insert type (auxName, levelParams)⟩ return auxName match s.lemmas.find? type with | some (name, levelParams') => if levelParams == levelParams' then return name else mkNewAuxLemma | none => mkNewAuxLemma end Lean.Meta
25055834c8d0d2d0d9b4bf7d983e432dab20db0a
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/rat.lean
41390e969e08cc139d0add28652f71f9a123b412
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
41,454
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 Introduces the rational numbers as discrete, linear ordered field. -/ import data.nat.gcd data.pnat data.int.basic data.equiv.encodable order.basic algebra.ordered_field data.real.cau_seq /- rational numbers -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : denom > 0) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (int.of_nat d) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat local infix ` /. `:70 := mk theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_inj, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib] } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply eq_of_mul_eq_mul_right m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom | ⟨n, d, h, (c:_=1)⟩ := show _ = mk_nat n d, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _ @[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt h theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0, mul_comm]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : discrete_field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_mul_cancel := rat.inv_mul_cancel, has_decidable_eq := rat.decidable_eq, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : field ℚ := by apply_instance instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nonzero_comm_ring ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0] protected def nonneg : ℚ → Prop | ⟨n, d, h, c⟩ := n ≥ 0 @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le} end protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], exact mul_nonneg end protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : (d:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁ end protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) : a /. b ≤ c /. d ↔ a * d ≤ c * b := show rat.nonneg _ ↔ _, by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm] using @sub_nonneg _ _ (b * c) (a * d) protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa); rwa neg_neg at this protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, have rat.nonneg (c - a + (b - b)), by simpa [-add_right_neg, add_left_comm], by simpa instance : decidable_linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : lattice.distrib_lattice ℚ := by apply_instance instance : lattice.lattice ℚ := by apply_instance instance : lattice.semilattice_inf ℚ := by apply_instance instance : lattice.semilattice_sup ℚ := by apply_instance instance : lattice.has_inf ℚ := by apply_instance instance : lattice.has_sup ℚ := by apply_instance instance : linear_order ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) : a /. b ≤ c /. d ↔ a * d ≤ c * b := by conv in (_ ≤ _) { simp only [(≤), rat.le], rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁), mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] } protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : discrete_linear_ordered_field ℚ := { zero_lt_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba, not_le_of_lt ab $ rat.add_le_add_left.1 ba, mul_nonneg := @rat.mul_nonneg, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.discrete_field, ..rat.decidable_linear_order } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_field ℚ := by apply_instance instance : decidable_linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : decidable_linear_ordered_semiring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : decidable_linear_ordered_comm_group ℚ := by apply_instance instance : ordered_comm_group ℚ := by apply_instance instance : ordered_cancel_comm_monoid ℚ := by apply_instance instance : ordered_comm_monoid ℚ := by apply_instance theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := le_iff_le_iff_lt_iff_lt.1 $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' _ _ _ _ theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, {refl}, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH], simpa [show -1 = (-1) /. 1, from rfl] end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm theorem mk_eq_div (n d : ℤ) : n /. d = (n / d : ℚ) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def, mul_def one_ne_zero d0, one_mul, mul_one] end /-- `floor q` is the largest integer `z` such that `z ≤ q` -/ def floor : ℚ → ℤ | ⟨n, d, h, c⟩ := n / d theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ := begin simp [floor], rw [num_denom'], have h' := int.coe_nat_lt.2 h, conv { to_rhs, rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] }, exact int.le_div_iff_mul_le h' end theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z := le_iff_le_iff_lt_iff_lt.1 le_floor theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r := le_floor.1 (le_refl _) theorem lt_succ_floor (r : ℚ) : r < (floor r).succ := floor_lt.1 $ int.lt_succ_self _ @[simp] theorem floor_coe (z : ℤ) : floor z = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) /-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/ def ceil (r : ℚ) : ℤ := -(floor (-r)) theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem le_ceil (r : ℚ) : r ≤ ceil r := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ceil z = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) /- cast (injection into fields) -/ section cast variables {α : Type*} section variables [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ protected def cast : ℚ → α | ⟨n, d, h, c⟩ := n / d @[priority 0] instance cast_coe : has_coe ℚ α := ⟨rat.cast⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl @[simp] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem mul_cast_comm (a : α) : ∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a | ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a, by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc, ← show (d:α)⁻¹ * a = a * d⁻¹, from division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, ← nat.mul_cast_comm], simp [d₁0, mul_assoc] end @[simp] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [m0, this, cast_add_of_ne_zero] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm] end theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [num_denom n, inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _), ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[simp] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) : ∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n | ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂], have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] }, rw [← this, ← this, ← Hmul, div_mul_cancel], exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h), end theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n := eq_cast_of_ne_zero _ H1 Hadd Hmul _ $ nat.cast_ne_zero.2 $ ne_of_gt n.pos end theorem cast_mk [discrete_field α] [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := if b0 : b = 0 then by simp [b0, div_zero] else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0) @[simp] theorem cast_add [division_ring α] [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_sub [division_ring α] [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_mul [division_ring α] [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_inv [discrete_field α] [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := if n0 : n.num = 0 then by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_div [discrete_field α] [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := by rw [division_def, cast_mul, cast_inv, division_def] @[simp] theorem cast_bit0 [division_ring α] [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [division_ring α] [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl @[simp] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos (@inv_pos α _ _ (nat.cast_pos.2 h)), int.cast_nonneg] @[simp] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end cast /- nat ceiling -/ /-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`. It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/ def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q) theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q := not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le] theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n := show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n := show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n, by rw [ceil_add_int]; exact match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with | _, ⟨m, rfl⟩ := rfl end theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 := lt_nat_ceil.1 $ by rw [ show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self @[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom | ⟨_, d, _, _⟩ := rfl @[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num) | ⟨n, _, _, _⟩ := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom _, by simpa [hq] lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by rwa [←num_denom q, ←num_denom r] at this, by simp [mul_def hq' hr'] lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [←rat.num_denom q], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, {apply rat.num_ne_zero_of_ne_zero hq}, {simp [rat.denom_ne_zero]}, repeat {assumption} } end end rat
35e38b83161d461df8b3787a81f49a73aaf43b49
618003631150032a5676f229d13a079ac875ff77
/src/number_theory/quadratic_reciprocity.lean
654e8d4b57afb3de74dc7447ab5dce63a2053230
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
25,098
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 field_theory.finite import data.zmod.basic import data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_pow_two_eq_prime_iff_of_mod_four_eq_one`, and `exists_pow_two_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_pow_two_eq_neg_one_iff_mod_four_ne_three` and `exists_pow_two_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmod namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] @[simp] lemma card_units : fintype.card (units (zmod p)) = p - 1 := by rw [card_units, card] /-- Fermat's Little Theorem: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/ theorem fermat_little_units {p : ℕ} [fact p.prime] (a : units (zmod p)) : a ^ (p - 1) = 1 := by rw [← card_units p, pow_card_eq_one] /-- Fermat's Little Theorem: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/ theorem fermat_little {a : zmod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 := begin have := fermat_little_units (units.mk0 a ha), apply_fun (coe : units (zmod p) → zmod p) at this, simpa, end /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : units (zmod p)) : (∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd, { resetI, subst p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim }, obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)), obtain ⟨n, hn⟩ : x ∈ powers g, { rw powers_eq_gpowers, apply hg }, split, { rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, fermat_little_units], }, { subst x, assume h, have key : 2 * (p / 2) ∣ n * (p / 2), { rw [← pow_mul] at h, rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_gpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < p / 2 := nat.div_pos (show fact (1 < p), by apply_instance) dec_trivial, obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul], }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : (∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, _root_.pow_two, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [_root_.zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 := begin cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd, { resetI, subst p, exact dec_trivial }, change fact (p % 2 = 1) at hp_odd, resetI, have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd, { rw [p_half_even, _root_.pow_zero, eq_self_iff_true, true_iff], contrapose! p_half_even with hp, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp], exact dec_trivial }, { rw [p_half_odd, _root_.pow_one, iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd, rw [_root_.fact, ← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd, have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp hp_odd p_half_odd, generalize : p % 4 = k, revert k, exact dec_trivial } end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd ‹p.prime› with hp2 hp_odd, { resetI, subst p, revert a ha, exact dec_trivial }, rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact fermat_little p ha end /-- Wilson's Lemma: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : (nat.fact (p - 1) : zmod p) = -1 := begin refine calc (nat.fact (p - 1) : zmod p) = (Ico 1 (succ (p - 1))).prod (λ (x : ℕ), x) : by rw [← finset.prod_Ico_id_eq_fact, prod_nat_cast] ... = finset.univ.prod (λ x : units (zmod p), x) : _ ... = -1 : by rw [prod_hom _ (coe : units (zmod p) → zmod p), prod_univ_units_id_eq_neg_one, units.coe_neg, units.coe_one], have hp : 0 < p := nat.prime.pos ‹p.prime›, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [Ico.mem, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.coe_ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [Ico.mem, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, nat.pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (Ico 1 p).prod (λ x, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (nat.prime.pos ‹p.prime›)] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_fact, wilsons_lemma] end end zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, nat.pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, nat.pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, Ico.mem.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero_iff', or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2).fact : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2).fact := calc (a ^ (p / 2) * (p / 2).fact : zmod p) = (Ico 1 (p / 2).succ).prod (λ x, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_fact, prod_const, Ico.card, succ_sub_one]; simp ... = (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmod p).val) : by simp ... = (Ico 1 (p / 2).succ).prod (λ x, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (Ico 1 (p / 2).succ).prod (λ x, (a * x : zmod p).val_min_abs.nat_abs) : have (Ico 1 (p / 2).succ).prod (λ x, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).prod (λ _, -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2).fact : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_fact] private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (domain.mul_left_inj (show ((p / 2).fact : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.dvd_fact, not_le]; exact nat.div_lt_self hp.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap private lemma eisenstein_lemma_aux₁ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + (Ico 1 (p / 2).succ).sum (λ x, x) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2, calc (((Ico 1 (p / 2).succ).sum (λ x, a * x) : ℕ) : zmod 2) = (((Ico 1 (p / 2).succ).sum (λ x, (a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = ((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmod p).val) : ℕ) + ((Ico 1 (p / 2).succ).sum (λ x, (a * x) / p) : ℕ) : by simp only [val_cast_nat]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, sum_nat_cast, hp2] ... = _ : congr_arg2 (+) (calc (((Ico 1 (p / 2).succ).sum (λ x, ((a * x : ℕ) : zmod p).val) : ℕ) : zmod 2) = (Ico 1 (p / 2).succ).sum (λ x, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2)) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [sum_nat_cast] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + (((Ico 1 (p / 2).succ).sum (λ x, (a * x : zmod p).val_min_abs.nat_abs)) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, sum_nat_cast], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [sum_nat_cast]) rfl private lemma eisenstein_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ (Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, sum_nat_cast, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _$ finset.ext.2 $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext] else calc (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) = (Ico 1 (p / 2).succ).sum (λ a, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card) : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : (Ico 1 (p / 2).succ).sum (λ a, (a * q) / p) + (Ico 1 (q / 2).succ).sum (λ a, (a * p) / q) = (p / 2) * (q / 2) := have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), from disjoint_filter.2 $ λ x hx hpq hqp, have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp [*, nat.lt_succ_iff] at *; tauto) (nat.div_lt_self hp.pos dec_trivial), begin have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simp * at * end, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext.2 $ λ x, by have := le_total (x.2 * p) (x.1 * q); simp; tauto, by rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product]; simp variables (p q : ℕ) [fact p.prime] [fact q.prime] namespace zmod /-- The Legendre symbol of `a` and `p` is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a ^ (p / 2)` is `1` modulo `p` (by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”); * `-1` otherwise. -/ def legendre_sym (a p : ℕ) : ℤ := if (a : zmod p) = 0 then 0 else if (a : zmod p) ^ (p / 2) = 1 then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] : (legendre_sym a p : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [if_pos, ha, _root_.zero_pow (nat.div_pos (hp.two_le) (succ_pos 1)), int.cast_zero] }, cases hp.eq_two_or_odd with hp2 hp_odd, { resetI, subst p, have : ∀ (a : zmod 2), ((if a = 0 then 0 else if a ^ (2 / 2) = 1 then 1 else -1 : ℤ) : zmod 2) = a ^ (2 / 2), by exact dec_trivial, exact this a }, { change fact (p % 2 = 1) at hp_odd, resetI, rw if_neg ha, have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm, cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg this, int.cast_neg, int.cast_one], } } end lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) : legendre_sym a p = -1 ∨ legendre_sym a p = 1 := by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at * lemma legendre_sym_eq_zero_iff (a p : ℕ) : legendre_sym a p = 0 ↔ (a : zmod p) = 0 := begin split, { classical, contrapose, assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h, all_goals { rw h, norm_num } }, { assume ha, rw [legendre_sym, if_pos ha] } end /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} [hp1 : fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a p ha0; cases @neg_one_pow_eq_or ℤ _ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) := begin rw [euler_criterion p ha0, legendre_sym, if_neg ha0], split_ifs, { simp only [h, eq_self_iff_true] }, finish -- this is quite slow. I'm actually surprised that it can close the goal at all! end lemma eisenstein_lemma [hp1 : fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1)^(Ico 1 (p / 2).succ).sum (λ x, (x * a) / p) := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0] theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) : legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hp1 hpq0, eisenstein_lemma p hq1 hqp0, ← _root_.pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] -- move this instance fact_prime_two : fact (nat.prime 2) := nat.prime_two lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← mod_add_div p 2, add_comm, show p % 2 = 1, from hp1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma p (prime_ne_zero p 2 hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_pow_two_eq_two_iff [hp1 : fact (p % 2 = 1)] : (∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2, legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), resetI, rw _root_.fact at hp1, revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, clear hm, revert m, exact dec_trivial end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] : (∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p := if hpq : p = q then by resetI; subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_one hp1, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hqp0, if_neg hpq0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction, end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin haveI hp_odd : fact (p % 2 = 1) := odd_of_mod_four_eq_three hp3, haveI hq_odd : fact (q % 2 = 1) := odd_of_mod_four_eq_three hq3, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hpq0, if_neg hqp0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction end end zmod
889e7df75a455681d60302c565c0dc96745fdb30
49ffcd4736fa3bdcc1cdbb546d4c855d67c0f28a
/tests/lean/string_imp2.lean
1aba2106d575b1071bfe6f499803ee26c8d4d992
[ "Apache-2.0" ]
permissive
black13/lean
979e24d09e17b2fdf8ec74aac160583000086bc8
1a80ea9c8e28902cadbfb612896bcd45ba4ce697
refs/heads/master
1,626,839,620,164
1,509,113,016,000
1,509,122,889,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,985
lean
def f (s : string) : string := s ++ " " ++ s def g (s : string) : string := s.push ' ' ++ s.push '-' def h (s : string) : string := let it₁ := s.mk_iterator in let it₂ := it₁.next in it₁.next_to_string ++ "-" ++ it₂.next_to_string def r (s : string) : string := let it₁ := s.mk_iterator.to_end in let it₂ := it₁.prev in it₁.prev_to_string ++ "-" ++ it₂.prev_to_string def s (s : string) : string := let it₁ := s.mk_iterator.to_end in let it₂ := it₁.prev in (it₁.insert "abc").to_string ++ (it₂.insert "de").to_string #eval "hello" ++ "hello" #eval f "hello" #eval (f "αβ").length #eval "hello".to_list #eval "αβ".to_list #eval "".to_list #eval "αβγ".to_list #eval "αβγ".fold [] (λ r c, c::r) #eval "".fold 0 (λ r c, r+1) #eval "αβγ".fold 0 (λ r c, r+1) #eval "αβγ".mk_iterator.1 #eval "αβγ".mk_iterator.next.1 #eval "αβγ".mk_iterator.next.next.1 #eval "αβγ".mk_iterator.next.2 #eval "αβ".1 #eval string.empty #eval "αβ".push 'a' #eval g "α" #eval "".mk_iterator.curr #eval ("αβγ".mk_iterator.set_curr 'a').to_string #eval (("αβγ".mk_iterator.set_curr 'a').next.set_curr 'b').to_string #eval ((("αβγ".mk_iterator.set_curr 'a').next.set_curr 'b').next.set_curr 'c').to_string #eval ((("αβγ".mk_iterator.set_curr 'a').next.set_curr 'b').prev.set_curr 'c').to_string #eval ("abc".mk_iterator.set_curr '0').to_string #eval (("abc".mk_iterator.set_curr '0').next.set_curr '1').to_string #eval ((("abc".mk_iterator.set_curr '0').next.set_curr '1').next.set_curr '2').to_string #eval ((("abc".mk_iterator.set_curr '0').next.set_curr '1').prev.set_curr '2').to_string #eval ("abc".mk_iterator.set_curr (char.of_nat 955)).to_string #eval h "abc" #eval "abc".mk_iterator.next_to_string #eval ("a".push (char.of_nat 0)) ++ "bb" #eval (("a".push (char.of_nat 0)) ++ "αb").length #eval r "abc" #eval "abc".mk_iterator.to_end.prev_to_string #eval "".mk_iterator.has_next #eval "a".mk_iterator.has_next #eval "a".mk_iterator.next.has_next #eval "".mk_iterator.has_prev #eval "a".mk_iterator.next.has_prev #eval "αβ".mk_iterator.next.has_prev #eval "αβ".mk_iterator.next.prev.has_prev #eval ("αβ".mk_iterator.to_end.insert "abc").to_string #eval ("αβ".mk_iterator.next.insert "abc").to_string #eval s "αβ" #eval ("abcdef".mk_iterator.next.remove 2).to_string #eval ("abcdef".mk_iterator.next.next.remove 2).to_string #eval ("abcdef".mk_iterator.next.remove 3).to_string #eval (("abcdef".mk_iterator.next.next.next.remove 100).prev.set_curr 'a').to_string #eval ("abcdef".mk_iterator.next.next.next.remove 100).has_next #eval ("abcdef".mk_iterator.next.next.next.remove 100).prev.has_next #eval to_bool $ "abc" = "abc" #eval to_bool $ "abc" = "abd" #eval "abc".cmp "acc" #eval "abc".cmp "aac" #eval "abc".cmp "abc" #eval "abcd".cmp "abc" #eval "ab".cmp "abc" #eval "aβc".cmp "aγc" #eval "aβc".cmp "aac" #eval "aβc".cmp "aβc" #eval "aβcd".cmp "aβc" #eval "aβ".cmp "aβc" #eval "".cmp "a" #eval "a".cmp ""
e3f72328460509c7968402e3ce9d26e976d06f1f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Util/ShareCommon.lean
5cd559a9dec327fa46a1e86a31ec72acf5f5ee7b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,006
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.Data.HashSet import Lean.Data.HashMap import Lean.Data.PersistentHashMap import Lean.Data.PersistentHashSet open ShareCommon namespace Lean.ShareCommon def objectFactory := StateFactory.mk { Map := HashMap, mkMap := (mkHashMap ·), mapFind? := (·.find?), mapInsert := (·.insert) Set := HashSet, mkSet := (mkHashSet ·), setFind? := (·.find?), setInsert := (·.insert) } def persistentObjectFactory := StateFactory.mk { Map := PersistentHashMap, mkMap := fun _ => .empty, mapFind? := (·.find?), mapInsert := (·.insert) Set := PersistentHashSet, mkSet := fun _ => .empty, setFind? := (·.find?), setInsert := (·.insert) } abbrev ShareCommonT := _root_.ShareCommonT objectFactory abbrev PShareCommonT := _root_.ShareCommonT persistentObjectFactory abbrev ShareCommonM := ShareCommonT Id abbrev PShareCommonM := PShareCommonT Id @[specialize] def ShareCommonT.withShareCommon [Monad m] (a : α) : ShareCommonT m α := modifyGet fun s => s.shareCommon a @[specialize] def PShareCommonT.withShareCommon [Monad m] (a : α) : PShareCommonT m α := modifyGet fun s => s.shareCommon a instance ShareCommonT.monadShareCommon [Monad m] : MonadShareCommon (ShareCommonT m) where withShareCommon := ShareCommonT.withShareCommon instance PShareCommonT.monadShareCommon [Monad m] : MonadShareCommon (PShareCommonT m) where withShareCommon := PShareCommonT.withShareCommon @[inline] def ShareCommonT.run [Monad m] : ShareCommonT m α → m α := _root_.ShareCommonT.run @[inline] def PShareCommonT.run [Monad m] : PShareCommonT m α → m α := _root_.ShareCommonT.run @[inline] def ShareCommonM.run : ShareCommonM α → α := ShareCommonT.run @[inline] def PShareCommonM.run : PShareCommonM α → α := PShareCommonT.run def shareCommon (a : α) : α := (withShareCommon a : ShareCommonM α).run
9fc0d0dbd7fcd9ae83852a69bc2ff3cd29e778d6
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Elab/Tactic/Generalize.lean
ad58f9446873dc827b6d160577f0c5fe27f79b54
[ "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
2,862
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Meta.Tactic.Generalize import Lean.Meta.Check import Lean.Meta.Tactic.Intro import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic open Meta private def getAuxHypothesisName (stx : Syntax) : Option Name := if stx[1].isNone then none else some stx[1][0].getId private def getVarName (stx : Syntax) : Name := stx[4].getId private def evalGeneralizeFinalize (mvarId : MVarId) (e : Expr) (target : Expr) : MetaM (List MVarId) := do let tag ← Meta.getMVarTag mvarId let eType ← inferType e let u ← Meta.getLevel eType let mvar' ← Meta.mkFreshExprSyntheticOpaqueMVar target tag let rfl := mkApp2 (Lean.mkConst `Eq.refl [u]) eType e let val := mkApp2 mvar' e rfl assignExprMVar mvarId val let mvarId' := mvar'.mvarId! let (_, mvarId') ← Meta.introNP mvarId' 2 pure [mvarId'] private def evalGeneralizeWithEq (h : Name) (e : Expr) (x : Name) : TacticM Unit := liftMetaTactic fun mvarId => do let mvarId ← Meta.generalize mvarId e x false let mvarDecl ← getMVarDecl mvarId match mvarDecl.type with | Expr.forallE _ _ b _ => let (_, mvarId) ← Meta.intro1P mvarId let eType ← inferType e let u ← Meta.getLevel eType let eq := mkApp3 (Lean.mkConst `Eq [u]) eType e (mkBVar 0) let target := Lean.mkForall x BinderInfo.default eType $ Lean.mkForall h BinderInfo.default eq (b.liftLooseBVars 0 1) evalGeneralizeFinalize mvarId e target | _ => throwError "unexpected type after generalize" -- If generalizing fails, fall back to not replacing anything private def evalGeneralizeFallback (h : Name) (e : Expr) (x : Name) : TacticM Unit := liftMetaTactic fun mvarId => do let eType ← inferType e let u ← Meta.getLevel eType let mvarType ← Meta.getMVarType mvarId let eq := mkApp3 (Lean.mkConst `Eq [u]) eType e (mkBVar 0) let target := Lean.mkForall x BinderInfo.default eType $ Lean.mkForall h BinderInfo.default eq mvarType evalGeneralizeFinalize mvarId e target def evalGeneralizeAux (h? : Option Name) (e : Expr) (x : Name) : TacticM Unit := match h? with | none => liftMetaTactic fun mvarId => do let mvarId ← Meta.generalize mvarId e x false let (_, mvarId) ← Meta.intro1P mvarId pure [mvarId] | some h => evalGeneralizeWithEq h e x <|> evalGeneralizeFallback h e x @[builtinTactic Lean.Parser.Tactic.generalize] def evalGeneralize : Tactic := fun stx => withMainContext do let h? := getAuxHypothesisName stx let x := getVarName stx let e ← elabTerm stx[2] none evalGeneralizeAux h? e x end Lean.Elab.Tactic
7e6cb53a4ba77224fbe5211ee792331bae559bcb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/big_operators/intervals.lean
6e7f9c0f4bf0277a16f07e9b28aeede06ab36c2c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,081
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.basic import Mathlib.data.finset.intervals import Mathlib.PostPort universes u_1 v namespace Mathlib /-! # Results about big operators over intervals We prove results about big operators over intervals (mostly the `ℕ`-valued `Ico m n`). -/ namespace finset theorem sum_Ico_add {δ : Type u_1} [add_comm_monoid δ] (f : ℕ → δ) (m : ℕ) (n : ℕ) (k : ℕ) : (finset.sum (Ico m n) fun (l : ℕ) => f (k + l)) = finset.sum (Ico (m + k) (n + k)) fun (l : ℕ) => f l := Eq.subst (Ico.image_add m n k) Eq.symm (sum_image fun (x : ℕ) (hx : x ∈ Ico m n) (y : ℕ) (hy : y ∈ Ico m n) (h : k + x = k + y) => nat.add_left_cancel h) theorem prod_Ico_add {β : Type v} [comm_monoid β] (f : ℕ → β) (m : ℕ) (n : ℕ) (k : ℕ) : (finset.prod (Ico m n) fun (l : ℕ) => f (k + l)) = finset.prod (Ico (m + k) (n + k)) fun (l : ℕ) => f l := sum_Ico_add f m n k theorem sum_Ico_succ_top {δ : Type u_1} [add_comm_monoid δ] {a : ℕ} {b : ℕ} (hab : a ≤ b) (f : ℕ → δ) : (finset.sum (Ico a (b + 1)) fun (k : ℕ) => f k) = (finset.sum (Ico a b) fun (k : ℕ) => f k) + f b := sorry theorem prod_Ico_succ_top {β : Type v} [comm_monoid β] {a : ℕ} {b : ℕ} (hab : a ≤ b) (f : ℕ → β) : (finset.prod (Ico a (b + 1)) fun (k : ℕ) => f k) = (finset.prod (Ico a b) fun (k : ℕ) => f k) * f b := sum_Ico_succ_top hab fun (k : ℕ) => f k theorem sum_eq_sum_Ico_succ_bot {δ : Type u_1} [add_comm_monoid δ] {a : ℕ} {b : ℕ} (hab : a < b) (f : ℕ → δ) : (finset.sum (Ico a b) fun (k : ℕ) => f k) = f a + finset.sum (Ico (a + 1) b) fun (k : ℕ) => f k := sorry theorem prod_eq_prod_Ico_succ_bot {β : Type v} [comm_monoid β] {a : ℕ} {b : ℕ} (hab : a < b) (f : ℕ → β) : (finset.prod (Ico a b) fun (k : ℕ) => f k) = f a * finset.prod (Ico (a + 1) b) fun (k : ℕ) => f k := sum_eq_sum_Ico_succ_bot hab fun (k : ℕ) => f k theorem prod_Ico_consecutive {β : Type v} [comm_monoid β] (f : ℕ → β) {m : ℕ} {n : ℕ} {k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : ((finset.prod (Ico m n) fun (i : ℕ) => f i) * finset.prod (Ico n k) fun (i : ℕ) => f i) = finset.prod (Ico m k) fun (i : ℕ) => f i := Eq.subst (Ico.union_consecutive hmn hnk) Eq.symm (prod_union (Ico.disjoint_consecutive m n k)) theorem sum_range_add_sum_Ico {β : Type v} [add_comm_monoid β] (f : ℕ → β) {m : ℕ} {n : ℕ} (h : m ≤ n) : ((finset.sum (range m) fun (k : ℕ) => f k) + finset.sum (Ico m n) fun (k : ℕ) => f k) = finset.sum (range n) fun (k : ℕ) => f k := Ico.zero_bot m ▸ Ico.zero_bot n ▸ sum_Ico_consecutive f (nat.zero_le m) h theorem sum_Ico_eq_add_neg {δ : Type u_1} [add_comm_group δ] (f : ℕ → δ) {m : ℕ} {n : ℕ} (h : m ≤ n) : (finset.sum (Ico m n) fun (k : ℕ) => f k) = (finset.sum (range n) fun (k : ℕ) => f k) + -finset.sum (range m) fun (k : ℕ) => f k := sorry theorem sum_Ico_eq_sub {δ : Type u_1} [add_comm_group δ] (f : ℕ → δ) {m : ℕ} {n : ℕ} (h : m ≤ n) : (finset.sum (Ico m n) fun (k : ℕ) => f k) = (finset.sum (range n) fun (k : ℕ) => f k) - finset.sum (range m) fun (k : ℕ) => f k := sorry theorem sum_Ico_eq_sum_range {β : Type v} [add_comm_monoid β] (f : ℕ → β) (m : ℕ) (n : ℕ) : (finset.sum (Ico m n) fun (k : ℕ) => f k) = finset.sum (range (n - m)) fun (k : ℕ) => f (m + k) := sorry theorem prod_Ico_reflect {β : Type v} [comm_monoid β] (f : ℕ → β) (k : ℕ) {m : ℕ} {n : ℕ} (h : m ≤ n + 1) : (finset.prod (Ico k m) fun (j : ℕ) => f (n - j)) = finset.prod (Ico (n + 1 - m) (n + 1 - k)) fun (j : ℕ) => f j := sorry theorem sum_Ico_reflect {δ : Type u_1} [add_comm_monoid δ] (f : ℕ → δ) (k : ℕ) {m : ℕ} {n : ℕ} (h : m ≤ n + 1) : (finset.sum (Ico k m) fun (j : ℕ) => f (n - j)) = finset.sum (Ico (n + 1 - m) (n + 1 - k)) fun (j : ℕ) => f j := prod_Ico_reflect f k h theorem prod_range_reflect {β : Type v} [comm_monoid β] (f : ℕ → β) (n : ℕ) : (finset.prod (range n) fun (j : ℕ) => f (n - 1 - j)) = finset.prod (range n) fun (j : ℕ) => f j := sorry theorem sum_range_reflect {δ : Type u_1} [add_comm_monoid δ] (f : ℕ → δ) (n : ℕ) : (finset.sum (range n) fun (j : ℕ) => f (n - 1 - j)) = finset.sum (range n) fun (j : ℕ) => f j := prod_range_reflect f n @[simp] theorem prod_Ico_id_eq_factorial (n : ℕ) : (finset.prod (Ico 1 (n + 1)) fun (x : ℕ) => x) = nat.factorial n := sorry @[simp] theorem prod_range_add_one_eq_factorial (n : ℕ) : (finset.prod (range n) fun (x : ℕ) => x + 1) = nat.factorial n := sorry /-- Gauss' summation formula -/ theorem sum_range_id_mul_two (n : ℕ) : (finset.sum (range n) fun (i : ℕ) => i) * bit0 1 = n * (n - 1) := sorry /-- Gauss' summation formula -/ theorem sum_range_id (n : ℕ) : (finset.sum (range n) fun (i : ℕ) => i) = n * (n - 1) / bit0 1 := sorry
07880f21f6700c334502d826c22e5a25f5bf8441
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/measure_theory/measurable_space.lean
ff71c53a929e5630bd38c58377f7957962a951b6
[ "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
48,023
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, measurable function, dynkin system -/ local attribute [instance] classical.prop_decidable open set encodable open_locale classical universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort x} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type u) := (is_measurable : set α → Prop) (is_measurable_empty : is_measurable ∅) (is_measurable_compl : ∀s, is_measurable s → is_measurable sᶜ) (is_measurable_Union : ∀f:ℕ → set α, (∀i, is_measurable (f i)) → is_measurable (⋃i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := s.compl_compl ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.Union [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by { rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union (λ n, ⋃ b ∈ decode2 β n, f b) (λ n, encodable.Union_decode2_cases is_measurable.empty h) } lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋃b∈s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋃₀ s) := by rw sUnion_eq_bUnion; exact is_measurable.bUnion hs h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by by_cases p; simp [h, hf, is_measurable.empty] lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := is_measurable.compl_iff.1 $ by rw compl_Inter; exact is_measurable.Union (λ b, (h b).compl) lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.compl_iff.1 $ by rw compl_bInter; exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := by rw sInter_eq_bInter; exact is_measurable.bInter hs h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := by by_cases p; simp [h, hf, is_measurable.univ] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by rw union_eq_Union; exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by rw inter_eq_compl_compl_union_compl; exact (h₁.compl.union h₂.compl).compl lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ end @[ext] lemma measurable_space.ext : ∀{m₁ m₂ : measurable_space α}, (∀s:set α, m₁.is_measurable s ↔ m₂.is_measurable s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λm₁ m₂, m₁.is_measurable ≤ m₂.is_measurable, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀u∈s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀s, generate_measurable s → generate_measurable sᶜ | union : ∀f:ℕ → set α, (∀n, generate_measurable (f n)) → generate_measurable (⋃i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀t∈s, m.is_measurable t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} {m : measurable_space α} : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable t} = g) : measurable_space α := { is_measurable := λs, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by rw [← hs] {occs := occurrences.pos [1] }; refl /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λm, {t | @is_measurable α m t}) := { gc := assume s m, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λg hg, measurable_space.mk_of_closure g $ le_antisymm hg $ generate_from_le_iff.1 $ le_refl _, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable := λs, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (assume s, s.symm ▸ @is_measurable_empty _ ⊥) (assume s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂m∈ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λm, {s | @is_measurable _ m s }) (infi m) ↔ _, by rw (@gi_generate_from α).gc.u_infi; simp; refl theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable ∪ m₂.is_measurable) s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable (⋃₀ (measurable_space.is_measurable '' ms)) s := begin change @is_measurable _ (generate_from _) _ ↔ _, dsimp [generate_from], rw (show (⨆ (b : measurable_space α) (H : b ∈ ms), set_of (is_measurable b)) = (⋃₀(is_measurable '' ms)), { ext, simp only [exists_prop, mem_Union, sUnion_image, mem_set_of_eq], refl, }) end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable (⋃i, (m i).is_measurable) s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable := λs, m.is_measurable $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by rw [preimage_Union]; exact m.is_measurable_Union _ hf } @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable := λs, ∃s', m.is_measurable s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃i, s' i, m.is_measurable_Union _ (λi, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥:measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} :(⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤:measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [ measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma subsingleton.measurable [measurable_space α] [measurable_space β] [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable_id [measurable_space α] : measurable (@id α) := λ t, id lemma measurable.comp [measurable_space α] [measurable_space β] [measurable_space γ] {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀t∈s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h lemma measurable.piecewise [measurable_space α] [measurable_space β] {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end lemma measurable_const {α β} [measurable_space α] [measurable_space β] {a : α} : measurable (λb:β, a) := by { intros s hs, by_cases a ∈ s; simp [*, preimage] } lemma measurable.indicator [measurable_space α] [measurable_space β] [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one {α β} [measurable_space α] [has_one α] [measurable_space β] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] [measurable_space α] [measurable_space β] {f : β → α} (h : ∀ y, is_measurable {x | f x = y}) : measurable f := begin assume s hs, show is_measurable {x | f x ∈ s}, have : {x | f x ∈ s} = ⋃ (n ∈ s), {x | f x = n}, { ext, simp }, rw this, simp [is_measurable.Union, is_measurable.Union_Prop, h] end lemma measurable_unit [measurable_space α] (f : unit → α) : measurable f := have f = (λu, f ()) := funext $ assume ⟨⟩, rfl, by rw this; exact measurable_const section nat lemma measurable_from_nat [measurable_space α] {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat [measurable_space α] {f : α → ℕ} : (∀ k, is_measurable {x | f x = k}) → measurable f := measurable_to_encodable lemma measurable_find_greatest [measurable_space α] {p : ℕ → α → Prop} : ∀ {N}, (∀ k ≤ N, is_measurable {x | nat.find_greatest (λ n, p n x) N = k}) → measurable (λ x, nat.find_greatest (λ n, p n x) N) | 0 := assume h s hs, show is_measurable {x : α | (nat.find_greatest (λ n, p n x) 0) ∈ s}, begin by_cases h : 0 ∈ s, { convert is_measurable.univ, simp only [nat.find_greatest_zero, h] }, { convert is_measurable.empty, simp only [nat.find_greatest_zero, h], refl } end | (n + 1) := assume h, begin apply measurable_to_nat, assume k, by_cases hk : k ≤ n + 1, { exact h k hk }, { have := is_measurable.empty, rw ← set_of_false at this, convert this, funext, rw eq_false, assume h, rw ← h at hk, have := nat.find_greatest_le, contradiction } end end nat section subtype instance {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe [measurable_space α] {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λa:α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image [measurable_space α] {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover [measurable_space α] [measurable_space β] {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λa:s, f a)) (hd : measurable (λa:t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_space α] [measurable_space β] [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable_fst [measurable_space α] [measurable_space β] : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).1) := measurable_fst.comp hf lemma measurable_snd [measurable_space α] [measurable_space β] : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).2) := measurable_snd.comp hf lemma measurable.prod [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf₁ : measurable (λa, (f a).1)) (hf₂ : measurable (λa, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₁) (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₂) lemma measurable.prod_mk [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λa:α, (f a, g a)) := measurable.prod hf hg lemma is_measurable.prod [measurable_space α] [measurable_space β] {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (set.prod s t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) end prod section pi instance measurable_space.pi {α : Type u} {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (Πa, β a) := ⨆a, (m a).comap (λb, b a) lemma measurable_pi_apply {α : Type u} {β : α → Type v} [Πa, measurable_space (β a)] (a : α) : measurable (λf:Πa, β a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable_pi_lambda {α : Type u} {β : α → Type v} {γ : Type w} [Πa, measurable_space (β a)] [measurable_space γ] (f : γ → Πa, β a) (hf : ∀a, measurable (λc, f c a)) : measurable f := measurable.of_le_map $ supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) end pi instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_rec {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : @measurable (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by rwa [preimage_image_eq]; exact (assume a b, sum.inl.inj), have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by rw [this]; exact is_measurable.empty⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by rw [← image_univ]; exact is_measurable.univ.inl_image lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by rw [this]; exact is_measurable.empty, show is_measurable (sum.inr ⁻¹' _), by rwa [preimage_image_eq]; exact (assume a b, sum.inr.inj)⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by rw [← image_univ]; exact is_measurable_inr_image is_measurable.univ end sum instance {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) namespace measurable_equiv instance (α β) [measurable_space α] [measurable_space β] : has_coe_to_fun (measurable_equiv α β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : (e : α → β) = e.to_equiv := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : measurable_equiv α α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } /-- The composition of equivalences between measurable spaces. -/ def trans [measurable_space α] [measurable_space β] [measurable_space γ] (ab : measurable_equiv α β) (bc : measurable_equiv β γ) : measurable_equiv α γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } lemma trans_to_equiv {α β} [measurable_space α] [measurable_space β] [measurable_space γ] (e : measurable_equiv α β) (f : measurable_equiv β γ) : (e.trans f).to_equiv = e.to_equiv.trans f.to_equiv := rfl /-- The inverse of an equivalence between measurable spaces. -/ def symm [measurable_space α] [measurable_space β] (ab : measurable_equiv α β) : measurable_equiv β α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } lemma symm_to_equiv {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : e.symm.to_equiv = e.to_equiv.symm := rfl /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : measurable_equiv α β := { to_equiv := equiv.cast h, measurable_to_fun := by substI h; substI hi; exact measurable_id, measurable_inv_fun := by substI h; substI hi; exact measurable_id } protected lemma measurable {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : measurable (e : α → β) := e.measurable_to_fun protected lemma measurable_coe_iff {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : β → γ} (e : measurable_equiv α β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λh, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α × γ) (β × δ) := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := measurable.prod_mk (ab.measurable_to_fun.comp (measurable.fst measurable_id)) (cd.measurable_to_fun.comp (measurable.snd measurable_id)), measurable_inv_fun := measurable.prod_mk (ab.measurable_inv_fun.comp (measurable.fst measurable_id)) (cd.measurable_inv_fun.comp (measurable.snd measurable_id)) } /-- Products of measurable spaces are symmetric. -/ def prod_comm [measurable_space α] [measurable_space β] : measurable_equiv (α × β) (β × α) := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id), measurable_inv_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id) } /-- Sums of measurable spaces are symmetric. -/ def sum_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α ⊕ γ) (β ⊕ δ) := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod [measurable_space α] [measurable_space β] (s : set α) (t : set β) : measurable_equiv (s.prod t) (s × t) := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable.prod_mk measurable_id.subtype_coe.fst.subtype_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable.prod_mk measurable_id.fst.subtype_coe measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : measurable_equiv (univ : set α) α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton [measurable_space α] (a:α) : measurable_equiv ({a} : set α) unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image [measurable_space α] [measurable_space β] (f : α → β) (s : set α) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv s (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := assume t ⟨u, (hu : is_measurable u), eq⟩, begin clear_, subst eq, show is_measurable {x : f '' s | ((equiv.set.image f s hf).inv_fun x).val ∈ u}, have : ∀(a ∈ s) (h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λa ha h, (classical.some_spec h).2, rw show {x:f '' s | ((equiv.set.image f s hf).inv_fun x).val ∈ u} = subtype.val ⁻¹' (f '' u), by ext ⟨b, a, hbs, rfl⟩; simp [equiv.set.image, equiv.set.image_of_inj_on, hf, this _ hbs], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range [measurable_space α] [measurable_space β] (f : α → β) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv α (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inl : set (α ⊕ β)) α := { to_fun := λab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by cases p; contradiction, this.elim end, inv_fun := λa, ⟨sum.inl a, a, rfl⟩, left_inv := assume ⟨ab, a, eq⟩, by subst eq; refl, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inr : set (α ⊕ β)) β := { to_fun := λab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by cases p; contradiction, this.elim end, inv_fun := λb, ⟨sum.inr b, b, rfl⟩, left_inv := assume ⟨ab, b, eq⟩, by subst eq; refl, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv ((α ⊕ β) × γ) ((α × γ) ⊕ (β × γ)) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (assume ⟨ab, c⟩ s, by cases ab; simp [set.prod_eq]) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp (measurable.fst measurable_id)).prod_mk (measurable.snd measurable_id)) ((measurable_inr.comp (measurable.fst measurable_id)).prod_mk (measurable.snd measurable_id)) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv (α × (β ⊕ γ)) ((α × β) ⊕ (α × γ)) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : measurable_equiv ((α ⊕ β) × (γ ⊕ δ)) (((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ))) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv namespace measurable_equiv end measurable_equiv namespace measurable_space /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀{a}, has a → has aᶜ) (has_Union_nat : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, has (f i)) → has (⋃i, f i)) namespace dynkin_system @[ext] lemma ext : ∀{d₁ d₂ : dynkin_system α}, (∀s:set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀i, d.has (f i)) : d.has (⋃i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by rw union_eq_Union; exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := d.has_compl_iff.1 begin simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λm₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable, has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀t∈s, generate_has t | empty : generate_has ∅ | compl : ∀{a}, generate_has a → generate_has aᶜ | Union : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, generate_has (f i)) → generate_has (⋃i, f i) /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λt, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by by_cases x ∈ s; simp [h], by rw [this]; from d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _), has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀t∈s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_inter {s : set (set α)} (hs : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ lemma generate_from_eq {s : set (set α)} (hs : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by rw [of_measurable_space_to_measurable_space]; from (generate_le _ $ assume t ht, is_measurable_generate_from ht)) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} {m : measurable_space α} (h_eq : m = generate_from s) (h_inter : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) (h_empty : C ∅) (h_basic : ∀t∈s, C t) (h_compl : ∀t, m.is_measurable t → C t → C tᶜ) (h_union : ∀f:ℕ → set α, (∀i j, i ≠ j → f i ∩ f j ⊆ ∅) → (∀i, m.is_measurable (f i)) → (∀i, C (f i)) → C (⋃i, f i)) : ∀{t}, m.is_measurable t → C t := have eq : m.is_measurable = dynkin_system.generate_has s, by rw [h_eq, dynkin_system.generate_from_eq h_inter]; refl, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by rw [eq]; exact ht) (assume f hf ht, h_union f hf $ assume i, by rw [eq]; exact ht _) end measurable_space
da3aba7807d1bdcdf3921af6f8ec81639c38f48e
54f4ad05b219d444b709f56c2f619dd87d14ec29
/my_project/src/love11_logical_foundations_of_mathematics_exercise_sheet.lean
8900f0b577b707c3c50a2ade9064b2febbbbbe71
[]
no_license
yizhou7/learning-lean
8efcf838c7276e235a81bd291f467fa43ce56e0a
91fb366c624df6e56e19555b2e482ce767cd8224
refs/heads/master
1,675,649,087,737
1,609,022,281,000
1,609,022,281,000
272,072,779
0
0
null
null
null
null
UTF-8
Lean
false
false
1,951
lean
import .love11_logical_foundations_of_mathematics_demo /-! # LoVe Exercise 11: Logical Foundations of Mathematics -/ set_option pp.beta true namespace LoVe /-! ## Question 1: Vectors as Subtypes Recall the definition of vectors from the demo: -/ #check vector /-! The following function adds two lists of integers elementwise. If one function is longer than the other, the tail of the longer function is truncated. -/ def list.add : list ℤ → list ℤ → list ℤ | [] [] := [] | (x :: xs) (y :: ys) := (x + y) :: list.add xs ys | [] (y :: ys) := [] | (x :: xs) [] := [] /-! 1.1. Show that if the lists have the same length, the resulting list also has that length. -/ lemma list.length_add : ∀(xs : list ℤ) (ys : list ℤ) (h : list.length xs = list.length ys), list.length (list.add xs ys) = list.length xs | [] [] := sorry | (x :: xs) (y :: ys) := sorry | [] (y :: ys) := sorry | (x :: xs) [] := sorry /-! 1.2. Define componentwise addition on vectors using `list.add` and `length.length_add`. -/ def vector.add {n : ℕ} : vector ℤ n → vector ℤ n → vector ℤ n := sorry /-! 1.3. Show that `list.add` and `vector.add` are commutative. -/ lemma list.add.comm : ∀(xs : list ℤ) (ys : list ℤ), list.add xs ys = list.add ys xs := sorry lemma vector.add.comm {n : ℕ} (x y : vector ℤ n) : vector.add x y = vector.add y x := sorry /-! ## Question 2: Integers as Quotients Recall the construction of integers from the lecture, not to be confused with Lean's predefined type `int` (= `ℤ`): -/ #check int.rel #check int.rel_iff #check int /-! 2.1. Define negation on these integers. -/ def int.neg : int → int := sorry /-! 2.2. Prove the following lemmas about negation. -/ lemma int.neg_eq (p n : ℕ) : int.neg ⟦(p, n)⟧ = ⟦(n, p)⟧ := sorry lemma int.neg_neg (a : int) : int.neg (int.neg a) = a := sorry end LoVe
b8270d1f5d56e80ba73defbe032c8024a09f6fb9
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.15.lean
6216e9b863b11cce4a72169881f4c5516c46e612
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
202
lean
import standard structure point (A : Type) := mk :: (x : A) (y : A) inductive color := red | green | blue -- BEGIN structure color_point (A : Type) extends private point A := mk :: (c : color) -- END
295585b15a0722952f6c0b937982f490eb7ad040
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/field_theory/splitting_field.lean
b8435f2f41056e8752f5cf5cd4c320b33559a02e
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,450
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.adjoin_root import ring_theory.algebra_tower import ring_theory.algebraic import ring_theory.polynomial import field_theory.minimal_polynomial import linear_algebra.finite_dimensional noncomputable theory open_locale classical big_operators universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial variables [field α] [field β] [field γ] open polynomial section splits variables (i : α →+* β) /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : polynomial α} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : β →+* γ) {f : polynomial α} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : polynomial α} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : α} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_id_iff_splits {f : polynomial α} : (f.map i).splits (ring_hom.id β) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial α} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end theorem splits_prod_iff {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : polynomial β} (h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id β) p) : p.degree = 1 := begin rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, wf_dvd_monoid.induction_on_irreducible (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 ::ₘ s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : polynomial α} (hf : f.splits i) (hfd : f.degree ≠ 0) : β := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : polynomial α} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd theorem roots_map {f : polynomial α} (hf : f.splits $ ring_hom.id α) : (f.map i).roots = (f.roots).map i := if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else have hmf0 : f.map i ≠ 0 := map_ne_zero hf0, let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in have h1 : ∀ p ∈ m.map (λ r, X - C r), (p : _) ≠ 0, from multiset.forall_mem_map_iff.2 $ λ _ _, X_sub_C_ne_zero _, have h2 : ∀ p ∈ m.map (λ r, X - C (i r)), (p : _) ≠ 0, from multiset.forall_mem_map_iff.2 $ λ _ _, X_sub_C_ne_zero _, begin rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢, rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add, map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C], rw [roots_multiset_prod _ h2, multiset.bind_map, roots_multiset_prod _ h1, multiset.bind_map], simp_rw roots_X_sub_C, rw [multiset.bind_cons, multiset.bind_zero, add_zero, multiset.bind_cons, multiset.bind_zero, add_zero, multiset.map_id'] end lemma eq_prod_roots_of_splits {p : polynomial α} {i : α →+* β} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] }, obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 := by rwa hs at map_ne_zero, have ne_zero_of_mem : ∀ (p : polynomial β), p ∈ s.map (λ a, X - C a) → p ≠ 0, { intros p mem, obtain ⟨a, _, rfl⟩ := multiset.mem_map.mp mem, apply X_sub_C_ne_zero }, have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s, { refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _, intros a s ih, rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C, multiset.cons_add, zero_add] }, rw [hs, roots_mul prod_ne_zero, roots_C, zero_add, roots_multiset_prod _ ne_zero_of_mem, map_bind_roots_eq] end lemma eq_X_sub_C_of_splits_of_single_root {x : α} {h : polynomial α} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end lemma nat_degree_multiset_prod {R : Type*} [integral_domain R] {s : multiset (polynomial R)} (h : ∀ p ∈ s, p ≠ (0 : polynomial R)) : nat_degree s.prod = (s.map nat_degree).sum := begin revert h, refine s.induction_on _ _, { simp }, intros p s ih h, have hs : ∀ p ∈ s, p ≠ (0 : polynomial R) := λ p hp, h p (multiset.mem_cons_of_mem hp), have hprod : s.prod ≠ 0 := multiset.prod_ne_zero (λ p hp, hs p hp), rw [multiset.prod_cons, nat_degree_mul (h p (multiset.mem_cons_self _ _)) hprod, ih hs, multiset.map_cons, multiset.sum_cons], end lemma nat_degree_eq_card_roots {p : polynomial α} {i : α →+* β} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] }, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), rw eq_prod_roots_of_splits hsplit at map_ne_zero, conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] }, have : ∀ p' ∈ (map i p).roots.map (λ a, X - C a), p' ≠ (0 : polynomial β), { intros p hp, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.mp hp, exact X_sub_C_ne_zero _ }, simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero), nat_degree_multiset_prod this] end lemma degree_eq_card_roots {p : polynomial α} {i : α →+* β} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := factors_unique (λ p hp, irreducible_of_factor _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map' C : units β →* units (polynomial β)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (map_ne_zero hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_monoid.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β →+* γ) {f : polynomial α} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A monic polynomial `p` that has as much roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {p : polynomial α} (hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) : (multiset.map (λ (a : α), X - C a) p.roots).prod = p := begin have hprodmonic : (multiset.map (λ (a : α), X - C a) p.roots).prod.monic, { simp only [prod_multiset_root_eq_finset_root (ne_zero_of_monic hmonic), monic_prod_of_monic, monic_X_sub_C, monic_pow, forall_true_iff] }, have hdegree : (multiset.map (λ (a : α), X - C a) p.roots).prod.nat_degree = p.nat_degree, { rw [← hroots, nat_degree_multiset_prod], simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat, multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map], intros x y, simp only [multiset.mem_map] at y, rcases y with ⟨a, ha, rfl⟩, exact X_sub_C_ne_zero a }, obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p, have qzero : q ≠ 0, { rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq }, have degp : p.nat_degree = (multiset.map (λ (a : α), X - C a) p.roots).prod.nat_degree + q.nat_degree, { nth_rewrite 0 [hq], simp only [nat_degree_mul (ne_zero_of_monic hprodmonic) qzero] }, have degq : q.nat_degree = 0, { rw hdegree at degp, exact (add_right_inj p.nat_degree).mp (tactic.ring_exp.add_pf_sum_z degp rfl).symm }, obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq), have hassoc : associated (multiset.map (λ (a : α), X - C a) p.roots).prod p, { rw associated, use u, rw [hu, ← hq] }, exact eq_of_monic_of_associated hprodmonic hmonic hassoc end /-- A polynomial `p` that has as much roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C {p : polynomial α} (hroots : p.roots.card = p.nat_degree) : (C p.leading_coeff) * (multiset.map (λ (a : α), X - C a) p.roots).prod = p := begin by_cases hzero : p = 0, { rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree, { rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots, coe_norm_unit, nat_degree_C, add_zero], }, have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero) hrootsnorm, rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod, calc (C p.leading_coeff) * (multiset.map (λ (a : α), X - C a) p.roots).prod = p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) : by rw [hprod, mul_comm, mul_assoc, ← C_mul] ... = p * C 1 : by field_simp [hcoeff] ... = p : by simp only [mul_one, ring_hom.map_one], }, end /-- A polynomial splits if and only if it has as much roots as its degree. -/ lemma splits_iff_card_roots {p : polynomial α} : splits (ring_hom.id α) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, apply (splits_iff_exists_multiset (ring_hom.id α)).2, use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end end splits end polynomial section embeddings variables (F : Type*) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minimal_polynomial {R : Type*} [comm_ring R] [algebra F R] (x : R) (hx : is_integral F x) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minimal_polynomial hx) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.lift_hom _ x $ minimal_polynomial.aeval hx) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minimal_polynomial.dvd hx hp, λ y, let ⟨p, _, hp⟩ := (subalgebra.ext_iff.1 (algebra.adjoin_singleton_eq_range F x) y).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset -- Speed up the following proof. local attribute [irreducible] minimal_polynomial -- TODO: Why is this so slow? /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, ∃ H : is_integral F x, polynomial.splits (algebra_map F L) (minimal_polynomial H)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3), letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minimal_polynomial H5).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minimal_polynomial.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minimal_polynomial.dvd _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minimal_polynomial.aeval H1] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minimal_polynomial.degree_pos H5)).symm, exact ⟨subalgebra.of_under _ _ $ (adjoin_root.lift_hom (minimal_polynomial H5) y hy).comp $ alg_equiv.adjoin_singleton_equiv_adjoin_root_minimal_polynomial _ _ H5⟩ end end embeddings namespace polynomial variables [field α] [field β] [field γ] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : polynomial α) : polynomial α := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X instance irreducible_factor (f : polynomial α) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end theorem factor_dvd_of_not_is_unit {f : polynomial α} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : polynomial α} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial α} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : polynomial α) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : polynomial α) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : polynomial α) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : polynomial α} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/ def splitting_field_aux (n : ℕ) : Π {α : Type u} [field α], by exactI Π (f : polynomial α), f.nat_degree = n → Type u := nat.rec_on n (λ α _ _ _, α) $ λ n ih α _ f hf, by exactI ih f.remove_factor (nat_degree_remove_factor' hf) namespace splitting_field_aux theorem succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) : splitting_field_aux (n+1) f hfn = splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl instance field (n : ℕ) : Π {α : Type u} [field α], by exactI Π {f : polynomial α} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) := nat.rec_on n (λ α _ _ _, ‹field α›) $ λ n ih α _ f hf, ih _ instance inhabited {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n) : inhabited (splitting_field_aux n f hfn) := ⟨37⟩ instance algebra (n : ℕ) : Π {α : Type u} [field α], by exactI Π {f : polynomial α} (hfn : f.nat_degree = n), algebra α (splitting_field_aux n f hfn) := nat.rec_on n (λ α _ _ _, by exactI algebra.id α) $ λ n ih α _ f hfn, by exactI @@algebra.comap.algebra _ _ _ _ _ _ _ (ih _) instance algebra' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := splitting_field_aux.algebra n _ instance algebra'' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra α (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra (n+1) hfn instance algebra''' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n _ instance scalar_tower {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl instance scalar_tower' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl theorem algebra_map_succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) : by exact algebra_map α (splitting_field_aux _ _ hfn) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp (adjoin_root.of f.factor) := rfl protected theorem splits (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n), splits (algebra_map α $ splitting_field_aux n f hfn) f := nat.rec_on n (λ α _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih α _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ _) } theorem exists_lift (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n) {β : Type*} [field β], by exactI ∀ (j : α →+* β) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* β, k.comp (algebra_map _ _) = j := nat.rec_on n (λ α _ _ _ β _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih α _ f hf β _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n), algebra.adjoin α (↑(f.map $ algebra_map α $ splitting_field_aux n f hfn).roots.to_finset : set (splitting_field_aux n f hfn)) = ⊤ := nat.rec_on n (λ α _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih α _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map α (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢, rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_cons, multiset.to_finset_zero, insert_emptyc_eq, finset.coe_singleton, algebra.adjoin_union, ← set.image_singleton, algebra.adjoin_algebra_map α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.range_under_adjoin α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), ih, subalgebra.res_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : polynomial α) := splitting_field_aux _ f rfl namespace splitting_field variables (f : polynomial α) instance : field (splitting_field f) := splitting_field_aux.field _ _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ instance : algebra α (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map α (splitting_field f)) f := splitting_field_aux.splits _ _ _ variables [algebra α β] (hb : splits (algebra_map α β) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[α] β := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin α (↑(f.map (algebra_map α $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ _ end splitting_field variables (α β) [algebra α β] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : polynomial α) : Prop := (splits [] : splits (algebra_map α β) f) (adjoin_roots [] : algebra.adjoin α (↑(f.map (algebra_map α β)).roots.to_finset : set β) = ⊤) namespace is_splitting_field variables {α} instance splitting_field (f : polynomial α) : is_splitting_field α (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {α β γ} [algebra β γ] [algebra α γ] [is_scalar_tower α β γ] variables {α} instance map (f : polynomial α) [is_splitting_field α γ f] : is_splitting_field β γ (f.map $ algebra_map α β) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits γ f }, subalgebra.res_inj α $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.res_top, eq_top_iff, ← adjoin_roots γ f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin β _ _ _ _ _ _ hx }⟩ variables {α} (β) theorem splits_iff (f : polynomial α) [is_splitting_field α β f] : polynomial.splits (ring_hom.id α) f ↔ (⊤ : subalgebra α β) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots β f ▸ (roots_map (algebra_map α β) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl α _ ▸ ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits β f) }⟩ theorem mul (f g : polynomial α) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field α β f] [is_splitting_field β γ (g.map $ algebra_map α β)] : is_splitting_field α γ (f * g) := ⟨(is_scalar_tower.algebra_map_eq α β γ).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits β f)) ((splits_map_iff _ _).1 (splits γ $ g.map $ algebra_map α β)), by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map α γ) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union, is_scalar_tower.algebra_map_eq α β γ, ← map_map, roots_map (algebra_map β γ) ((splits_id_iff_splits $ algebra_map α β).2 $ splits β f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.range_under_adjoin, ← map_map, adjoin_roots, subalgebra.res_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra α γ] (f : polynomial α) [is_splitting_field α β f] (hf : polynomial.splits (algebra_map α γ) f) : β →ₐ[α] γ := if hf0 : f = 0 then (algebra.of_id α γ).comp $ (algebra.bot_equiv α β : (⊥ : subalgebra α β) →ₐ[α] α).comp $ by { rw ← (splits_iff β f).1 (show f.splits (ring_hom.id α), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots β f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minimal_polynomial.dvd _ this⟩) }) algebra.to_top theorem finite_dimensional (f : polynomial α) [is_splitting_field α β f] : finite_dimensional α β := finite_dimensional.iff_fg.2 $ @algebra.coe_top α β _ _ _ ▸ adjoin_roots β f ▸ fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy, if hf : f = 0 then by { rw [hf, map_zero, roots_zero] at hy, cases hy } else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩) /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : polynomial α) [is_splitting_field α β f] : β ≃ₐ[α] splitting_field f := begin refine alg_equiv.of_bijective (lift β f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift β f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional β f, have : finite_dimensional.findim α β = finite_dimensional.findim α (splitting_field f) := le_antisymm (linear_map.findim_le_findim_of_injective (show function.injective (lift β f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field))) (linear_map.findim_le_findim_of_injective (show function.injective (lift (splitting_field f) f $ splits β f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits β f : f.splitting_field →+* β))), change function.surjective (lift β f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_findim_eq_findim this).1 _, exact ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field) end end is_splitting_field end splitting_field end polynomial
04d8a12719cd978ec376955760e2667562d0625f
e7de183433d907275be4926240a8c8ddb5915131
/recipes/plain-lean4.lean
8392bde01b15314227eec4f6fc410dfc8e887d65
[ "MIT" ]
permissive
cpitclaudel/alectryon
70b01086e9b4aee4f18017621578004903ce74d3
11e8cdc8395d66858baa7371b6cf8e827ca38f4a
refs/heads/master
1,683,666,125,135
1,683,473,634,000
1,683,473,844,000
260,735,576
206
29
MIT
1,655,000,579,000
1,588,439,321,000
HTML
UTF-8
Lean
false
false
383
lean
/- To compile: alectryon --frontend lean4 plain-lean4.lean # Lean → HTML; produces ‘plain-lean4.lean.html’ -/ -- Queries: #check Nat #check Bool -- Proofs: theorem test (p q : Prop) (hp : p) (hq : q): p ∧ q ↔ q ∧ p := by apply Iff.intro . intro h apply And.intro . exact hq . exact hp . intro h apply And.intro . exact hp . exact hq
44105b63a92a6a5d4937dfe169ff01182a8ea524
67190c9aacc0cac64fb4463d93e84c696a5be896
/Lists of exercises/List 5/cap12-Domingues.lean
6e98e9749385bd76691f5ae043d12543588845a8
[]
no_license
lucasresck/Discrete-Mathematics
ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738
0a08081c5f393e5765259d3f1253c3a6dd043dac
refs/heads/master
1,596,627,857,734
1,573,411,500,000
1,573,411,500,000
212,489,764
0
0
null
null
null
null
UTF-8
Lean
false
false
5,303
lean
/- aluno: - Lucas Emanuel Resck Domingues -/ open set -- ex 1 section variable U : Type variables A B C : set U example : ∀ x, x ∈ A ∩ C → x ∈ A ∪ B := assume x, show x ∈ A ∩ C → x ∈ A ∪ B, from assume h1 : x ∈ A ∩ C, show x ∈ A ∪ B, from or.inl h1.left example : ∀ x, x ∈ -(A ∪ B) → x ∈ -A := assume x, show x ∈ -(A ∪ B) → x ∈ -A, from assume h1 : x ∈ -(A ∪ B), show x ∈ -A, from assume h2 : x ∈ A, show false, from h1 $ or.inl h2 end -- ex 2 section variable {U : Type} /- defining "disjoint" -/ def disj (A B : set U) : Prop := ∀ ⦃x⦄, x ∈ A → x ∈ B → false example (A B : set U) (h : ∀ x, ¬ (x ∈ A ∧ x ∈ B)) : disj A B := assume x, assume h1 : x ∈ A, assume h2 : x ∈ B, have h3 : x ∈ A ∧ x ∈ B, from and.intro h1 h2, show false, from h x h3 -- notice that we do not have to mention x when applying -- h : disj A B example (A B : set U) (h1 : disj A B) (x : U) (h2 : x ∈ A) (h3 : x ∈ B) : false := h1 h2 h3 -- the same is true of ⊆ example (A B : set U) (x : U) (h : A ⊆ B) (h1 : x ∈ A) : x ∈ B := h h1 example (A B C D : set U) (h1 : disj A B) (h2 : C ⊆ A) (h3 : D ⊆ B) : disj C D := assume x, show x ∈ C → x ∈ D → false, from assume h4 : x ∈ C, show x ∈ D → false, from assume h5 : x ∈ D, show false, from h1 (h2 h4) (h3 h5) end -- ex 3 section variables {I U : Type} variables {A B : I → set U} def Union (A : I → set U) : set U := { x | ∃ i : I, x ∈ A i } def Inter (A : I → set U) : set U := { x | ∀ i : I, x ∈ A i } notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r theorem Inter.intro {x : U} (h : ∀ i, x ∈ A i) : x ∈ ⋂ i, A i := by simp; assumption @[elab_simple] theorem Inter.elim {x : U} (h : x ∈ ⋂ i, A i) (i : I) : x ∈ A i := by simp at h; apply h theorem Union.intro {x : U} (i : I) (h : x ∈ A i) : x ∈ ⋃ i, A i := by {simp, existsi i, exact h} theorem Union.elim {b : Prop} {x : U} (h₁ : x ∈ ⋃ i, A i) (h₂ : ∀ (i : I), x ∈ A i → b) : b := by {simp at h₁, cases h₁ with i h, exact h₂ i h} end section variables {I U : Type} variables (A : I → set U) (B : I → set U) (C : set U) example : (⋂ i, A i) ∩ (⋂ i, B i) ⊆ (⋂ i, A i ∩ B i) := assume x, show x ∈ (⋂ i, A i) ∩ (⋂ i, B i) → x ∈ (⋂ i, A i ∩ B i), from assume h1 : x ∈ (⋂ i, A i) ∩ (⋂ i, B i), have h2 : x ∈ (⋂ i, A i), from h1.left, have h3 : x ∈ (⋂ i, B i), from h1.right, show x ∈ (⋂ i, A i ∩ B i), from Inter.intro $ assume i, have h4 : x ∈ A i, from Inter.elim h2 i, have h5 : x ∈ B i, from Inter.elim h3 i, show x ∈ A i ∩ B i, from and.intro h4 h5 example : C ∩ (⋃i, A i) ⊆ ⋃i, C ∩ A i := assume x, show x ∈ C ∩ (⋃i, A i) → x ∈ ⋃i, C ∩ A i, from assume h1 : x ∈ C ∩ (⋃i, A i), have h2 : x ∈ ⋃i, A i, from h1.right, have h5 : x ∈ C, from h1.left, show x ∈ ⋃i, C ∩ A i, from Union.elim h2 $ assume i, show x ∈ A i → x ∈ ⋃j, C ∩ A j, from assume h3 : x ∈ A i, have h4 : x ∈ C ∩ A i, from and.intro h5 h3, show x ∈ ⋃j, C ∩ A j, from Union.intro i h4 end -- ex 4 section variable {U : Type} variables A B C : set U universes u v w x theorem subset.refl (A : set U) : A ⊆ A := assume x, show x ∈ A → x ∈ A, from assume h : x ∈ A, show x ∈ A, from h theorem subset.trans {A B C : set U} (h1 : A ⊆ B) (h2 : B ⊆ C) : A ⊆ C := assume x, show x ∈ A → x ∈ C, from assume h3 : x ∈ A, have h4 : x ∈ B, from h1 h3, show x ∈ C, from h2 h4 -- For this exercise these two facts are useful example (h1 : A ⊆ B) (h2 : B ⊆ C) : A ⊆ C := subset.trans h1 h2 example : A ⊆ A := subset.refl A example (h : A ⊆ B) : powerset A ⊆ powerset B := assume X : set U, show X ∈ powerset A → X ∈ powerset B, from assume h1 : X ∈ powerset A, have h2 : X ⊆ A, from h1, have h3 : X ⊆ B, from subset.trans h2 h, show X ∈ powerset B, from h3 example (h : powerset A ⊆ powerset B) : A ⊆ B := assume x, show x ∈ A → x ∈ B, from assume h1 : x ∈ A, have h2 : ∀ X, X ⊆ A → X ⊆ B, from h, have h3 : A ⊆ A, from subset.refl A, have h4 : A ⊆ B, from h2 A h3, show x ∈ B, from h4 h1 end
b68ff8c0207751f5a786275633bb3d650491eb8b
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/ring_theory/adjoin_root.lean
2948c8c5be7285ca1628e4cae56a775114bb9842
[ "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
9,700
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `R` by the principal ideal of `f`. -/ def adjoin_root [comm_ring R] (f : polynomial R) : Type u := ideal.quotient (span {f} : ideal (polynomial R)) namespace adjoin_root section comm_ring variables [comm_ring R] (f : polynomial R) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : polynomial R, C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp (ring_hom.of C) instance : algebra R (adjoin_root f) := (of f).to_algebra @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_self : mk f f = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : polynomial R) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range R (root f)).symm ▸ ⟨p, aeval_eq p⟩ @[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : polynomial R) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end /-- If `E` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `E` is in bijection with the set of roots of `f` in `E`. -/ def equiv (F E : Type*) [field F] [field E] [algebra F E] (f : polynomial F) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots} := { to_fun := λ ϕ, ⟨ϕ (root f), begin rw [mem_roots (map_ne_zero hf), is_root.def, ←eval₂_eq_eval_map], exact aeval_alg_hom_eq_zero f ϕ, exact field.to_nontrivial E, end⟩, inv_fun := λ x, lift_hom f ↑x (begin rw [aeval_def, eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf)], exact subtype.mem x, exact field.to_nontrivial E end), left_inv := λ ϕ, lift_hom_eq_alg_hom f ϕ, right_inv := λ x, begin ext, refine @lift_root F E _ f _ _ ↑x _, rw [eval₂_eq_eval_map, ←is_root.def, ←mem_roots (map_ne_zero hf), ←multiset.mem_to_finset], exact multiset.mem_to_finset.mpr (subtype.mem x), exact field.to_nontrivial E end } end comm_ring section irreducible variables [field K] {f : polynomial K} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) := principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial K)) } lemma coe_injective : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel : ((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section power_basis variables [field K] {f : polynomial K} lemma power_basis_is_basis (hf : f ≠ 0) : is_basis K (λ (i : fin f.nat_degree), (root f ^ i.val)) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have f'_monic : monic f' := monic_mul_leading_coeff_inv hf, have aeval_f' : aeval (root f) f' = 0, { rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩, have minpoly_eq : f' = minpoly K (root f), { apply minpoly.unique K _ f'_monic aeval_f', intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, deg_f'], apply nat_degree_le_of_dvd, { rw [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem], change mk f q = 0, rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero] }, { exact q_monic.ne_zero } }, refine ⟨_, eq_top_iff.mpr _⟩, { rw [←deg_f', minpoly_eq], exact hx.linear_independent_pow }, { rintros y -, rw [←deg_f', minpoly_eq], apply hx.mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ noncomputable def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, is_basis := power_basis_is_basis hf } end power_basis end adjoin_root
dfc389cc914cb745f02f8a08ad1513bb586a03bf
fe84e287c662151bb313504482b218a503b972f3
/src/group_theory/cyclic.lean
3403f6d00b849b5535cbe6142007aa59a31d245c
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
4,335
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland We define finite cyclic groups, in multiplicative notation. The elements of `Cₙ` are denoted by `r i` for `i : zmod n`. We prove that an element `g ∈ G` with `gⁿ = 1` gives rise to a homomorphism `Cₙ → G`. We also do the case n = ∞ separately. -/ import data.fintype.basic algebra.power_mod namespace group_theory variables (n : ℕ) [fact (n > 0)] @[derive decidable_eq] inductive cyclic | r : (zmod n) → cyclic namespace cyclic variable {n} def log : cyclic n → zmod n := λ ⟨i⟩, i def log_equiv : (cyclic n) ≃ (zmod n) := { to_fun := log, inv_fun := r, left_inv := λ ⟨i⟩, rfl, right_inv := λ i, rfl } instance : fintype (cyclic n) := fintype.of_equiv (zmod n) log_equiv.symm lemma card : fintype.card (cyclic n) = n := by { rw [fintype.card_congr log_equiv], exact zmod.card n } def one : cyclic n := r 0 def inv : ∀ (g : cyclic n) , cyclic n | (r i) := r (-i) def mul : ∀ (g h : cyclic n), cyclic n | (r i) (r j) := r (i + j) instance : has_one (cyclic n) := ⟨r 0⟩ lemma one_eq : (1 : cyclic n) = r 0 := rfl instance : has_inv (cyclic n) := ⟨cyclic.inv⟩ lemma r_inv (i : zmod n) : (r i)⁻¹ = r (- i) := rfl instance : has_mul (cyclic n) := ⟨cyclic.mul⟩ lemma rr_mul (i j : zmod n) : (r i) * (r j) = r (i + j) := rfl instance : group (cyclic n) := { one := 1, mul := (*), inv := has_inv.inv, one_mul := λ ⟨i⟩, by rw [one_eq, rr_mul, zero_add], mul_one := λ ⟨i⟩, by rw [one_eq, rr_mul, add_zero], mul_left_inv := λ ⟨i⟩, by rw [r_inv, rr_mul, neg_add_self, one_eq], mul_assoc := λ ⟨i⟩ ⟨j⟩ ⟨k⟩, by simp only [rr_mul, add_assoc] } section hom_from_gens variables {M : Type*} [monoid M] {g : M} (hg : g ^ (n : ℕ) = 1) include g hg def hom_from_gens₀ : (cyclic n) → M | (r i) := g ^ i def hom_from_gens : (cyclic n) →* M := { to_fun := hom_from_gens₀ hg, map_one' := begin change hom_from_gens₀ hg (r 0) = 1, rw[hom_from_gens₀,pow_mod_zero] end, map_mul' := λ ⟨i⟩ ⟨j⟩, pow_mod_add hg i j, } lemma hom_from_gens_r (i : zmod n) : hom_from_gens hg (r i) = g ^ i := rfl end hom_from_gens end cyclic @[derive decidable_eq] inductive infinite_cyclic | r : ℤ → infinite_cyclic namespace infinite_cyclic def log : infinite_cyclic → ℤ := λ ⟨i⟩, i def log_equiv : infinite_cyclic ≃ ℤ := { to_fun := log, inv_fun := r, left_inv := λ ⟨i⟩, rfl, right_inv := λ i, rfl } def one : infinite_cyclic := r 0 def inv : ∀ (g : infinite_cyclic) , infinite_cyclic | (r i) := r (-i) def mul : ∀ (g h : infinite_cyclic), infinite_cyclic | (r i) (r j) := r (i + j) instance : has_one (infinite_cyclic) := ⟨r 0⟩ lemma one_eq : (1 : infinite_cyclic) = r 0 := rfl instance : has_inv (infinite_cyclic) := ⟨infinite_cyclic.inv⟩ lemma r_inv (i : ℤ) : (r i)⁻¹ = r (- i) := rfl instance : has_mul (infinite_cyclic) := ⟨infinite_cyclic.mul⟩ lemma rr_mul (i j : ℤ) : (r i) * (r j) = r (i + j) := rfl instance : group (infinite_cyclic) := { one := 1, mul := (*), inv := has_inv.inv, one_mul := λ ⟨i⟩, by rw [one_eq, rr_mul, zero_add], mul_one := λ ⟨i⟩, by rw [one_eq, rr_mul, add_zero], mul_left_inv := λ ⟨i⟩, by rw [r_inv, rr_mul, neg_add_self, one_eq], mul_assoc := λ ⟨i⟩ ⟨j⟩ ⟨k⟩, by simp only [rr_mul, add_assoc] } def hom_from_gens₀ {G : Type*} [group G] (g : G) : infinite_cyclic → G | (r i) := g ^ i def hom_from_gens {G : Type*} [group G] (g : G) : infinite_cyclic →* G := { to_fun := hom_from_gens₀ g, map_one' := by { rw[one_eq], exact zpow_zero g, }, map_mul' := λ ⟨i⟩ ⟨j⟩, by { rw[rr_mul], apply zpow_add g, } } def monoid_hom_from_gens₀ {M : Type*} [monoid M] (g : units M) : infinite_cyclic → M | (r i) := ((g ^ i) : units M) def monoid_hom_from_gens {M : Type*} [monoid M] (g : units M) : infinite_cyclic →* M := { to_fun := monoid_hom_from_gens₀ g, map_one' := by { rw[one_eq], refl, }, map_mul' := λ i j, by { rcases i, rcases j, change ((g ^ (i + j) : units M) : M) = (g ^ i : units M) * (g ^ j : units M) , rw [← units.coe_mul, zpow_add] } } end infinite_cyclic end group_theory
a78327935279b2a2e71cb21c0077ab96d6eaf0af
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/smt/ematch.lean
8639a64a6cf7b4ca4eb8f68c246a247f21d1d306
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,172
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.congruence_closure import init.meta.attribute init.meta.simp_tactic open tactic /- Heuristic instantiation lemma -/ meta constant hinst_lemma : Type meta constant hinst_lemmas : Type /- (mk_core m e as_simp), m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma meta constant hinst_lemma.pp : hinst_lemma → tactic format meta constant hinst_lemma.id : hinst_lemma → name meta instance : has_to_tactic_format hinst_lemma := ⟨hinst_lemma.pp⟩ meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma := hinst_lemma.mk_core reducible h ff meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma := hinst_lemma.mk_from_decl_core reducible h ff meta constant hinst_lemmas.mk : hinst_lemmas meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas := hinst_lemmas.add hinst_lemmas.mk meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format := let tac := s^.fold (return format.nil) (λ h tac, do hpp ← h^.pp, r ← tac, if r^.is_nil then return hpp else return (r ++ to_fmt "," ++ format.line ++ hpp)) in do r ← tac, return $ format.cbrace (format.group r) meta instance : has_to_tactic_format hinst_lemmas := ⟨hinst_lemmas.pp⟩ open tactic meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas | as_simp [] hs := return hs | as_simp (n::ns) hs := let add_core n := do h ← hinst_lemma.mk_from_decl_core m n as_simp, new_hs ← return $ hs^.add h, to_hinst_lemmas_core as_simp ns new_hs in do /- First check if n is the name of a function with equational lemmas associated with it -/ eqns ← tactic.get_eqn_lemmas_for tt n, match eqns with | [] := do /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/ add_core n | _ := do p ← is_prop_decl n, if p then add_core n /- n is a proposition -/ else do /- Add equational lemmas to resulting hinst_lemmas -/ new_hs ← to_hinst_lemmas_core tt eqns hs, to_hinst_lemmas_core as_simp ns new_hs end meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command := do t ← to_expr `(caching_user_attribute hinst_lemmas), a ← attr_name^.to_expr, b ← if as_simp then to_expr `(tt) else to_expr `(ff), v ← to_expr `({ name := %%a, descr := "hinst_lemma attribute", mk_cache := λ ns, to_hinst_lemmas_core reducible %%b ns hinst_lemmas.mk, dependencies := [`reducibility] } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command | [] := skip | (n::ns) := (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns) <|> (do type ← infer_type (expr.const n []), expected ← to_expr `(caching_user_attribute hinst_lemmas), (is_def_eq type expected <|> fail ("failed to create hinst_lemma attribute '" ++ n^.to_string ++ "', declaration already exists and has different type.")), mk_hinst_lemma_attrs_core ns) meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas | [] hs := return hs | (attr::attrs) hs := do ns ← attribute.get_instances attr, new_hs ← to_hinst_lemmas_core m as_simp ns hs, merge_hinst_lemma_attrs attrs new_hs /-- Create a new "cached" attribute (attr_name : caching_user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command := do mk_hinst_lemma_attrs_core ff attr_names, mk_hinst_lemma_attrs_core tt simp_attr_names, t ← to_expr `(caching_user_attribute hinst_lemmas), a ← attr_name^.to_expr, l1 : expr ← list_name.to_expr attr_names, l2 : expr ← list_name.to_expr simp_attr_names, v ← to_expr `({ name := %%a, descr := "hinst_lemma attribute set", mk_cache := λ ns, let aux1 : list name := %%l1, aux2 : list name := %%l2 in do { hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk, hs₂ ← merge_hinst_lemma_attrs reducible ff aux1 hs₁, merge_hinst_lemma_attrs reducible tt aux2 hs₂}, dependencies := [`reducibility] ++ %%l1 ++ %%l2 } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute hinst_lemmas) cnst, caching_user_attribute.get_cache attr structure ematch_config := (max_instances : nat := 10000) (max_generation : nat := 10) /- Ematching -/ meta constant ematch_state : Type meta constant ematch_state.mk : ematch_config → ematch_state meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state namespace tactic meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_core reducible meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_all_core reducible end tactic
f5e244d059fbde390398f761ec9d25d3ea5475b4
75c54c8946bb4203e0aaf196f918424a17b0de99
/old/peano.lean
888d1361ab68b8ce6986b081b058c041ed120df4
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
10,619
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .realization -- local attribute [instance, priority 0] classical.prop_decidable --local attribute [instance] classical.prop_decidable local notation h :: t := dvector.cons h t local notation `[]` := dvector.nil local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l namespace peano open fol section PA /- The language of PA -/ inductive peano_functions : ℕ → Type -- thanks Floris! | zero : peano_functions 0 | succ : peano_functions 1 | plus : peano_functions 2 | mult : peano_functions 2 def L_peano : Language := ⟨peano_functions, λ n, empty⟩ def L_peano_plus {n} (t₁ t₂ : bounded_term L_peano n) : bounded_term L_peano n := @bounded_term_of_function L_peano 2 n peano_functions.plus t₁ t₂ def L_peano_mult {n} (t₁ t₂ : bounded_term L_peano n) : bounded_term L_peano n := @bounded_term_of_function L_peano 2 n peano_functions.mult t₁ t₂ local infix ` +' `:100 := L_peano_plus local infix ` ×' `:150 := L_peano_mult def succ {n} : bounded_term L_peano n → bounded_term L_peano n := @bounded_term_of_function L_peano 1 n peano_functions.succ def zero {n} : bounded_term L_peano n := bd_const peano_functions.zero def one {n} : bounded_term L_peano n := succ zero /- For each k : ℕ, return the bounded_term of L_peano corresponding to k-/ @[reducible]def formal_nat {n}: Π k : ℕ, bounded_term L_peano n | 0 := zero | (k+1) := succ $ formal_nat k /- for all x, zero not equal to succ x -/ def p_zero_not_succ : sentence L_peano := ∀'(zero ≃ succ &0 ⟹ ⊥) @[reducible]def shallow_zero_not_succ : Prop := ∀ n : ℕ, 0 = nat.succ n → false def p_succ_inj : sentence L_peano := ∀' ∀'(succ &1 ≃ succ &0 ⟹ &1 ≃ &0) @[reducible]def shallow_succ_inj : Prop := ∀ x, ∀ y, nat.succ x = nat.succ y → x = y def p_zero_is_identity : sentence L_peano := ∀'(&0 +' zero ≃ &0) @[reducible]def shallow_zero_is_identity : Prop := ∀ x : ℕ, x + 0 = x /- ∀ x ∀ y, x + succ y = succ( x + y) -/ def p_succ_plus : sentence L_peano := ∀' ∀'(&1 +' succ &0 ≃ succ (&1 +' &0)) @[reducible]def shallow_succ_plus : Prop := ∀ x, ∀ y, x + nat.succ y = nat.succ(x + y) /- ∀ x, x ⬝ 0 = 0 -/ def p_zero_of_times_zero : sentence L_peano := ∀'(&0 ×' zero ≃ zero) @[reducible]def shallow_zero_of_times_zero : Prop := ∀ x : ℕ, x * 0 = 0 /- ∀ x y, (x ⬝ succ y = (x ⬝ y) + x -/ def p_times_succ : sentence L_peano := ∀' ∀' (&1 ×' succ &0 ≃ &1 ×' &0 +' &1) @[reducible]def shallow_times_succ : Prop := ∀ x : ℕ, ∀ y : ℕ, x * (y + 1) = (x * y) + x /- The induction schema instance at ψ is the following formula (up to the fixed ordering of variables given by the de Bruijn indexing): letting k+1 be the number of free vars of ψ: (k ∀'s)[(ψ(...,0) ∧ ∀' (ψ → ψ(...,S(x)))) → ∀' ψ] -/ def p_induction_schema {n : ℕ} (ψ : bounded_formula L_peano (n+1)) : sentence L_peano := bd_alls n (ψ[zero/0] ⊓ ∀' (ψ ⟹ (ψ ↑' 1 # 1)[succ &0/0]) ⟹ ∀' ψ) @[reducible]def shallow_induction_schema : Π P : set ℕ, Prop := λ P, (P(0) ∧ ∀ x, P x → P (nat.succ x)) → ∀ x, P x /- The theory of Peano arithmetic -/ def PA : Theory L_peano := {p_zero_not_succ, p_succ_inj, p_zero_is_identity, p_succ_plus, p_zero_of_times_zero, p_times_succ} ∪ ⋃ (n : ℕ), (λ(ψ : bounded_formula L_peano (n+1)), p_induction_schema ψ) '' set.univ @[reducible]def shallow_PA : set Prop := {shallow_zero_not_succ, shallow_succ_inj, shallow_zero_is_identity, shallow_succ_plus, shallow_zero_of_times_zero, shallow_times_succ} ∪ (shallow_induction_schema '' (set.univ)) def is_even : bounded_formula L_peano 1 := ∃' (&0 +' &0 ≃ &1) def L_peano_structure_of_nat : Structure L_peano := begin refine ⟨ℕ, _, _⟩, {intros n F, induction F, exact λv, 0, {intro v, cases v, exact nat.succ v_x}, {intro v, cases v, exact v_x + (v_xs.nth 0 $ by constructor)}, {intro v, cases v, exact v_x * (v_xs.nth 0 $ by constructor)},}, {intro v, intro R, cases R}, end local notation `ℕ'` := L_peano_structure_of_nat @[simp]lemma floris {L} {S : Structure L} : ↥S = S.carrier := by refl example : ℕ' ⊨ p_zero_not_succ := begin change ∀ x : ℕ', 0 = nat.succ x → false, intros x h, cases h end @[simp]lemma zero_is_zero : @realize_bounded_term L_peano ℕ' 0 [] 0 zero [] = nat.zero := by refl @[simp]lemma one_is_one : @realize_bounded_term L_peano ℕ' 0 [] 0 one [] = (nat.succ nat.zero) := by refl instance has_zero_sort_L_peano_structure_of_nat : has_zero ℕ' := ⟨nat.zero⟩ instance has_zero_L_peano_structure_of_nat : has_zero L_peano_structure_of_nat := ⟨nat.zero⟩ @[simp]lemma formal_nat_realize_term {n} : realize_closed_term ℕ' (formal_nat n) = n := by {induction n, refl, tidy} @[simp] lemma succ_realize_term {n} : realize_closed_term ℕ' (succ $ formal_nat n) = nat.succ n := begin dsimp[realize_closed_term, realize_bounded_term, succ, bounded_term_of_function], induction n, tidy end @[simp]lemma formal_nat_realize_formula {ψ : bounded_formula L_peano 1} (n) : realize_bounded_formula ([(n : ℕ')]) ψ [] ↔ ℕ' ⊨ ψ[(formal_nat n)/0] := begin induction n, all_goals{dsimp[formal_nat], simp[realize_subst_formula0]}, have := @formal_nat_realize_term 0, unfold formal_nat at this, rw[this] end @[simp]lemma nat_bd_all {ψ : bounded_formula L_peano 1} : ℕ' ⊨ ∀'ψ ↔ ∀(n : ℕ'), ℕ' ⊨ ψ[(formal_nat n)/0] := begin refine ⟨by {intros H n, induction n, all_goals{dsimp[formal_nat], rw[realize_subst_formula0], tidy}}, _⟩, intros H n, have := H n, induction n, all_goals{simp only [formal_nat_realize_formula], exact this} end lemma shallow_induction (P : set nat) : (P(0) ∧ ∀ x, P x → P (nat.succ x)) → ∀ x, P x := λ h, nat.rec h.1 h.2 section notation_test -- #reduce (ℕ')[(@zero 0) /// [] ] -- #reduce (L_peano_structure_of_nat)[(p_zero_not_succ)] -- #reduce (L_peano_structure_of_nat)[(&0 ≃ zero : bounded_formula L_peano 1) ;; ([(1 : ℕ)] : dvector (ℕ') 1)] -- #reduce (&0 : bounded_term L_peano 1)[zero // 0] -- elaborator fails, don't know why -- need to fix subst_bounded_term notation, something's not type-checking end notation_test -- @[simp]lemma subst0_subst0 {L} {n} {f : bounded_formula L (n+1)} {s₁} {s₂} : (f ↑' 1 # 1)[s₁ /0][s₂ /0] = f[s₁[s₂ /0] /0] := sorry -- this probably isn't true with careful lifting -- @[simp]lemma subst_succ_is_apply {n} {k} : (succ &0)[formal_nat n /0] = @formal_nat k (nat.succ n) := -- begin -- induction n, refl, symmetry, dsimp[formal_nat] at *, rw[<-n_ih], -- unfold succ bounded_term_of_function formal_nat, tidy, induction n_n, tidy -- end -- @[simp]lemma subst_term'_cancel {n} {k} : Π ψ : bounded_formula L_peano (k + 1), (ψ ↑' 1 # 1)[succ &0 /0][formal_nat n /0] = ψ[formal_nat (nat.succ n) /0] := by simp -- begin -- -- intros n ψ, unfold subst0_bounded_formula, tidy, -- simp[lift_subst_formula_cancel ψ.fst 0], -- -- sorry -- looks like here we need a lemma that generalizes lift_subst_formula_cancel to substitutions of terms, or something -- end ---- oops, i think this is already somewhere in fol.lean -- /-- Canonical extension of a dvector to a valuation --/ -- def val_of_dvector {α : Type*} [has_zero α] {n} (xs : dvector α n): ℕ' → α := -- begin -- intro k, -- by_cases nat.lt k n, -- exact xs.nth k h, -- exact 0 -- end /-- Given a term t with ≤ n free variables, the realization of t only depends on the nth initial segment of the realizing dvector v. --/ -- lemma realize_closed_term_realize_irrel {L} {S : Structure L} {n n' : nat} {h : n' ≤ n} {t : bounded_term L n'} {v : dvector S n} : realize_bounded_term (dvector.trunc h v) t [] = realize_bounded_term v (t.cast h) [] := -- begin -- revert t, apply bounded_term.rec, {intro k, induction k, induction v, have : n' = 0, by {apply nat.eq_zero_of_le_zero, exact h}, subst this, {tidy}, sorry}, -- tidy, sorry -- end -- lemma realize_closed_term_realizer_irrel {L} {S : Structure L} {n} {n'} {h : n' ≤ n} {t : bounded_term L n'} {v : dvector S n} : realize_bounded_term (@dvector.trunc n' n h xs) (t.cast (by simp)) [] = realize_bounded_term [] t [] := -- begin -- induction n, -- {cases v, revert t, }, -- {sorry}, -- end -- lemma realize_bounded_formula_subst0_gen {L} {S : Structure L} {n l} (f : bounded_preformula L (n+1) l) {v : dvector S n} {xs : dvector S l} (t : bounded_term L n) : realize_bounded_formula v (f[(t.cast (by refl)) /0]) xs ↔ realize_bounded_formula ((realize_bounded_term v t [])::v) f xs := -- begin -- sorry -- end -- realization of a substitution of a bounded_term (n' + 1) at n in a bounded_formula (n'' + 1), where n + n' = n'', is the same as realization (insert S[t]) -- lemma asjh {L} {S : Structure L} {n n' n''} {h : n + (n') + 1 = n'' + 1} {t : bounded_term L (n')} {f : bounded_formula L (n''+1)} {v : dvector S (n + n' + 1)} : -- @realize_bounded_formula L S n 0 v (@subst_bounded_formula L n (n' + 1) (n'' + 1) 0 f t (by assumption) = @realize_bounded_formula L S (n+1) 0 (dvector.insert (realize_bounded_term begin end t)) sorry) sorry := sorry /- ℕ' satisfies PA induction schema -/ theorem PA_standard_model_induction {index : nat} {ψ : bounded_formula L_peano (index + 1)} : ℕ' ⊨ bd_alls index (ψ[zero /0] ⊓ ∀'(ψ ⟹ (ψ ↑' 1 # 1)[succ &0 /0]) ⟹ ∀' ψ) := begin rw[realize_sentence_bd_alls], intro xs, simp, intros H_zero H_ih, apply nat.rec, {apply (realize_bounded_formula_subst0 ψ zero).mp, apply H_zero}, {intros n H, apply (@realize_bounded_formula_subst0' _ _ _ ψ xs (succ &0) n).mp, exact H_ih n H} end def true_arithmetic := Th ℕ' lemma true_arithmetic_extends_PA : PA ⊆ true_arithmetic := begin intros f hf, cases hf with not_induct induct, swap, {rcases induct with ⟨induction_schemas, ⟨⟨index, h_eq⟩, ih_right⟩⟩, rw [←h_eq] at ih_right, simp[set.range, set.image] at ih_right, rcases ih_right with ⟨ψ, h_ψ⟩, subst h_ψ, apply PA_standard_model_induction}, {repeat{cases not_induct}, tidy, contradiction} end lemma shallow_standard_model : ∀ ψ ∈ shallow_PA, ψ := begin intros x H, cases H, {repeat{cases H}, tidy, contradiction}, {simp[shallow_induction_schema] at H, rcases H with ⟨y, Hy⟩, subst Hy, exact nat.rec} end def PA_standard_model : Model PA := ⟨ℕ', true_arithmetic_extends_PA⟩ end PA end peano
3185b6fde7f1f6ee4e486537e4218f2a96515fec
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/period_after_eqns.lean
921bb5753fcee7d7fc66037ab0efc08d10b78fac
[ "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
54
lean
def f : nat → nat | 0 := 1 | (a+1) := 1 . check 10
ced3bba2de990a63e692e372bc787ea989010f9d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/category/Kleisli.lean
2c5d47ad9e81c187ac5e1caab5412e03fef97000
[ "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,737
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import category_theory.category.basic /-! # The Kleisli construction on the Type category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Define the Kleisli category for (control) monads. `category_theory/monad/kleisli` defines the general version for a monad on `C`, and demonstrates the equivalence between the two. ## TODO Generalise this to work with category_theory.monad -/ universes u v namespace category_theory /-- The Kleisli category on the (type-)monad `m`. Note that the monad is not assumed to be lawful yet. -/ @[nolint unused_arguments] def Kleisli (m : Type u → Type v) := Type u /-- Construct an object of the Kleisli category from a type. -/ def Kleisli.mk (m) (α : Type u) : Kleisli m := α instance Kleisli.category_struct {m} [monad.{u v} m] : category_struct (Kleisli m) := { hom := λ α β, α → m β, id := λ α x, pure x, comp := λ X Y Z f g, f >=> g } instance Kleisli.category {m} [monad.{u v} m] [is_lawful_monad m] : category (Kleisli m) := by refine { id_comp' := _, comp_id' := _, assoc' := _ }; intros; ext; unfold_projs; simp only [(>=>)] with functor_norm @[simp] lemma Kleisli.id_def {m} [monad m] (α : Kleisli m) : 𝟙 α = @pure m _ α := rfl lemma Kleisli.comp_def {m} [monad m] (α β γ : Kleisli m) (xs : α ⟶ β) (ys : β ⟶ γ) (a : α) : (xs ≫ ys) a = xs a >>= ys := rfl instance : inhabited (Kleisli id) := ⟨punit⟩ instance {α : Type u} [inhabited α] : inhabited (Kleisli.mk id α) := ⟨show α, from default⟩ end category_theory
53d1c0f0bc41dba3eab0d3bcf609f3efe6629b3a
649957717d58c43b5d8d200da34bf374293fe739
/src/algebra/group/with_one.lean
59c550cdf356d4a5aa786e1af95078b7b795640b
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
7,196
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin Various multiplicative and additive structures. -/ import algebra.group.to_additive algebra.group.basic universe u variable {α : Type u} @[to_additive with_zero] def with_one (α) := option α @[to_additive with_zero.monad] instance : monad with_one := option.monad @[to_additive with_zero.has_zero] instance : has_one (with_one α) := ⟨none⟩ @[to_additive with_zero.has_coe_t] instance : has_coe_t α (with_one α) := ⟨some⟩ @[simp, to_additive with_zero.zero_ne_coe] lemma with_one.one_ne_coe {a : α} : (1 : with_one α) ≠ a := λ h, option.no_confusion h @[simp, to_additive with_zero.coe_ne_zero] lemma with_one.coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := λ h, option.no_confusion h @[to_additive with_zero.ne_zero_iff_exists] lemma with_one.ne_one_iff_exists : ∀ {x : with_one α}, x ≠ 1 ↔ ∃ (a : α), x = a | 1 := ⟨λ h, false.elim $ h rfl, by { rintros ⟨a,ha⟩ h, simpa using h }⟩ | (a : α) := ⟨λ h, ⟨a, rfl⟩, λ h, with_one.coe_ne_one⟩ @[to_additive with_zero.coe_inj] lemma with_one.coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive with_zero.cases_on] protected lemma with_one.cases_on (P : with_one α → Prop) : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on attribute [to_additive with_zero.has_zero.equations._eqn_1] with_one.has_one.equations._eqn_1 @[to_additive with_zero.has_add] instance [has_mul α] : has_mul (with_one α) := { mul := option.lift_or_get (*) } @[simp, to_additive with_zero.add_coe] lemma with_one.mul_coe [has_mul α] (a b : α) : (a : with_one α) * b = (a * b : α) := rfl attribute [to_additive with_zero.has_add.equations._eqn_1] with_one.has_mul.equations._eqn_1 instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1, ..with_one.has_one, ..with_one.has_mul } attribute [to_additive with_zero.add_monoid._proof_1] with_one.monoid._proof_1 attribute [to_additive with_zero.add_monoid._proof_2] with_one.monoid._proof_2 attribute [to_additive with_zero.add_monoid._proof_3] with_one.monoid._proof_3 attribute [to_additive with_zero.add_monoid] with_one.monoid attribute [to_additive with_zero.add_monoid.equations._eqn_1] with_one.monoid.equations._eqn_1 instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } instance [add_comm_semigroup α] : add_comm_monoid (with_zero α) := { add_comm := (option.lift_or_get_comm _).1, ..with_zero.add_monoid } attribute [to_additive with_zero.add_comm_monoid] with_one.comm_monoid namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } instance [has_one α] : zero_ne_one_class (with_zero α) := { zero_ne_one := λ h, option.no_confusion h, ..with_zero.has_zero, ..with_zero.has_one } lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp] lemma mul_coe [has_mul α] (a b : α) : (a : with_zero α) * b = (a * b : α) := rfl instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.zero_ne_one_class, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } definition inv [has_inv α] (x : with_zero α) : with_zero α := do a ← x, return a⁻¹ instance [has_inv α] : has_inv (with_zero α) := ⟨with_zero.inv⟩ @[simp] lemma inv_coe [has_inv α] (a : α) : (a : with_zero α)⁻¹ = (a⁻¹ : α) := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl section group variables [group α] @[simp] lemma inv_one : (1 : with_zero α)⁻¹ = 1 := show ((1⁻¹ : α) : with_zero α) = 1, by simp [coe_one] definition with_zero.div (x y : with_zero α) : with_zero α := x * y⁻¹ instance : has_div (with_zero α) := ⟨with_zero.div⟩ @[simp] lemma zero_div (a : with_zero α) : 0 / a = 0 := rfl @[simp] lemma div_zero (a : with_zero α) : a / 0 = 0 := by change a * _ = _; simp lemma div_coe (a b : α) : (a : with_zero α) / b = (a * b⁻¹ : α) := rfl lemma one_div (x : with_zero α) : 1 / x = x⁻¹ := one_mul _ @[simp] lemma div_one : ∀ (x : with_zero α), x / 1 = x | 0 := rfl | (a : α) := show _ * _ = _, by simp @[simp] lemma mul_right_inv : ∀ (x : with_zero α) (h : x ≠ 0), x * x⁻¹ = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_left_inv : ∀ (x : with_zero α) (h : x ≠ 0), x⁻¹ * x = 1 | 0 h := false.elim $ h rfl | (a : α) h := by simp [coe_one] @[simp] lemma mul_inv_rev : ∀ (x y : with_zero α), (x * y)⁻¹ = y⁻¹ * x⁻¹ | 0 0 := rfl | 0 (b : α) := rfl | (a : α) 0 := rfl | (a : α) (b : α) := by simp @[simp] lemma mul_div_cancel {a b : with_zero α} (hb : b ≠ 0) : a * b / b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] @[simp] lemma div_mul_cancel {a b : with_zero α} (hb : b ≠ 0) : a / b * b = a := show _ * _ * _ = _, by simp [mul_assoc, hb] lemma div_eq_iff_mul_eq {a b c : with_zero α} (hb : b ≠ 0) : a / b = c ↔ c * b = a := by split; intro h; simp [h.symm, hb] end group section comm_group variables [comm_group α] {a b c d : with_zero α} lemma div_eq_div (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = b * c := begin rw ne_zero_iff_exists at hb hd, rcases hb with ⟨b, rfl⟩, rcases hd with ⟨d, rfl⟩, induction a using with_zero.cases_on; induction c using with_zero.cases_on, { refl }, { simp [div_coe] }, { simp [div_coe] }, erw [with_zero.coe_inj, with_zero.coe_inj], show a * b⁻¹ = c * d⁻¹ ↔ a * d = b * c, split; intro H, { rw mul_inv_eq_iff_eq_mul at H, rw [H, mul_right_comm, inv_mul_cancel_right, mul_comm] }, { rw [mul_inv_eq_iff_eq_mul, mul_right_comm, mul_comm c, ← H, mul_inv_cancel_right] } end end comm_group end with_zero
68fdb024e801b375ff77c0b96ed38e505857ea39
137c667471a40116a7afd7261f030b30180468c2
/src/data/set/finite.lean
32634cbe6066c3473b7ef159ecf227eeecba7a0f
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,588
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.finset.sort /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ h.fintype @[simp] theorem finite.mem_to_finset {s : set α} (h : finite s) {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) : h.to_finset.nonempty ↔ s.nonempty := show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s), from exists_congr (λ _, h.mem_to_finset) @[simp] lemma finite.coe_to_finset {s : set α} (h : finite s) : ↑h.to_finset = s := @set.coe_to_finset _ s h.fintype @[simp] lemma finite.coe_sort_to_finset {s : set α} (h : finite s) : (h.to_finset : Type*) = s := by rw [← finset.coe_sort_coe _, h.coe_to_finset] @[simp] lemma finite_empty_to_finset (h : finite (∅ : set α)) : h.to_finset = ∅ := by rw [← finset.coe_inj, h.coe_to_finset, finset.coe_empty] @[simp] lemma finite.to_finset_inj {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset = ht.to_finset ↔ s = t := by simp [←finset.coe_inj] @[simp] lemma finite_to_finset_eq_empty_iff {s : set α} {h : finite s} : h.to_finset = ∅ ↔ s = ∅ := by simp [←finset.coe_inj] theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩ lemma finite.fin_embedding {s : set α} (h : finite s) : ∃ (n : ℕ) (f : fin n ↪ α), range f = s := ⟨_, (fintype.equiv_fin (h.to_finset : set α)).symm.as_embedding, by simp⟩ lemma finite.fin_param {s : set α} (h : finite s) : ∃ (n : ℕ) (f : fin n → α), injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding in ⟨n, f, f.injective, hf⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩ /-- A `fintype` structure on `insert a s`. -/ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (hs.insert a).to_finset = insert a hs.to_finset := finset.ext $ by simp @[simp] lemma insert_to_finset [decidable_eq α] {a : α} {s : set α} [fintype s] : (insert a s).to_finset = insert a s.to_finset := by simp [finset.ext_iff, mem_insert_iff] @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := unique.fintype @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ lemma subsingleton.finite {s : set α} (h : s.subsingleton) : finite s := h.induction_on finite_empty finite_singleton instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ /-- If `(set.univ : set α)` is finite then `α` is a finite type. -/ noncomputable def fintype_of_univ_finite (H : (univ : set α).finite ) : fintype α := @fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _) lemma univ_finite_iff_nonempty_fintype : (univ : set α).finite ↔ nonempty (fintype α) := begin split, { intro h, exact ⟨fintype_of_univ_finite h⟩ }, { rintro ⟨_i⟩, exactI finite_univ } end theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ h₂, h₁ (fintype_of_univ_finite h₂)⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s := ⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩ theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s := infinite_coe_iff.2 h /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty := let a := infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩ instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ lemma finite.sup {s t : set α} : finite s → finite t → finite (s ⊔ t) := finite.union lemma infinite_of_finite_compl {α : Type} [_root_.infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma finite.infinite_compl {α : Type} [_root_.infinite α] {s : set α} (hs : s.finite) : sᶜ.infinite := λ h, set.infinite_univ (by simpa using hs.union h) instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s ∩ t : set α) := set.fintype_sep s t /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred (∈ t)] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ lemma finite.union_iff {s t : set α} : finite (s ∪ t) ↔ finite s ∧ finite t := ⟨λ h, ⟨h.subset (subset_union_left _ _), h.subset (subset_union_right _ _)⟩, λ ⟨hs, ht⟩, hs.union ht⟩ lemma finite.diff {s t u : set α} (hs : s.finite) (ht : t.finite) (h : u \ t ≤ s) : u.finite := begin refine finite.subset (ht.union hs) _, exact diff_subset_iff.mp h end theorem finite.inter_of_left {s : set α} (h : finite s) (t : set α) : finite (s ∩ t) := h.subset (inter_subset_left _ _) theorem finite.inter_of_right {s : set α} (h : finite s) (t : set α) : finite (t ∩ s) := h.subset (inter_subset_right _ _) theorem finite.inf_of_left {s : set α} (h : finite s) (t : set α) : finite (s ⊓ t) := h.inter_of_left t theorem finite.inf_of_right {s : set α} (h : finite s) (t : set α) : finite (t ⊓ s) := h.inter_of_right t theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t := mt (λ ht, ht.subset h) instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs lemma finite.dependent_image {s : set α} (hs : finite s) (F : Π i ∈ s, β) : finite {y : β | ∃ x (hx : x ∈ s), y = F x hx} := begin letI : fintype s := hs.fintype, convert finite_range (λ x : s, F x x.2), simp only [set_coe.exists, subtype.coe_mk, eq_comm], end theorem finite.of_preimage {f : α → β} {s : set β} (h : finite (f ⁻¹' s)) (hf : surjective f) : finite s := hf.image_preimage s ▸ h.image _ instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite.map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite.image /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image hi, finite.image _⟩ theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : infinite (f '' s) ↔ infinite s := not_congr $ finite_image_iff hi theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t := infinite_mono (maps_to'.mp hm) $ (infinite_image_iff hi).2 hs theorem infinite.exists_ne_map_eq_of_maps_to {s : set α} {t : set β} {f : α → β} (hs : infinite s) (hf : maps_to f s t) (ht : finite t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin unfreezingI { contrapose! ht }, exact infinite_of_inj_on_maps_to (λ x hx y hy, not_imp_not.1 (ht x hx y hy)) hf hs end theorem infinite.exists_lt_map_eq_of_maps_to [linear_order α] {s : set α} {t : set β} {f : α → β} (hs : infinite s) (hf : maps_to f s t) (ht : finite t) : ∃ (x ∈ s) (y ∈ s), x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_maps_to hf ht in hxy.lt_or_lt.elim (λ hxy, ⟨x, hx, y, hy, hxy, hf⟩) (λ hyx, ⟨y, hy, x, hx, hyx, hf.symm⟩) theorem infinite_range_of_injective [_root_.infinite α] {f : α → β} (hi : injective f) : infinite (range f) := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [_root_.infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : infinite s := by { rw ←range_subset_iff at hf, exact infinite_mono hf (infinite_range_of_injective hi) } theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (h.subset (image_preimage_subset f s)) theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := finite.preimage (λ _ _ _ _ h', f.injective h') h lemma finite_option {s : set (option α)} : finite s ↔ finite {x : α | some x ∈ s} := ⟨λ h, h.preimage_embedding embedding.some, λ h, ((h.image some).insert none).subset $ λ x, option.cases_on x (λ _, or.inl rfl) (λ x hx, or.inr $ mem_image_of_mem _ hx)⟩ instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bUnion (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} : finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _) theorem finite_Union_Prop {p : Prop} {f : p → set α} (hf : ∀ h, finite (f h)) : finite (⋃ h : p, f h) := by by_cases p; simp * instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ /-- `image2 f s t` is finitype if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (image2 f s t) := by { rw ← image_prod, exact (hs.prod ht).image _ } /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite.bind {α β} {s : set α} {f : α → set β} (h : finite s) (hf : ∀ a ∈ s, finite (f a)) : finite (s >>= f) := h.bUnion hf instance fintype_seq [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f.seq s) := by { rw seq_def, apply set.fintype_bUnion' } instance fintype_seq' {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := set.fintype_seq f s theorem finite.seq {f : set (α → β)} {s : set α} (hf : finite f) (hs : finite s) : finite (f.seq s) := by { rw seq_def, exact hf.bUnion (λ f _, hs.image _) } theorem finite.seq' {α β : Type u} {f : set (α → β)} {s : set α} (hf : finite f) (hs : finite s) : finite (f <*> s) := hf.seq hs /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)), have : finite s := (finite_mem_finset _).image _, apply this.subset, refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩, simpa [finset.subset_iff] end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_min_image f ⟨x, h1.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩ theorem exists_lower_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f a ≤ f b := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_min_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end theorem exists_upper_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f b ≤ f a := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_max_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end end set namespace finset variables [decidable_eq β] variables {s : finset α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bUnion {f : α → finset β} : ↑(s.bUnion f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) : (finite_to_set s).to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace set /-- Finite product of finite sets is finite -/ lemma finite.pi {δ : Type*} [fintype δ] {κ : δ → Type*} {t : Π d, set (κ d)} (ht : ∀ d, (t d).finite) : (pi univ t).finite := begin classical, convert (fintype.pi_finset (λ d, (ht d).to_finset)).finite_to_set, ext, simp, end lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨x, ⟨hx, hf _⟩⟩, end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [linear_order ι'] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := begin ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩, simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx, obtain ⟨j₀⟩ := show nonempty ι', by apply_instance, refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩, rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)], exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩ end instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) := fintype.of_finset (finset.range n) $ by simp /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := (finite_singleton c).subset range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := (finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $ λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma subset_iff_to_finset_subset (s t : set α) [fintype s] [fintype t] : s ⊆ t ↔ s.to_finset ⊆ t.to_finset := by simp @[simp, mono] lemma finite.to_finset_mono {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset ⊆ ht.to_finset ↔ s ⊆ t := begin split, { intros h x, rw [←finite.mem_to_finset hs, ←finite.mem_to_finset ht], exact λ hx, h hx }, { intros h x, rw [finite.mem_to_finset hs, finite.mem_to_finset ht], exact λ hx, h hx } end @[simp, mono] lemma finite.to_finset_strict_mono {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset ⊂ ht.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective f hf lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, exact absurd h empty_not_nonempty }, assume a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext, rw set.finite.mem_to_finset } section decidable_eq lemma to_finset_compl {α : Type*} [fintype α] [decidable_eq α] (s : set α) [fintype (sᶜ : set α)] [fintype s] : sᶜ.to_finset = (s.to_finset)ᶜ := by ext; simp lemma to_finset_inter {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∩ t : set α)] [fintype s] [fintype t] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp lemma to_finset_union {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∪ t : set α)] [fintype s] [fintype t] : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp lemma to_finset_ne_eq_erase {α : Type*} [decidable_eq α] [fintype α] (a : α) [fintype {x : α | x ≠ a}] : {x : α | x ≠ a}.to_finset = finset.univ.erase a := by ext; simp lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] : fintype.card {x : α | x ≠ a} = fintype.card α - 1 := begin haveI := classical.dec_eq α, rw [←to_finset_card, to_finset_ne_eq_erase, finset.card_erase_of_mem (finset.mem_univ _), finset.card_univ, nat.pred_eq_sub_one], end end decidable_eq section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : finite s) : bdd_below s := @finite.bdd_above (order_dual α) _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset namespace fintype variables [fintype α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] @[simp] lemma card_subtype_compl : fintype.card {x // ¬ p x} = fintype.card α - fintype.card {x // p x} := begin classical, rw [fintype.card_of_subtype (set.to_finset pᶜ), set.to_finset_compl p, finset.card_compl, fintype.card_of_subtype (set.to_finset p)]; intros; simp; refl end /-- If two subtypes of a fintype have equal cardinality, so do their complements. -/ lemma card_compl_eq_card_compl (h : fintype.card {x // p x} = fintype.card {x // q x}) : fintype.card {x // ¬ p x} = fintype.card {x // ¬ q x} := by simp only [card_subtype_compl, h] end fintype /-- If a set `s` does not contain any elements between any pair of elements `x, z ∈ s` with `x ≤ z` (i.e if given `x, y, z ∈ s` such that `x ≤ y ≤ z`, then `y` is either `x` or `z`), then `s` is finite. -/ lemma set.finite_of_forall_between_eq_endpoints {α : Type*} [linear_order α] (s : set α) (h : ∀ (x ∈ s) (y ∈ s) (z ∈ s), x ≤ y → y ≤ z → x = y ∨ y = z) : set.finite s := begin by_contra hinf, change s.infinite at hinf, rcases hinf.exists_subset_card_eq 3 with ⟨t, hts, ht⟩, let f := t.order_iso_of_fin ht, let x := f 0, let y := f 1, let z := f 2, have := h x (hts x.2) y (hts y.2) z (hts z.2) (f.monotone $ by dec_trivial) (f.monotone $ by dec_trivial), have key₁ : (0 : fin 3) ≠ 1 := by dec_trivial, have key₂ : (1 : fin 3) ≠ 2 := by dec_trivial, cases this, { dsimp only [x, y] at this, exact key₁ (f.injective $ subtype.coe_injective this) }, { dsimp only [y, z] at this, exact key₂ (f.injective $ subtype.coe_injective this) } end
ac1a57caf266855a8be9cf2334a1e86c67b5ee25
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/bintreeGoal.lean
bdb929ee960f02293a5c099d1a47da44282df418
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,816
lean
inductive Tree (β : Type v) where | leaf | node (left : Tree β) (key : Nat) (value : β) (right : Tree β) deriving Repr def Tree.find? (t : Tree β) (k : Nat) : Option β := match t with | leaf => none | node left key value right => if k < key then left.find? k else if key < k then right.find? k else some value def Tree.insert (t : Tree β) (k : Nat) (v : β) : Tree β := match t with | leaf => node leaf k v leaf | node left key value right => if k < key then node (left.insert k v) key value right else if key < k then node left key value (right.insert k v) else node left k v right inductive ForallTree (p : Nat → β → Prop) : Tree β → Prop | leaf : ForallTree p .leaf | node : ForallTree p left → p key value → ForallTree p right → ForallTree p (.node left key value right) inductive BST : Tree β → Prop | leaf : BST .leaf | node : {value : β} → ForallTree (fun k v => k < key) left → ForallTree (fun k v => key < k) right → BST left → BST right → BST (.node left key value right) def BinTree (β : Type u) := { t : Tree β // BST t } def BinTree.mk : BinTree β := ⟨.leaf, .leaf⟩ def BinTree.find? (b : BinTree β) (k : Nat) : Option β := b.val.find? k def BinTree.insert (b : BinTree β) (k : Nat) (v : β) : BinTree β := ⟨b.val.insert k v, sorry⟩ attribute [local simp] BinTree.mk BinTree.find? BinTree.insert Tree.find? Tree.insert theorem BinTree.find_insert (b : BinTree β) (k : Nat) (v : β) : (b.insert k v).find? k = some v := by let ⟨t, h⟩ := b; simp induction t with simp | node left key value right ihl ihr => by_cases k < key <;> simp [*] . cases h; apply ihl; done . sorry
b5dd4358e182bd1b4797b9ac4c8f28fd721f879f
69d4931b605e11ca61881fc4f66db50a0a875e39
/test/lift.lean
d0bd06dc17dafb180f46540bb6679f62d27391e4
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
643
lean
import tactic.lift import data.set.basic instance can_lift_subtype (R : Type*) (P : R → Prop) : can_lift R {x // P x} := { coe := coe, cond := λ x, P x, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } instance can_lift_set (R : Type*) (s : set R) : can_lift R s := { coe := coe, cond := λ x, x ∈ s, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } example {R : Type*} {P : R → Prop} (x : R) (hx : P x) : true := by { lift x to {x // P x} using hx with y, trivial } /-! Test that `lift` elaborates `s` as a type, not as a set. -/ example {R : Type*} {s : set R} (x : R) (hx : x ∈ s) : true := by { lift x to s using hx with y, trivial }
533cdcbd80aee3b62b02752d58e3d42a82161837
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/zfc.lean
148aa37b3bd752f6d64b919176eba242c072967e
[]
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
22,607
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A model of ZFC in Lean. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.basic import Mathlib.PostPort universes u u_1 l u_2 u_3 v namespace Mathlib /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : ℕ → Type u := sorry namespace arity /-- Constant `n`-ary function with value `a`. -/ def const {α : Type u} (a : α) (n : ℕ) : arity α n := sorry protected instance arity.inhabited {α : Type u_1} {n : ℕ} [Inhabited α] : Inhabited (arity α n) := { default := const Inhabited.default n } end arity /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet where | mk : (α : Type u) → (α → pSet) → pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u := sorry /-- The underlying pre-set family of a pre-set -/ def func (x : pSet) : type x → pSet := sorry theorem mk_type_func (x : pSet) : mk (type x) (func x) = x := pSet.cases_on x fun (x_α : Type u_1) (x_A : x_α → pSet) => idRhs (mk (type (mk x_α x_A)) (func (mk x_α x_A)) = mk (type (mk x_α x_A)) (func (mk x_α x_A))) rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x : pSet) (y : pSet) := pSet.rec (fun (α : Type u_1) (z : α → pSet) (m : α → pSet → Prop) (_x : pSet) => sorry) x y theorem equiv.refl (x : pSet) : equiv x x := pSet.rec_on x fun (α : Type u_1) (A : α → pSet) (IH : ∀ (ᾰ : α), equiv (A ᾰ) (A ᾰ)) => { left := fun (a : α) => Exists.intro a (IH a), right := fun (a : α) => Exists.intro a (IH a) } theorem equiv.euc {x : pSet} {y : pSet} {z : pSet} : equiv x y → equiv z y → equiv x z := sorry theorem equiv.symm {x : pSet} {y : pSet} : equiv x y → equiv y x := equiv.euc (equiv.refl y) theorem equiv.trans {x : pSet} {y : pSet} {z : pSet} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := equiv.euc h1 (equiv.symm h2) protected instance setoid : setoid pSet := setoid.mk equiv sorry protected def subset : pSet → pSet → Prop := sorry protected instance has_subset : has_subset pSet := has_subset.mk pSet.subset theorem equiv.ext (x : pSet) (y : pSet) : equiv x y ↔ x ⊆ y ∧ y ⊆ x := sorry theorem subset.congr_left {x : pSet} {y : pSet} {z : pSet} : equiv x y → (x ⊆ z ↔ y ⊆ z) := sorry theorem subset.congr_right {x : pSet} {y : pSet} {z : pSet} : equiv x y → (z ⊆ x ↔ z ⊆ y) := sorry /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ def mem : pSet → pSet → Prop := sorry protected instance has_mem : has_mem pSet pSet := has_mem.mk mem theorem mem.mk {α : Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := (fun (this : mem (A a) (mk α A)) => this) (Exists.intro a (equiv.refl (A a))) theorem mem.ext {x : pSet} {y : pSet} : (∀ (w : pSet), w ∈ x ↔ w ∈ y) → equiv x y := sorry theorem mem.congr_right {x : pSet} {y : pSet} : equiv x y → ∀ {w : pSet}, w ∈ x ↔ w ∈ y := sorry theorem equiv_iff_mem {x : pSet} {y : pSet} : equiv x y ↔ ∀ {w : pSet}, w ∈ x ↔ w ∈ y := sorry theorem mem.congr_left {x : pSet} {y : pSet} : equiv x y → ∀ {w : pSet}, x ∈ w ↔ y ∈ w := sorry /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet) : set pSet := set_of fun (x : pSet) => x ∈ u /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x : pSet} {y : pSet} : equiv x y ↔ to_set x = to_set y := iff.trans equiv_iff_mem (iff.symm set.ext_iff) protected instance set.has_coe : has_coe pSet (set pSet) := has_coe.mk to_set /-- The empty pre-set -/ protected def empty : pSet := mk (ulift empty) fun (e : ulift empty) => sorry protected instance has_emptyc : has_emptyc pSet := has_emptyc.mk pSet.empty protected instance inhabited : Inhabited pSet := { default := ∅ } theorem mem_empty (x : pSet) : ¬x ∈ ∅ := sorry /-- Insert an element into a pre-set -/ protected def insert : pSet → pSet → pSet := sorry protected instance has_insert : has_insert pSet pSet := has_insert.mk pSet.insert protected instance has_singleton : has_singleton pSet pSet := has_singleton.mk fun (s : pSet) => insert s ∅ protected instance is_lawful_singleton : is_lawful_singleton pSet pSet := is_lawful_singleton.mk fun (_x : pSet) => rfl /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet := sorry /-- The von Neumann ordinal ω -/ def omega : pSet := mk (ulift ℕ) fun (n : ulift ℕ) => of_nat (ulift.down n) /-- The separation operation `{x ∈ a | p x}` -/ protected def sep (p : set pSet) : pSet → pSet := sorry protected instance has_sep : has_sep pSet pSet := has_sep.mk pSet.sep /-- The powerset operator -/ def powerset : pSet → pSet := sorry theorem mem_powerset {x : pSet} {y : pSet} : y ∈ powerset x ↔ y ⊆ x := sorry /-- The set union operator -/ def Union : pSet → pSet := sorry theorem mem_Union {x : pSet} {y : pSet} : y ∈ Union x ↔ ∃ (z : pSet), ∃ (_x : z ∈ x), y ∈ z := sorry /-- The image of a function -/ def image (f : pSet → pSet) : pSet → pSet := sorry theorem mem_image {f : pSet → pSet} (H : ∀ {x y : pSet}, equiv x y → equiv (f x) (f y)) {x : pSet} {y : pSet} : y ∈ image f x ↔ ∃ (z : pSet), ∃ (H : z ∈ x), equiv y (f z) := sorry /-- Universe lift operation -/ protected def lift : pSet → pSet := sorry /-- Embedding of one universe in another -/ def embed : pSet := mk (ulift pSet) fun (_x : ulift pSet) => sorry theorem lift_mem_embed (x : pSet) : pSet.lift x ∈ embed := Exists.intro (ulift.up x) (equiv.refl (pSet.lift x)) /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of n-ary functions. -/ def arity.equiv {n : ℕ} : arity pSet n → arity pSet n → Prop := sorry theorem arity.equiv_const {a : pSet} (n : ℕ) : arity.equiv (arity.const a n) (arity.const a n) := sorry /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n : ℕ) := Subtype fun (x : arity pSet n) => arity.equiv x x protected instance resp.inhabited {n : ℕ} : Inhabited (resp n) := { default := { val := arity.const Inhabited.default n, property := sorry } } def resp.f {n : ℕ} (f : resp (n + 1)) (x : pSet) : resp n := { val := subtype.val f x, property := sorry } def resp.equiv {n : ℕ} (a : resp n) (b : resp n) := arity.equiv (subtype.val a) (subtype.val b) theorem resp.refl {n : ℕ} (a : resp n) : resp.equiv a a := subtype.property a theorem resp.euc {n : ℕ} {a : resp n} {b : resp n} {c : resp n} : resp.equiv a b → resp.equiv c b → resp.equiv a c := sorry protected instance resp.setoid {n : ℕ} : setoid (resp n) := setoid.mk resp.equiv sorry end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set := quotient pSet.setoid namespace pSet namespace resp def eval_aux {n : ℕ} : Subtype fun (f : resp n → arity Set n) => ∀ (a b : resp n), equiv a b → f a = f b := sorry /-- An equivalence-respecting function yields an n-ary Set function. -/ def eval (n : ℕ) : resp n → arity Set n := subtype.val eval_aux theorem eval_val {n : ℕ} {f : resp (n + 1)} {x : pSet} : eval (n + 1) f (quotient.mk x) = eval n (f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ class inductive definable (n : ℕ) : arity Set n → Type (u + 1) where | mk : (f : resp n) → definable n (resp.eval n f) def definable.eq_mk {n : ℕ} (f : resp n) {s : arity Set n} (H : resp.eval n f = s) : definable n s := sorry def definable.resp {n : ℕ} (s : arity Set n) [definable n s] : resp n := sorry theorem definable.eq {n : ℕ} (s : arity Set n) [H : definable n s] : resp.eval n (definable.resp s) = s := sorry end pSet namespace classical def all_definable {n : ℕ} (F : arity Set n) : pSet.definable n F := sorry end classical namespace Set def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : quotient.mk x = mk x := rfl @[simp] theorem eval_mk {n : ℕ} {f : pSet.resp (n + 1)} {x : pSet} : pSet.resp.eval (n + 1) f (mk x) = pSet.resp.eval n (pSet.resp.f f x) := rfl def mem : Set → Set → Prop := quotient.lift₂ pSet.mem sorry protected instance has_mem : has_mem Set Set := has_mem.mk mem /-- Convert a ZFC set into a `set` of sets -/ def to_set (u : Set) : set Set := set_of fun (x : Set) => x ∈ u protected def subset (x : Set) (y : Set) := ∀ {z : Set}, z ∈ x → z ∈ y protected instance has_subset : has_subset Set := has_subset.mk Set.subset theorem subset_def {x : Set} {y : Set} : x ⊆ y ↔ ∀ {z : Set}, z ∈ x → z ∈ y := iff.rfl theorem subset_iff (x : pSet) (y : pSet) : mk x ⊆ mk y ↔ x ⊆ y := sorry theorem ext {x : Set} {y : Set} : (∀ (z : Set), z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y fun (u v : pSet) (h : ∀ (z : Set), z ∈ quotient.mk u ↔ z ∈ quotient.mk v) => quotient.sound (pSet.mem.ext fun (w : pSet) => h (quotient.mk w)) theorem ext_iff {x : Set} {y : Set} : (∀ (z : Set), z ∈ x ↔ z ∈ y) ↔ x = y := sorry /-- The empty set -/ def empty : Set := mk ∅ protected instance has_emptyc : has_emptyc Set := has_emptyc.mk empty protected instance inhabited : Inhabited Set := { default := ∅ } @[simp] theorem mem_empty (x : Set) : ¬x ∈ ∅ := quotient.induction_on x pSet.mem_empty theorem eq_empty (x : Set) : x = ∅ ↔ ∀ (y : Set), ¬y ∈ x := sorry /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := pSet.resp.eval (bit0 1) { val := pSet.insert, property := sorry } protected instance has_insert : has_insert Set Set := has_insert.mk Set.insert protected instance has_singleton : has_singleton Set Set := has_singleton.mk fun (x : Set) => insert x ∅ protected instance is_lawful_singleton : is_lawful_singleton Set Set := is_lawful_singleton.mk fun (x : Set) => rfl @[simp] theorem mem_insert {x : Set} {y : Set} {z : Set} : x ∈ insert y z ↔ x = y ∨ x ∈ z := sorry @[simp] theorem mem_singleton {x : Set} {y : Set} : x ∈ singleton y ↔ x = y := iff.trans mem_insert { mp := fun (o : x = y ∨ x ∈ ∅) => Or._oldrec (fun (h : x = y) => h) (fun (n : x ∈ ∅) => absurd n (mem_empty x)) o, mpr := Or.inl } @[simp] theorem mem_pair {x : Set} {y : Set} {z : Set} : x ∈ insert y (singleton z) ↔ x = y ∨ x = z := iff.trans mem_insert (or_congr iff.rfl mem_singleton) /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk pSet.omega @[simp] theorem omega_zero : ∅ ∈ omega := (fun (this : pSet.mem ∅ pSet.omega) => this) (Exists.intro (ulift.up 0) (pSet.equiv.refl ∅)) @[simp] theorem omega_succ {n : Set} : n ∈ omega → insert n n ∈ omega := sorry /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := pSet.resp.eval 1 { val := pSet.sep fun (y : pSet) => p (quotient.mk y), property := sorry } protected instance has_sep : has_sep Set Set := has_sep.mk Set.sep @[simp] theorem mem_sep {p : Set → Prop} {x : Set} {y : Set} : y ∈ has_sep.sep (fun (y : Set) => p y) x ↔ y ∈ x ∧ p y := sorry /-- The powerset operation, the collection of subsets of a set -/ def powerset : Set → Set := pSet.resp.eval 1 { val := pSet.powerset, property := sorry } @[simp] theorem mem_powerset {x : Set} {y : Set} : y ∈ powerset x ↔ y ⊆ x := sorry theorem Union_lem {α : Type u} {β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀ (a : α), ∃ (b : β), pSet.equiv (A a) (B b)) (a : pSet.type (pSet.Union (pSet.mk α A))) : ∃ (b : pSet.type (pSet.Union (pSet.mk β B))), pSet.equiv (pSet.func (pSet.Union (pSet.mk α A)) a) (pSet.func (pSet.Union (pSet.mk β B)) b) := sorry /-- The union operator, the collection of elements of elements of a set -/ def Union : Set → Set := pSet.resp.eval 1 { val := pSet.Union, property := sorry } notation:1024 "⋃" => Mathlib.Set.Union @[simp] theorem mem_Union {x : Set} {y : Set} : y ∈ ⋃ ↔ ∃ (z : Set), ∃ (H : z ∈ x), y ∈ z := sorry @[simp] theorem Union_singleton {x : Set} : ⋃ = x := sorry theorem singleton_inj {x : Set} {y : Set} (H : singleton x = singleton y) : x = y := let this : ⋃ = ⋃ := congr_arg ⋃ H; eq.mp (Eq._oldrec (Eq.refl (x = ⋃)) Union_singleton) (eq.mp (Eq._oldrec (Eq.refl (⋃ = ⋃)) Union_singleton) this) /-- The binary union operation -/ protected def union (x : Set) (y : Set) : Set := ⋃ /-- The binary intersection operation -/ protected def inter (x : Set) (y : Set) : Set := has_sep.sep (fun (z : Set) => z ∈ y) x /-- The set difference operation -/ protected def diff (x : Set) (y : Set) : Set := has_sep.sep (fun (z : Set) => ¬z ∈ y) x protected instance has_union : has_union Set := has_union.mk Set.union protected instance has_inter : has_inter Set := has_inter.mk Set.inter protected instance has_sdiff : has_sdiff Set := has_sdiff.mk Set.diff @[simp] theorem mem_union {x : Set} {y : Set} {z : Set} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := sorry @[simp] theorem mem_inter {x : Set} {y : Set} {z : Set} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := mem_sep @[simp] theorem mem_diff {x : Set} {y : Set} {z : Set} : z ∈ x \ y ↔ z ∈ x ∧ ¬z ∈ y := mem_sep theorem induction_on {p : Set → Prop} (x : Set) (h : ∀ (x : Set), (∀ (y : Set), y ∈ x → p y) → p x) : p x := sorry theorem regularity (x : Set) (h : x ≠ ∅) : ∃ (y : Set), ∃ (H : y ∈ x), x ∩ y = ∅ := sorry /-- The image of a (definable) set function -/ def image (f : Set → Set) [H : pSet.definable 1 f] : Set → Set := let r : pSet.resp 1 := pSet.definable.resp f; pSet.resp.eval 1 { val := pSet.image (subtype.val r), property := sorry } theorem image.mk (f : Set → Set) [H : pSet.definable 1 f] (x : Set) {y : Set} (h : y ∈ x) : f y ∈ image f x := sorry @[simp] theorem mem_image {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : y ∈ image f x ↔ ∃ (z : Set), ∃ (H : z ∈ x), f z = y := sorry /-- Kuratowski ordered pair -/ def pair (x : Set) (y : Set) : Set := insert (singleton x) (singleton (insert x (singleton y))) /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set → Set → Prop) (x : Set) (y : Set) : Set := has_sep.sep (fun (z : Set) => ∃ (a : Set), ∃ (H : a ∈ x), ∃ (b : Set), ∃ (H : b ∈ y), z = pair a b ∧ p a b) (powerset (powerset (x ∪ y))) @[simp] theorem mem_pair_sep {p : Set → Set → Prop} {x : Set} {y : Set} {z : Set} : z ∈ pair_sep p x y ↔ ∃ (a : Set), ∃ (H : a ∈ x), ∃ (b : Set), ∃ (H : b ∈ y), z = pair a b ∧ p a b := sorry theorem pair_inj {x : Set} {y : Set} {x' : Set} {y' : Set} (H : pair x y = pair x' y') : x = x' ∧ y = y' := sorry /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set → Set → Set := pair_sep fun (a b : Set) => True @[simp] theorem mem_prod {x : Set} {y : Set} {z : Set} : z ∈ prod x y ↔ ∃ (a : Set), ∃ (H : a ∈ x), ∃ (b : Set), ∃ (H : b ∈ y), z = pair a b := sorry @[simp] theorem pair_mem_prod {x : Set} {y : Set} {a : Set} {b : Set} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := sorry /-- `is_func x y f` is the assertion `f : x → y` where `f` is a ZFC function (a set of ordered pairs) -/ def is_func (x : Set) (y : Set) (f : Set) := f ⊆ prod x y ∧ ∀ (z : Set), z ∈ x → exists_unique fun (w : Set) => pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x : Set) (y : Set) : Set := has_sep.sep (fun (f : Set) => is_func x y f) (powerset (prod x y)) @[simp] theorem mem_funs {x : Set} {y : Set} {f : Set} : f ∈ funs x y ↔ is_func x y f := sorry -- TODO(Mario): Prove this computably protected instance map_definable_aux (f : Set → Set) [H : pSet.definable 1 f] : pSet.definable 1 fun (y : Set) => pair y (f y) := classical.all_definable fun (y : Set) => pair y (f y) /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ def map (f : Set → Set) [H : pSet.definable 1 f] : Set → Set := image fun (y : Set) => pair y (f y) @[simp] theorem mem_map {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : y ∈ map f x ↔ ∃ (z : Set), ∃ (H : z ∈ x), pair z (f z) = y := mem_image theorem map_unique {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {z : Set} (zx : z ∈ x) : exists_unique fun (w : Set) => pair z w ∈ map f x := sorry @[simp] theorem map_is_func {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : is_func x y (map f x) ↔ ∀ (z : Set), z ∈ x → f z ∈ y := sorry end Set def Class := set Set namespace Class protected instance has_subset : has_subset Class := has_subset.mk set.subset protected instance has_sep : has_sep Set Class := has_sep.mk set.sep protected instance has_emptyc : has_emptyc Class := has_emptyc.mk fun (a : Set) => False protected instance inhabited : Inhabited Class := { default := ∅ } protected instance has_insert : has_insert Set Class := has_insert.mk set.insert protected instance has_union : has_union Class := has_union.mk set.union protected instance has_inter : has_inter Class := has_inter.mk set.inter protected instance has_neg : Neg Class := { neg := set.compl } protected instance has_sdiff : has_sdiff Class := has_sdiff.mk set.diff /-- Coerce a set into a class -/ def of_Set (x : Set) : Class := set_of fun (y : Set) => y ∈ x protected instance has_coe : has_coe Set Class := has_coe.mk of_Set /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a set satisfying `p` -/ def to_Set (p : Set → Prop) (A : Class) := ∃ (x : Set), ↑x = A ∧ p x /-- `A ∈ B` if `A` is a set which is a member of `B` -/ protected def mem (A : Class) (B : Class) := to_Set B A protected instance has_mem : has_mem Class Class := has_mem.mk Class.mem theorem mem_univ {A : Class} : A ∈ univ ↔ ∃ (x : Set), ↑x = A := exists_congr fun (x : Set) => and_true (↑x = A) /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class) : Class := set_of fun (y : Set) => ↑y ∈ x /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class) : set Class := set_of fun (y : Class) => y ∈ x /-- The power class of a class is the class of all subclasses that are sets -/ def powerset (x : Class) : Class := Cong_to_Class (𝒫 x) /-- The union of a class is the class of all members of sets in the class -/ def Union (x : Class) : Class := ⋃₀Class_to_Cong x notation:1024 "⋃" => Mathlib.Class.Union theorem of_Set.inj {x : Set} {y : Set} (h : ↑x = ↑y) : x = y := sorry @[simp] theorem to_Set_of_Set (p : Set → Prop) (x : Set) : to_Set p ↑x ↔ p x := sorry @[simp] theorem mem_hom_left (x : Set) (A : Class) : ↑x ∈ A ↔ A x := to_Set_of_Set (fun (x : Set) => A x) x @[simp] theorem mem_hom_right (x : Set) (y : Set) : coe y x ↔ x ∈ y := iff.rfl @[simp] theorem subset_hom (x : Set) (y : Set) : ↑x ⊆ ↑y ↔ x ⊆ y := iff.rfl @[simp] theorem sep_hom (p : Set → Prop) (x : Set) : ↑(has_sep.sep (fun (y : Set) => p y) x) = has_sep.sep (fun (y : Set) => p y) ↑x := set.ext fun (y : Set) => Set.mem_sep @[simp] theorem empty_hom : ↑∅ = ∅ := set.ext fun (y : Set) => (fun (this : y ∈ ↑∅ ↔ False) => this) (eq.mpr (id (propext (iff_false (y ∈ ↑∅)))) (Set.mem_empty y)) @[simp] theorem insert_hom (x : Set) (y : Set) : insert x ↑y = ↑(insert x y) := set.ext fun (z : Set) => iff.symm Set.mem_insert @[simp] theorem union_hom (x : Set) (y : Set) : ↑x ∪ ↑y = ↑(x ∪ y) := set.ext fun (z : Set) => iff.symm Set.mem_union @[simp] theorem inter_hom (x : Set) (y : Set) : ↑x ∩ ↑y = ↑(x ∩ y) := set.ext fun (z : Set) => iff.symm Set.mem_inter @[simp] theorem diff_hom (x : Set) (y : Set) : ↑x \ ↑y = ↑(x \ y) := set.ext fun (z : Set) => iff.symm Set.mem_diff @[simp] theorem powerset_hom (x : Set) : powerset ↑x = ↑(Set.powerset x) := set.ext fun (z : Set) => iff.symm Set.mem_powerset @[simp] theorem Union_hom (x : Set) : ⋃ = ↑⋃ := sorry /-- The definite description operator, which is {x} if `{a | p a} = {x}` and ∅ otherwise -/ def iota (p : Set → Prop) : Class := ⋃ theorem iota_val (p : Set → Prop) (x : Set) (H : ∀ (y : Set), p y ↔ y = x) : iota p = ↑x := sorry /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `(Set → Prop) → Set` function. -/ theorem iota_ex (p : Set → Prop) : iota p ∈ univ := sorry /-- Function value -/ def fval (F : Class) (A : Class) : Class := iota fun (y : Set) => to_Set (fun (x : Set) => F (Set.pair x y)) A infixl:100 "′" => Mathlib.Class.fval theorem fval_ex (F : Class) (A : Class) : F′A ∈ univ := iota_ex fun (y : Set) => to_Set (fun (x : Set) => F (Set.pair x y)) A end Class namespace Set @[simp] theorem map_fval {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} (h : y ∈ x) : ↑(map f x)′↑y = ↑(f y) := sorry /-- A choice function on the set of nonempty sets `x` -/ def choice (x : Set) : Set := map (fun (y : Set) => classical.epsilon fun (z : Set) => z ∈ y) x theorem choice_mem_aux (x : Set) (h : ¬∅ ∈ x) (y : Set) (yx : y ∈ x) : (classical.epsilon fun (z : Set) => z ∈ y) ∈ y := sorry theorem choice_is_func (x : Set) (h : ¬∅ ∈ x) : is_func x ⋃ (choice x) := sorry theorem choice_mem (x : Set) (h : ¬∅ ∈ x) (y : Set) (yx : y ∈ x) : ↑(choice x)′↑y ∈ ↑y := sorry
f60f68c7f1b4921fda5bc0f48b33d7d5e8098626
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/category/Rel.lean
bc75375e4b5d1c9caa72bd61a992f37f223b4630
[ "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
860
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.category.basic /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The category of types with binary relations as morphisms. -/ namespace category_theory universe u /-- A type synonym for `Type`, which carries the category instance for which morphisms are binary relations. -/ def Rel := Type u instance Rel.inhabited : inhabited Rel := by unfold Rel; apply_instance /-- The category of types with binary relations as morphisms. -/ instance rel : large_category Rel := { hom := λ X Y, X → Y → Prop, id := λ X, λ x y, x = y, comp := λ X Y Z f g x z, ∃ y, f x y ∧ g y z } end category_theory
8ce0df4310c14a4ccfab02f42af83fa7e1a5920c
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/bug1.lean
9f35ec34f21be456ae8a50a368e35e05b672b879
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
638
lean
definition bool : Type.{1} := Type.{0} definition and (p q : bool) : bool := ∀ c : bool, (p → q → c) → c infixl `∧`:25 := and constant a : bool -- Error theorem and_intro (p q : bool) (H1 : p) (H2 : q) : a := fun (c : bool) (H : p -> q -> c), H H1 H2 -- Error theorem and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ p := fun (c : bool) (H : p -> q -> c), H H1 H2 -- Error theorem and_intro (p q : bool) (H1 : p) (H2 : q) : q ∧ p := fun (c : bool) (H : p -> q -> c), H H1 H2 -- Correct theorem and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ q := fun (c : bool) (H : p -> q -> c), H H1 H2 check and_intro
de6a254bb230c9af07288cbe2c799ca0e6fdc243
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1677.lean
8fa1c41536773307dccd0de267a5f42afa6347e6
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
351
lean
import data.real.basic -- BEGIN example {x y : ℝ} (h : x ≤ y) : ¬ y ≤ x ↔ x ≠ y := begin split, { contrapose!, rintro rfl, reflexivity }, contrapose!, exact le_antisymm h end example {x y : ℝ} (h : x ≤ y) : ¬ y ≤ x ↔ x ≠ y := ⟨λ h₀ h₁, h₀ (by rw h₁), λ h₀ h₁, h₀ (le_antisymm h h₁)⟩ -- END
8e9265bcae0ce3b1710d99a518872b94bdb38569
1e561612e7479c100cd9302e3fe08cbd2914aa25
/mathlib4_experiments/Data/Finset/Basic.lean
cd7d3f3519e24cba204d86095852a04334a91b03
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib4_experiments
8de8ed7193f70748a7529e05d831203a7c64eedb
87cb879b4d602c8ecfd9283b7c0b06015abdbab1
refs/heads/master
1,687,971,389,316
1,620,336,942,000
1,620,336,942,000
353,994,588
7
4
Apache-2.0
1,622,410,748,000
1,617,361,732,000
Lean
UTF-8
Lean
false
false
120,486
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ --import data.multiset.finset_ops --import tactic.monotonicity --import tactic.apply --import tactic.nth_rewrite import mathlib4_experiments.Data.Multiset.Basic /-! # Finite sets Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `finset α` is defined as a structure with 2 fields: 1. `val` is a `multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `list` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i in (s : finset α), f i`; 2. `∏ i in (s : finset α), f i`. Lean refers to these operations as `big_operator`s. More information can be found in `algebra.big_operators.basic`. Finsets are directly used to define fintypes in Lean. A `fintype α` instance for a type `α` consists of a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `data.fintype.basic`. ## Main declarations ### Main definitions * `finset`: Defines a type for the finite subsets of `α`. Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `finset.has_mem`: Defines membership `a ∈ (s : finset α)`. * `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`. * `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`, then it holds for the finset obtained by inserting a new element. * `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. * `finset.card`: `card s : ℕ` returns the cardinalilty of `s : finset α`. The API for `card`'s interaction with operations on finsets is extensive. TODO: The noncomputable sister `fincard` is about to be added into mathlib. ### Finset constructions * `singleton`: Denoted by `{a}`; the finset consisting of one element. * `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `finset.diag`: Given `s`, `diag s` is the set of pairs `(a, a)` with `a ∈ s`. See also `finset.off_diag`: Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. * `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`. * `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`. * `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `finset.subset`: Lots of API about lattices, otherwise behaves exactly as one would expect. * `finset.union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `finset.bUnion` for finite unions. * `finset.inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. TODO: `finset.bInter` for finite intersections. * `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. ### Operations on two or more finsets * `finset.insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `finset.union`: see "The lattice structure on subsets of finsets" * `finset.inter`: see "The lattice structure on subsets of finsets" * `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `finset.sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`. * `finset.prod`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `data.finset.pi`. * `finset.sigma`: Given finsets of `α` and `β`, defines finsets of the dependent sum type `Σ α, β` * `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a `s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. * `finset.bInter`: TODO: Implemement finite intersections. ### Maps constructed using finsets * `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ### Predicates on finsets * `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `finset.nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form. ### Equivalences between finsets * The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ open Multiset Subtype Nat Function /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α) := (val : Multiset α) (nodup : nodup val) /- TO BE PORTED variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl @[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := set.exists_of_ssubset h /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩ /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance inhabited_finset : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := by { rw nonempty_iff_ne_empty, exact not_not, } theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_not_nonempty (h : ¬ nonempty α) (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem $ λ x, false.elim $ not_nonempty_iff_imp_false.1 h x /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { intros h, subst h, simp, }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, }, end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := begin split, { intro hs, apply or.imp_right _ s.eq_empty_or_nonempty, rintro ⟨t, ht⟩, apply subset.antisymm hs, rwa [singleton_subset_iff, ←mem_singleton.1 (hs ht)] }, rintro (rfl | rfl), { exact empty_subset _ }, exact subset.refl _, end @[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty] lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### cons -/ /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s := by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff @[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl @[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 := rfl @[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 (or.inl rfl)⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a::l) hl := by simp [← multiset.cons_coe] /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} := begin ext, simp [or.comm] end @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty section universe u /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype end lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[elab_as_eliminator] lemma cons_induction {α : Type*} {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [cons_val] } end) nd @[elab_as_eliminator] lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion @[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} : (∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union {s₁ t₁ s₂ t₂ : finset α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∪ s₂ ⊆ t₁ ∪ t₂ := by { intros x hx, rw finset.mem_union at hx ⊢, tauto } theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end lemma exists_mem_subset_of_subset_bUnion_of_directed_on {α ι : Type*} {f : ι → set α} {c : set ι} {a : ι} (hac : a ∈ c) (hc : directed_on (λ i j, f i ⊆ f j) c) {s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i := begin classical, revert hs, apply s.induction_on, { intros, use [a, hac], simp }, { intros b t hbt htc hbtc, obtain ⟨i : ι , hic : i ∈ c, hti : (t : set α) ⊆ f i⟩ := htc (set.subset.trans (t.subset_insert b) hbtc), obtain ⟨j, hjc, hbj⟩ : ∃ j ∈ c, b ∈ f j, by simpa [set.mem_bUnion_iff] using hbtc (t.mem_insert_self b), rcases hc j hjc i hic with ⟨k, hkc, hk, hk'⟩, use [k, hkc], rw [coe_insert, set.insert_subset], exact ⟨hk hbj, trans hti hk'⟩ } end /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ -- TODO: some of these results may have simpler proofs, once there are enough results -- to obtain the `lattice` instance. theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl @[simp] theorem inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice } @[simp] lemma bot_eq_empty : (⊥ : finset α) = ∅ := rfl instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.semilattice_inf_bot, ..finset.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff lemma union_subset_iff {s₁ s₂ s₃ : finset α} : s₁ ∪ s₂ ⊆ s₃ ↔ s₁ ⊆ s₃ ∧ s₂ ⊆ s₃ := (sup_le_iff : s₁ ⊔ s₂ ≤ s₃ ↔ s₁ ≤ s₃ ∧ s₂ ≤ s₃) lemma subset_inter_iff {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ ∩ s₃ ↔ s₁ ⊆ s₂ ∧ s₁ ⊆ s₃ := (le_inf_iff : s₁ ≤ s₂ ⊓ s₃ ↔ s₁ ≤ s₂ ∧ s₁ ≤ s₃) theorem inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := (inf_eq_left : s ⊓ t = s ↔ s ≤ t) theorem inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := (inf_eq_right : t ⊓ s = s ↔ s ≤ t) /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := begin refine ⟨λ h, _, congr_arg _⟩, rw eq_of_mem_of_not_mem_erase hx, rw ←h, simp, end lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h instance : generalized_boolean_algebra (finset α) := { sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter], tauto }, inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff, inf_eq_inter, not_mem_empty], tauto }, ..finset.has_sdiff, ..finset.distrib_lattice, ..finset.semilattice_inf_bot } lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := sup_sdiff_of_le h theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := sdiff_inf @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := sdiff_inf_self_left @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := sdiff_inf_self_right @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := sdiff_bot @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := sdiff_le_sdiff ‹t₁ ≤ t₂› ‹s₂ ≤ s₁› @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := sup_sdiff_symm lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl @[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty := by simp [finset.nonempty] @[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ := by simpa [eq_empty_iff_forall_not_mem] /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩ /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], tauto, } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := ne_of_gt $ nat.sub_pos_of_lt $ mem_range.1 hx end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := begin assume j, rw subtype.ext_iff_val, apply nat.sub_add_cancel, simpa using j.2 end, right_inv := λ j, nat.add_sub_cancel _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := {a} end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero @[simp] lemma to_finset_subset (m1 m2 : multiset α) : m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace finset @[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s := by { ext, rw [multiset.mem_to_finset, ←mem_def] } end finset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := begin rintro s -, cases s with t hl, induction t using quot.ind with l, refine ⟨l, hl, (to_finset_eq hl).symm⟩ end theorem to_finset_surjective : surjective (to_finset : list α → finset α) := by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ } lemma to_finset_eq_iff_perm_erase_dup {l l' : list α} : l.to_finset = l'.to_finset ↔ l.erase_dup ~ l'.erase_dup := by simp [finset.ext_iff, perm_ext (nodup_erase_dup _) (nodup_erase_dup _)] lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset := to_finset_eq_iff_perm_erase_dup.mpr h.erase_dup @[simp] lemma to_finset_append {l l' : list α} : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset := begin induction l with hd tl hl, { simp }, { simp [hl] } end @[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset := to_finset_eq_of_perm _ _ (reverse_perm l) end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl @[simp] theorem mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.to_embedding ↔ f.symm b ∈ s := by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ } theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f := calc ↑(s.map f) = f '' s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right @[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) : s.map (equiv.cast h).to_embedding == s := by { subst h, simp } theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] /-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := eq_of_veq (map_filter _ _ _) theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ @[simp] lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty := ⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) @[simp] theorem image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := begin split, { rintros ⟨i, hi⟩, simp only [mem_image, exists_prop, mem_range], exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ }, { rintro h, simp only [mem_image, exists_prop, set.mem_range, mem_range] at *, rcases h with ⟨i, hi, ha⟩, use ⟨i, ha⟩ }, end lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] /-- Because `finset.image` requires a `decidable_eq` instances for the target type, we can only construct a `functor finset` when working classically. -/ instance [Π P, decidable P] : functor finset := { map := λ α β f s, s.image f, } instance [Π P, decidable P] : is_lawful_functor finset := { id_map := λ α x, image_id, comp_map := λ α β γ f g s, image_image.symm, } /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, rw mem_map, change (∃ a : {x // p x}, ∃ H, (a : α) = x) ↔ _, split, { rintros ⟨y, hy, hyval⟩, rw [mem_subtype, hyval] at hy, rw mem_filter, use hy, rw ← hyval, use y.property }, { intro hx, rw mem_filter at hx, use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ } end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin classical, split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { refine ⟨∅, set.empty_subset _, _⟩, convert finset.image_empty _ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi], congr end end image end finset theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm namespace finset /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} := by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val] theorem card_le_one {s : finset α} : s.card ≤ 1 ↔ ∀ (a ∈ s) (b ∈ s), a = b := begin rcases s.eq_empty_or_nonempty with rfl|⟨x, hx⟩, { simp }, refine (nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨_, _⟩), { rintro ⟨y, rfl⟩, simp }, { exact λ h, ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, h _ hy _ hx⟩⟩ } end theorem card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by { rw card_le_one, tauto } lemma card_le_one_iff_subset_singleton [nonempty α] {s : finset α} : s.card ≤ 1 ↔ ∃ (x : α), s ⊆ {x} := begin split, { assume H, by_cases h : ∃ x, x ∈ s, { rcases h with ⟨x, hx⟩, refine ⟨x, λ y hy, _⟩, rw [card_le_one.1 H y hy x hx, mem_singleton] }, { push_neg at h, inhabit α, exact ⟨default α, λ y hy, (h y hy).elim⟩ } }, { rintros ⟨x, hx⟩, rw ← card_singleton x, exact card_le_of_subset hx } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ theorem one_lt_card {s : finset α} : 1 < s.card ↔ ∃ (a ∈ s) (b ∈ s), a ≠ b := by { rw ← not_iff_not, push_neg, exact card_le_one } lemma one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := by { rw one_lt_card, simp only [exists_prop, exists_and_distrib_left] } @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _ lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 := begin cases (finset.decidable_mem x s), { simp [finset.singleton_inter_of_not_mem h] }, { simp [finset.singleton_inter_of_mem h] }, end theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} : card s - 1 ≤ card (erase s a) := begin by_cases h : a ∈ s, { rw [card_erase_of_mem h], refl }, { rw [erase_eq_of_not_mem h], apply nat.sub_le } end @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach end card end finset theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card := card_le_of_le (erase_dup_le _) lemma list.card_to_finset [decidable_eq α] (l : list α) : finset.card l.to_finset = l.erase_dup.length := rfl theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ namespace finset section card theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := by simpa only [card_map] using (s.1.map f).to_finset_card_le theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : set.inj_on f s) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem inj_on_of_card_image_eq [decidable_eq β] {f : α → β} {s : finset α} (H : card (image f s) = card s) : set.inj_on f s := begin change (s.1.map f).erase_dup.card = s.1.card at H, have : (s.1.map f).erase_dup = s.1.map f, { apply multiset.eq_of_le_of_card_le, { apply multiset.erase_dup_le }, rw H, simp only [multiset.card_map] }, rw multiset.erase_dup_eq_self at this, apply inj_on_of_nodup_map this, end theorem card_image_eq_iff_inj_on [decidable_eq β] {f : α → β} {s : finset α} : (s.image f).card = s.card ↔ set.inj_on f s := ⟨inj_on_of_card_image_eq, card_image_of_inj_on⟩ theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) : (s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f := by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] } @[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := multiset.card_map _ _ @[simp] lemma card_subtype (p : α → Prop) [decidable_pred p] (s : finset α) : (s.subtype p).card = (s.filter p).card := by simp [finset.subtype] lemma card_eq_of_bijective {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_filter_le (s : finset α) (p : α → Prop) [decidable_pred p] : card (s.filter p) ≤ card s := card_le_of_subset $ filter_subset _ _ theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := begin classical, calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ image_subset_iff.2 hf end /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin classical, by_contra hz, push_neg at hz, refine hc.not_le (card_le_card_of_inj_on f hf _), intros x hx y hy, contrapose, exact hz x hx y hy, end lemma le_card_of_inj_on_range {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀ (i<n) (j<n), f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simpa only [mem_range]) /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ def strong_induction {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) : ∀ (s : finset α), p s | s := H s (λ t h, have card t < card s, from card_lt_card h, strong_induction t) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} lemma strong_induction_eq {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : finset α) : strong_induction H s = H s (λ t h, strong_induction H t) := by rw strong_induction /-- Analogue of `strong_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀ t ⊂ s, p t) → p s) → p s := λ s H, strong_induction H s lemma strong_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) : s.strong_induction_on H = H s (λ t h, t.strong_induction_on H) := by { dunfold strong_induction_on, rw strong_induction } @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) : (s ∪ t).card = s.card + t.card := begin rw [← card_union_add_card_inter], convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h end lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from (left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)).injective, subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card section bUnion /-! ### bUnion This section is about the bounded union of an indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. -/ variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bUnion s t` is the union of `t x` over `x ∈ s`. (This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/ protected def bUnion (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bUnion_val (s : finset α) (t : α → finset β) : (s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl @[simp] theorem mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bUnion_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t := ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a := begin classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] end theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) := begin ext x, simp only [mem_bUnion, mem_inter], tauto end theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) := by rw [inter_comm, bUnion_inter]; simp [inter_comm] theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bUnion t = s.bUnion (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bUnion_insert, ih]) theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bUnion t).image f = s.bUnion (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bUnion_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop] lemma bUnion_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop] lemma bUnion_subset_bUnion_of_subset_left {α : Type*} {s₁ s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t := begin intro x, simp only [and_imp, mem_bUnion, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma subset_bUnion_of_mem {s : finset α} (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u := begin apply subset.trans _ (bUnion_subset_bUnion_of_subset_left u (singleton_subset_iff.2 xs)), exact subset_of_eq singleton_bUnion.symm, end lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm] @[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s := by { rw bUnion_singleton, exact image_id } lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bUnion (λa, s.filter $ (λc, f c = a)) = s := ext $ λ b, by simpa using h b lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s := bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g) lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) : (s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) := by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] } end bUnion /-! ### prod -/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ (s.image prod.fst).product (s.image prod.snd) := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ theorem product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bUnion (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, } lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros; finish, }, { rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, }, end end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bUnion [decidable_eq (Σ a, σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bUnion (λa, (t a).map $ embedding.sigma_mk a) := by { ext ⟨x, y⟩, simp [and.left_comm] } end sigma /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty] lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bUnion_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bUnion f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] } end lemma disjoint_bUnion_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bUnion f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bUnion_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop) [decidable_pred p] : (s.filter p).card + (s.filter (not ∘ p)).card = s.card := by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], } end disjoint section self_prod variables (s : finset α) [decidable_eq α] /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd) @[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, finish, }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end end self_prod /-- Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B inside it. -/ lemma exists_intermediate_set {A B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin classical, rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, induction k with k ih generalizing A, { exact ⟨A, h₂, subset.refl _, h.symm⟩ }, { have : (A \ B).nonempty, { rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm, nat.add_sub_cancel, nat.add_succ], apply nat.succ_pos }, rcases this with ⟨a, ha⟩, have z : i + card B + k = card (erase A a), { rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ], rw mem_sdiff at ha, exact ha.1 }, rcases ih _ z with ⟨B', hB', B'subA', cards⟩, { exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ }, { rintros t th, apply mem_erase_of_ne_of_mem _ (h₂ th), rintro rfl, exact not_mem_sdiff_of_mem_right th ha } } end /-- We can shrink A to any smaller size. -/ lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩ /-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/ def fin_range (k : ℕ) : finset (fin k) := ⟨list.fin_range k, list.nodup_fin_range k⟩ @[simp] lemma fin_range_card {k : ℕ} : (fin_range k).card = k := by simp [fin_range] @[simp] lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k := list.mem_fin_range m @[simp] lemma coe_fin_range (k : ℕ) : (fin_range k : set (fin k)) = set.univ := set.eq_univ_of_forall mem_fin_range /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_refl : (equiv.refl α).finset_congr = equiv.refl _ := by { ext, simp } @[simp] lemma finset_congr_symm (e : α ≃ β) : e.finset_congr.symm = e.symm.finset_congr := rfl @[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) : e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr := by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] } end equiv namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace multiset variable [decidable_eq α] theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h lemma disjoint_to_finset (m1 m2 : multiset α) : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, split, { intro h, intros a ha1 ha2, rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset -/
5de520d438fdeb92738b3619c1472efcd82d8964
19e65f097e49ef249bf10eb0d5cc0075bc4216a2
/src/utils/cmp.lean
22d403b86f6480e3d7e8ff20e40b75a92375b1bd
[]
no_license
UVM-M52/week-8-fgdorais
6eccbcf373d9a872949d37e434e18b082cf6ae48
251579081a03fadedc1606bcda8004cabf217ac3
refs/heads/master
1,613,424,257,678
1,583,335,096,000
1,583,335,096,000
244,933,167
0
0
null
null
null
null
UTF-8
Lean
false
false
6,256
lean
section variables {α : Type*} [semiring α] theorem mul_two_eq_add_self (x : α) : x * 2 = x + x := show x * (1 + 1) = x + x, by rw [mul_add, mul_one] theorem two_mul_eq_add_self (x : α) : 2 * x = x + x := show (1 + 1) * x = x + x, by rw [add_mul, one_mul] end namespace linear_ordered_ring variables (α : Type*) [i : linear_ordered_ring α] include i lemma one_pos : (0:α) < 1 := zero_lt_one α lemma two_pos : (0:α) < 2 := _root_.add_pos (one_pos α) (one_pos α) variable {α} lemma add_pos (x y : α) : 0 < x → 0 < y → 0 < x + y := _root_.add_pos lemma succ_pos (x : α) : 0 < x → 0 < x + 1 := λ h, add_pos x 1 h (one_pos α) -- linear_ordered_ring.mul_pos (x y : α) : 0 < x → 0 < y → 0 < x * y lemma bit0_pos (x : α) : 0 < x → 0 < bit0 x := λ h, add_pos x x h h lemma bit1_pos (x : α) : 0 < x → 0 < bit1 x := λ h, succ_pos (bit0 x) (bit0_pos x h) class num_pos (x : α) := (elim : (0:α) < x) namespace num_pos variable {i} @[priority 30] instance one : @num_pos α i (1:α) := ⟨one_pos α⟩ @[priority 30] instance two : @num_pos α i (2:α) := ⟨two_pos α⟩ @[priority 30] instance bit0 (x : α) [@num_pos α i x] : @num_pos α i (bit0 x) := ⟨bit0_pos x (elim x)⟩ @[priority 30] instance bit1 (x : α) [@num_pos α i x] : @num_pos α i (bit1 x) := ⟨bit1_pos x (elim x)⟩ @[priority 10] instance succ (x : α) [@num_pos α i x] : @num_pos α i (x+1) := ⟨succ_pos x (elim x)⟩ @[priority 20] instance add (x y : α) [@num_pos α i x] [@num_pos α i y] : @num_pos α i (x + y) := ⟨add_pos x y (elim x) (elim y)⟩ @[priority 30] instance mul (x y : α) [@num_pos α i x] [@num_pos α i y] : @num_pos α i (x * y) := ⟨mul_pos x y (elim x) (elim y)⟩ end num_pos class num_nonzero (x : α) := (elim : x ≠ (0:α)) @[priority 30] instance of_pos (x : α) {i : linear_ordered_ring α} [@num_pos α i x] : num_nonzero x := ⟨ne_of_gt $ num_pos.elim x⟩ end linear_ordered_ring theorem pos_trivial {α : Type*} [linear_ordered_ring α] (x : α) [linear_ordered_ring.num_pos x] : (0:α) < x := linear_ordered_ring.num_pos.elim x theorem nonzero_trivial {α : Type*} [linear_ordered_ring α] (x : α) [linear_ordered_ring.num_nonzero x] : x ≠ 0 := linear_ordered_ring.num_nonzero.elim x section variables {α : Type*} [linear_ordered_ring α] theorem le_of_mul_ge_mul_left {a b c : α} : c * b ≤ c * a → c < 0 → a ≤ b := begin intros h hc, have hc : -c > 0 := neg_pos_of_neg hc, apply le_of_mul_le_mul_left _ hc, apply le_of_neg_le_neg, rw [neg_mul_eq_neg_mul, neg_mul_eq_neg_mul, neg_neg], assumption, end theorem le_of_mul_ge_mul_right {a b c : α} : b * c ≤ a * c → c < 0 → a ≤ b := begin intros h hc, have hc : -c > 0 := neg_pos_of_neg hc, apply le_of_mul_le_mul_right _ hc, apply le_of_neg_le_neg, rw [neg_mul_eq_mul_neg, neg_mul_eq_mul_neg, neg_neg], assumption, end end section variables {α : Type*} [linear_ordered_field α] theorem div_le_of_le_mul_of_pos {x y : α} (z : α) : x ≤ y*z → 0 < z → x/z ≤ y := begin intros hm hz, apply le_of_mul_le_mul_right _ hz, transitivity x, { apply le_of_eq, apply div_mul_cancel, apply ne_of_gt, assumption }, { assumption }, end theorem le_div_of_mul_le_of_pos {x y : α} (z : α) : x*z ≤ y → 0 < z → x ≤ y/z := begin intros hm hz, apply le_of_mul_le_mul_right _ hz, transitivity y, { assumption }, { apply le_of_eq, symmetry, apply div_mul_cancel, apply ne_of_gt, assumption }, end theorem le_div_of_mul_ge_of_neg {x y : α} (z : α) : y ≤ x*z → z < 0 → x ≤ y/z := begin intros hm hz, apply le_of_mul_ge_mul_right _ hz, transitivity y, { apply le_of_eq, apply div_mul_cancel, apply ne_of_lt, assumption }, { assumption }, end theorem div_le_of_ge_mul_of_neg {x y : α} (z : α) : y*z ≤ x → z < 0 → x/z ≤ y := begin intros hm hz, apply le_of_mul_ge_mul_right _ hz, transitivity x, { assumption }, { apply le_of_eq, symmetry, apply div_mul_cancel, apply ne_of_lt, assumption }, end end namespace order inductive {u} lt_cmp {α : Type u} [has_lt α] (x y : α) : Type u | eq : x = y → lt_cmp | lt : x < y → lt_cmp | gt : y < x → lt_cmp inductive {u} le_cmp {α : Type u} [has_le α] (x y : α) : Type u | le : x ≤ y → le_cmp | ge : y ≤ x → le_cmp variables {α : Type*} [decidable_linear_order α] def lt_compare (x y : α) : lt_cmp x y := if hlt : x < y then lt_cmp.lt hlt else if hgt : y < x then lt_cmp.gt hgt else lt_cmp.eq $ le_antisymm (le_of_not_gt hgt) (le_of_not_gt hlt) def le_compare (x y : α) : le_cmp x y := if h : x < y then le_cmp.le (le_of_lt h) else le_cmp.ge (le_of_not_gt h) @[elab_as_eliminator] def trichotomy_on (x y : α) {C : Sort*} : (x = y → C) → (x < y → C) → (y < x → C) → C := λ heq hlt hgt, lt_cmp.cases_on (lt_compare x y) heq hlt hgt @[elab_as_eliminator] def dichotomy_on (x y : α) {C : Sort*} : (x ≤ y → C) → (y ≤ x → C) → C := λ hle hge, le_cmp.cases_on (le_compare x y) hle hge end order namespace tactic open interactive /-- `by_trichotomy (x, y)` splits the goal into three branches, the first assuming `x = y`, the second assuming `x < y` and the third assuming `y < x`. This tactic requires that terms `x` and `y` have the same type and that this type has `decidable_linear_order` instance. -/ meta def interactive.by_trichotomy : parse types.texpr → tactic unit := λ e, do { `(@prod.mk %%t %%.(t) %%x %%y) ← to_expr e, d ← to_expr ``(decidable_linear_order %%t) >>= mk_instance <|> fail ("cannot find decidable_linear_order instance for type " ++ to_string t), to_expr ``(@order.trichotomy_on %%t %%d %%x %%y) >>= apply >> skip } /-- `by_trichotomy (x, y)` splits the goal into two branches, the first assuming `x ≤ y` and the second assuming `y ≤ x`. This tactic requires that terms `x` and `y` have the same type and that this type has `decidable_linear_order` instance. -/ meta def interactive.by_dichotomy : parse types.texpr → tactic unit := λ e, do { `(@prod.mk %%t %%.(t) %%x %%y) ← to_expr e, d ← to_expr ``(decidable_linear_order %%t) >>= mk_instance <|> fail ("cannot find decidable_linear_order instance for " ++ to_string t), to_expr ``(@order.dichotomy_on %%t %%d %%x %%y) >>= apply >> skip } end tactic
d73cd984798e44065da4b74ab45e5acf168f1d0f
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Elab/Tactic/ElabTerm.lean
bfc96460c73bdea8e21c95f520fd0fa6a7d5fb8d
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,092
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.CollectMVars import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Assert import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /- `elabTerm` for Tactics and basic tactics that use it. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := withRef stx $ liftTermElabM $ Term.withoutErrToSorry do let e ← Term.elabTerm stx expectedType? Term.synthesizeSyntheticMVars mayPostpone instantiateMVars e def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone ensureHasType expectedType? e @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match_syntax stx with | `(tactic| exact $e) => do let (g, gs) ← getMainGoal withMVarContext g do let decl ← getMVarDecl g let val ← elabTermEnsuringType e decl.type ensureHasNoMVars val assignExprMVar g val setGoals gs | _ => throwUnsupportedSyntax def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do let val ← elabTermEnsuringType stx expectedType? let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) let newMVarIds ← if allowNaturalHoles then pure newMVarIds.toList else let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← getMVarDecl mvarId).kind.isNatural let syntheticMVarIds ← newMVarIds.filterM fun mvarId => return !(← getMVarDecl mvarId).kind.isNatural Term.logUnassignedUsingErrorInfos naturalMVarIds pure syntheticMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds pure (val, newMVarIds) /- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do let (g, gs) ← getMainGoal withMVarContext g do let decl ← getMVarDecl g let (val, gs') ← elabTermWithHoles stx decl.type tagSuffix allowNaturalHoles assignExprMVar g val setGoals (gs ++ gs') @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match_syntax stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtinTactic «refine!»] def evalRefineBang : Tactic := fun stx => match_syntax stx with | `(tactic| refine! $e) => refineCore e `refine (allowNaturalHoles := true) | _ => throwUnsupportedSyntax def evalApplyLikeTactic (tac : MVarId → Expr → MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do let (g, gs) ← getMainGoal let gs' ← withMVarContext g do let decl ← getMVarDecl g let val ← elabTerm e none true let gs' ← tac g val Term.synthesizeSyntheticMVarsNoPostponing pure gs' setGoals (gs' ++ gs) @[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match_syntax stx with | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx => match_syntax stx with | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(← Meta.existsIntro mvarId e)]) e | _ => throwUnsupportedSyntax /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := do let (mvarId, others) ← getMainGoal withMVarContext mvarId do let e ← elabTerm stx none match e with | Expr.fvar fvarId _ => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let (fvarId, mvarId) ← liftMetaM do let mvarId ← Meta.assert mvarId userName type e Meta.intro1Core mvarId preserveBinderNames setGoals $ mvarId::others pure fvarId match userName? with | none => intro `h false | some userName => intro userName true end Lean.Elab.Tactic
eb29b69e495f83cb07384f2b021f9461cc15d855
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/equiv/fin.lean
eae5b663119c03d4272889dc6d81c289d0ffcecb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
15,051
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fin.vec_notation import logic.equiv.basic import tactic.norm_num /-! # Equivalences for `fin n` -/ universes u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv_punit_of_unique /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, by norm_num, refine fin.cases _ _, by norm_num, exact λi, fin_zero_elim i end, begin rintro ⟨_|_⟩, { refl }, { rw ← fin.succ_zero_eq_one, refl } end⟩ /-- `Π i : fin 2, α i` is equivalent to `α 0 × α 1`. See also `fin_two_arrow_equiv` for a non-dependent version and `prod_equiv_pi_fin_two` for a version with inputs `α β : Type u`. -/ @[simps {fully_applied := ff}] def pi_fin_two_equiv (α : fin 2 → Type u) : (Π i, α i) ≃ α 0 × α 1 := { to_fun := λ f, (f 0, f 1), inv_fun := λ p, fin.cons p.1 $ fin.cons p.2 fin_zero_elim, left_inv := λ f, funext $ fin.forall_fin_two.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } lemma fin.preimage_apply_01_prod {α : fin 2 → Type u} (s : set (α 0)) (t : set (α 1)) : (λ f : Π i, α i, (f 0, f 1)) ⁻¹' s ×ˢ t = set.pi set.univ (fin.cons s $ fin.cons t fin.elim0) := begin ext f, have : (fin.cons s (fin.cons t fin.elim0) : Π i, set (α i)) 1 = t := rfl, simp [fin.forall_fin_two, this] end lemma fin.preimage_apply_01_prod' {α : Type u} (s t : set α) : (λ f : fin 2 → α, (f 0, f 1)) ⁻¹' s ×ˢ t = set.pi set.univ ![s, t] := fin.preimage_apply_01_prod s t /-- A product space `α × β` is equivalent to the space `Π i : fin 2, γ i`, where `γ = fin.cons α (fin.cons β fin_zero_elim)`. See also `pi_fin_two_equiv` and `fin_two_arrow_equiv`. -/ @[simps {fully_applied := ff }] def prod_equiv_pi_fin_two (α β : Type u) : α × β ≃ Π i : fin 2, ![α, β] i := (pi_fin_two_equiv (fin.cons α (fin.cons β fin_zero_elim))).symm /-- The space of functions `fin 2 → α` is equivalent to `α × α`. See also `pi_fin_two_equiv` and `prod_equiv_pi_fin_two`. -/ @[simps { fully_applied := ff }] def fin_two_arrow_equiv (α : Type*) : (fin 2 → α) ≃ α × α := { inv_fun := λ x, ![x.1, x.2], .. pi_fin_two_equiv (λ _, α) } /-- `Π i : fin 2, α i` is order equivalent to `α 0 × α 1`. See also `order_iso.fin_two_arrow_equiv` for a non-dependent version. -/ def order_iso.pi_fin_two_iso (α : fin 2 → Type u) [Π i, preorder (α i)] : (Π i, α i) ≃o α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, map_rel_iff' := λ f g, iff.symm fin.forall_fin_two } /-- The space of functions `fin 2 → α` is order equivalent to `α × α`. See also `order_iso.pi_fin_two_iso`. -/ def order_iso.fin_two_arrow_iso (α : Type*) [preorder α] : (fin 2 → α) ≃o α × α := { to_equiv := fin_two_arrow_equiv α, .. order_iso.pi_fin_two_iso (λ _, α) } /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := (fin.cast h).to_equiv @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) : fin (n + 1) ≃ option (fin n) := { to_fun := i.insert_nth none some, inv_fun := λ x, x.cases_on' i (fin.succ_above i), left_inv := λ x, fin.succ_above_cases i (by simp) (λ j, by simp) x, right_inv := λ x, by cases x; dsimp; simp } @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i = none := by simp [fin_succ_equiv'] @[simp] lemma fin_succ_equiv'_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : fin_succ_equiv' i (i.succ_above j) = some j := @fin.insert_nth_apply_succ_above n (λ _, option (fin n)) i _ _ _ lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i) m.cast_succ = some m := by rw [← fin.succ_above_below _ _ h, fin_succ_equiv'_succ_above] lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i) m.succ = some m := by rw [← fin.succ_above_above _ _ h, fin_succ_equiv'_succ_above] @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i := rfl @[simp] lemma fin_succ_equiv'_symm_some {n : ℕ} (i : fin (n + 1)) (j : fin n) : (fin_succ_equiv' i).symm (some j) = i.succ_above j := rfl lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := fin.succ_above_below i m h lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm (some m) = m.succ := fin.succ_above_above i m h lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm m = m.cast_succ := fin_succ_equiv'_symm_some_below h lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm m = m.succ := fin_succ_equiv'_symm_some_above h /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' 0 @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := rfl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := fin_succ_equiv'_above (fin.zero_le _) @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := fin_succ_equiv'_symm_none _ @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := congr_fun fin.succ_above_zero m @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl /-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/ def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' (fin.last n) @[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) : fin_succ_equiv_last i.cast_succ = some i := fin_succ_equiv'_below i.2 @[simp] lemma fin_succ_equiv_last_last {n : ℕ} : fin_succ_equiv_last (fin.last n) = none := by simp [fin_succ_equiv_last] @[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm (some i) = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm ↑i = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} : fin_succ_equiv_last.symm none = fin.last n := fin_succ_equiv'_symm_none _ /-- Equivalence between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ @[simps { fully_applied := ff}] def equiv.pi_fin_succ_above_equiv {n : ℕ} (α : fin (n + 1) → Type u) (i : fin (n + 1)) : (Π j, α j) ≃ α i × (Π j, α (i.succ_above j)) := { to_fun := λ f, (f i, λ j, f (i.succ_above j)), inv_fun := λ f, i.insert_nth f.1 f.2, left_inv := λ f, by simp [fin.insert_nth_eq_iff], right_inv := λ f, by simp } /-- Order isomorphism between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ def order_iso.pi_fin_succ_above_iso {n : ℕ} (α : fin (n + 1) → Type u) [Π i, has_le (α i)] (i : fin (n + 1)) : (Π j, α j) ≃o α i × (Π j, α (i.succ_above j)) := { to_equiv := equiv.pi_fin_succ_above_equiv α i, map_rel_iff' := λ f g, i.forall_iff_succ_above.symm } /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := sum.elim (fin.cast_add n) (fin.nat_add m), inv_fun := λ i, @fin.add_cases m n (λ _, fin m ⊕ fin n) sum.inl sum.inr i, left_inv := λ x, by { cases x with y y; dsimp; simp }, right_inv := λ x, by refine fin.add_cases (λ i, _) (λ i, _) x; simp } @[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) : (fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) : (fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.nat_add m i := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add (x : fin m) : fin_sum_fin_equiv.symm (fin.cast_add n x) = sum.inl x := fin_sum_fin_equiv.symm_apply_apply (sum.inl x) @[simp] lemma fin_sum_fin_equiv_symm_apply_nat_add (x : fin n) : fin_sum_fin_equiv.symm (fin.nat_add m x) = sum.inr x := fin_sum_fin_equiv.symm_apply_apply (sum.inr x) /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_cast_add (k : fin m) (n : ℕ) : fin_add_flip (fin.cast_add n k) = fin.nat_add n k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_nat_add (k : fin n) (m : ℕ) : fin_add_flip (fin.nat_add m k) = fin.cast_add m k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_mk_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := by convert fin_add_flip_apply_cast_add ⟨k, h⟩ n @[simp] lemma fin_add_flip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, tsub_le_self.trans_lt $ add_comm m n ▸ h₂⟩ := begin convert fin_add_flip_apply_nat_add ⟨k - m, (tsub_lt_iff_right h₁).2 _⟩ m, { simp [add_tsub_cancel_of_le h₁] }, { rwa add_comm } end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_mk_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ @[simps] def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2 + n * x.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, (x.div_nat, x.mod_nat), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying values are retained. This is the `order_iso` version of `fin.cast_le`. -/ @[simps apply symm_apply] def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} := { to_fun := λ i, ⟨fin.cast_le h i, by simpa using i.is_lt⟩, inv_fun := λ i, ⟨i, i.prop⟩, left_inv := λ _, by simp, right_inv := λ _, by simp, map_rel_iff' := λ _ _, by simp } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
0f743416514893870c7ca326946e82678d1cc7d8
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/vm_eval_crash.lean
2e2d009e4e2d7d07d58530ef66aa094f50ae1c9c
[ "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
9
lean
#eval 10
b4093f36df6e6e13772271eafff26d9abf223e2e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/normed_space/SemiNormedGroup.lean
526136ec9702e30b1e20eb6d71025b8896b23f97
[ "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
5,424
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Riccardo Brasca -/ import analysis.normed_space.normed_group_hom import category_theory.concrete_category.bundled_hom import category_theory.limits.shapes.zero /-! # The category of seminormed groups We define `SemiNormedGroup`, the category of seminormed groups and normed group homs between them, as well as `SemiNormedGroup₁`, the subcategory of norm non-increasing morphisms. -/ noncomputable theory universes u open category_theory /-- The category of seminormed abelian groups and bounded group homomorphisms. -/ def SemiNormedGroup : Type (u+1) := bundled semi_normed_group namespace SemiNormedGroup instance bundled_hom : bundled_hom @normed_group_hom := ⟨@normed_group_hom.to_fun, @normed_group_hom.id, @normed_group_hom.comp, @normed_group_hom.coe_inj⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] SemiNormedGroup /-- Construct a bundled `SemiNormedGroup` from the underlying type and typeclass. -/ def of (M : Type u) [semi_normed_group M] : SemiNormedGroup := bundled.of M instance (M : SemiNormedGroup) : semi_normed_group M := M.str @[simp] lemma coe_of (V : Type u) [semi_normed_group V] : (SemiNormedGroup.of V : Type u) = V := rfl @[simp] lemma coe_id (V : SemiNormedGroup) : ⇑(𝟙 V) = id := rfl @[simp] lemma coe_comp {M N K : SemiNormedGroup} (f : M ⟶ N) (g : N ⟶ K) : ((f ≫ g) : M → K) = g ∘ f := rfl instance : has_zero SemiNormedGroup := ⟨of punit⟩ instance : inhabited SemiNormedGroup := ⟨0⟩ instance : limits.has_zero_morphisms.{u (u+1)} SemiNormedGroup := {} @[simp] lemma zero_apply {V W : SemiNormedGroup} (x : V) : (0 : V ⟶ W) x = 0 := rfl instance has_zero_object : limits.has_zero_object SemiNormedGroup.{u} := { zero := 0, unique_to := λ X, { default := 0, uniq := λ a, by { ext ⟨⟩, exact a.map_zero, }, }, unique_from := λ X, { default := 0, uniq := λ f, by ext } } end SemiNormedGroup /-- `SemiNormedGroup₁` is a type synonym for `SemiNormedGroup`, which we shall equip with the category structure consisting only of the norm non-increasing maps. -/ @[derive has_coe_to_sort] def SemiNormedGroup₁ : Type (u+1) := bundled semi_normed_group namespace SemiNormedGroup₁ instance : large_category.{u} SemiNormedGroup₁ := { hom := λ X Y, { f : normed_group_hom X Y // f.norm_noninc }, id := λ X, ⟨normed_group_hom.id X, normed_group_hom.norm_noninc.id⟩, comp := λ X Y Z f g, ⟨(g : normed_group_hom Y Z).comp (f : normed_group_hom X Y), g.2.comp f.2⟩, } @[ext] lemma hom_ext {M N : SemiNormedGroup₁} (f g : M ⟶ N) (w : (f : M → N) = (g : M → N)) : f = g := subtype.eq (normed_group_hom.ext (congr_fun w)) instance : concrete_category.{u} SemiNormedGroup₁ := { forget := { obj := λ X, X, map := λ X Y f, f, }, forget_faithful := {} } /-- Construct a bundled `SemiNormedGroup₁` from the underlying type and typeclass. -/ def of (M : Type u) [semi_normed_group M] : SemiNormedGroup₁ := bundled.of M instance (M : SemiNormedGroup₁) : semi_normed_group M := M.str /-- Promote a morphism in `SemiNormedGroup` to a morphism in `SemiNormedGroup₁`. -/ def mk_hom {M N : SemiNormedGroup} (f : M ⟶ N) (i : f.norm_noninc) : SemiNormedGroup₁.of M ⟶ SemiNormedGroup₁.of N := ⟨f, i⟩ @[simp] lemma mk_hom_apply {M N : SemiNormedGroup} (f : M ⟶ N) (i : f.norm_noninc) (x) : mk_hom f i x = f x := rfl /-- Promote an isomorphism in `SemiNormedGroup` to an isomorphism in `SemiNormedGroup₁`. -/ @[simps] def mk_iso {M N : SemiNormedGroup} (f : M ≅ N) (i : f.hom.norm_noninc) (i' : f.inv.norm_noninc) : SemiNormedGroup₁.of M ≅ SemiNormedGroup₁.of N := { hom := mk_hom f.hom i, inv := mk_hom f.inv i', hom_inv_id' := by { apply subtype.eq, exact f.hom_inv_id, }, inv_hom_id' := by { apply subtype.eq, exact f.inv_hom_id, }, } instance : has_forget₂ SemiNormedGroup₁ SemiNormedGroup := { forget₂ := { obj := λ X, X, map := λ X Y f, f.1, }, } @[simp] lemma coe_of (V : Type u) [semi_normed_group V] : (SemiNormedGroup₁.of V : Type u) = V := rfl @[simp] lemma coe_id (V : SemiNormedGroup₁) : ⇑(𝟙 V) = id := rfl @[simp] lemma coe_comp {M N K : SemiNormedGroup₁} (f : M ⟶ N) (g : N ⟶ K) : ((f ≫ g) : M → K) = g ∘ f := rfl instance : has_zero SemiNormedGroup₁ := ⟨of punit⟩ instance : inhabited SemiNormedGroup₁ := ⟨0⟩ instance : limits.has_zero_morphisms.{u (u+1)} SemiNormedGroup₁ := { has_zero := λ X Y, { zero := ⟨0, normed_group_hom.norm_noninc.zero⟩, }, comp_zero' := λ X Y f Z, by { ext, refl, }, zero_comp' := λ X Y Z f, by { ext, simp, }, } @[simp] lemma zero_apply {V W : SemiNormedGroup₁} (x : V) : (0 : V ⟶ W) x = 0 := rfl instance has_zero_object : limits.has_zero_object SemiNormedGroup₁.{u} := { zero := 0, unique_to := λ X, { default := 0, uniq := λ a, by { ext ⟨⟩, exact a.1.map_zero, }, }, unique_from := λ X, { default := 0, uniq := λ f, by ext } } lemma iso_isometry {V W : SemiNormedGroup₁} (i : V ≅ W) : isometry i.hom := begin apply normed_group_hom.isometry_of_norm, intro v, apply le_antisymm (i.hom.2 v), calc ∥v∥ = ∥i.inv (i.hom v)∥ : by rw [coe_hom_inv_id] ... ≤ ∥i.hom v∥ : i.inv.2 _, end end SemiNormedGroup₁
48ac165ffcc7c833b5308af16f085bd32860ed89
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0505.lean
a8b1a5d98e3e97fd2b03c4df72f85502a187b07c
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
251
lean
open classical variables p q : Prop example (h : ¬(p ∧ q)) : ¬p ∨ ¬q := or.elim (em p) (assume hp : p, or.inr (show ¬q, from assume hq : q, h ⟨hp, hq⟩)) (assume hp : ¬p, or.inl hp)
8e1c81f4a10a6064449be8b191188d97a02ff0da
e953c38599905267210b87fb5d82dcc3e52a4214
/library/theories/number_theory/irrational_roots.lean
d291f1c11d9cfc18c22c00ce625e86933d279de7
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
7,155
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad A proof that if n > 1 and a > 0, then the nth root of a is irrational, unless a is a perfect nth power. -/ import data.rat .prime_factorization open eq.ops /- First, a textbook proof that sqrt 2 is irrational. -/ section open nat theorem sqrt_two_irrational {a b : ℕ} (co : coprime a b) : a^2 ≠ 2 * b^2 := assume H : a^2 = 2 * b^2, have even (a^2), from even_of_exists (exists.intro _ H), have even a, from even_of_even_pow this, obtain c (aeq : a = 2 * c), from exists_of_even this, have 2 * (2 * c^2) = 2 * b^2, by rewrite [-H, aeq, *pow_two, mul.assoc, mul.left_comm c], have 2 * c^2 = b^2, from eq_of_mul_eq_mul_left dec_trivial this, have even (b^2), from even_of_exists (exists.intro _ (eq.symm this)), have even b, from even_of_even_pow this, have 2 ∣ gcd a b, from dvd_gcd (dvd_of_even `even a`) (dvd_of_even `even b`), have 2 ∣ 1, from co ▸ this, absurd `2 ∣ 1` dec_trivial end /- Replacing 2 by an arbitrary prime and the power 2 by any n ≥ 1 yields the stronger result that the nth root of an integer is irrational, unless the integer is already a perfect nth power. -/ section open nat decidable theorem root_irrational {a b c n : ℕ} (npos : n > 0) (apos : a > 0) (co : coprime a b) (H : a^n = c * b^n) : b = 1 := have bpos : b > 0, from pos_of_ne_zero (suppose b = 0, have a^n = 0, by rewrite [H, this, zero_pow npos], assert a = 0, from eq_zero_of_pow_eq_zero this, show false, from ne_of_lt `0 < a` this⁻¹), have H₁ : ∀ p, prime p → ¬ p ∣ b, from take p, suppose prime p, suppose p ∣ b, assert p ∣ b^n, from dvd_pow_of_dvd_of_pos `p ∣ b` `n > 0`, have p ∣ a^n, by rewrite H; apply dvd_mul_of_dvd_right this, have p ∣ a, from dvd_of_prime_of_dvd_pow `prime p` this, have ¬ coprime a b, from not_coprime_of_dvd_of_dvd (gt_one_of_prime `prime p`) `p ∣ a` `p ∣ b`, show false, from this `coprime a b`, have b < 2, from by_contradiction (suppose ¬ b < 2, have b ≥ 2, from le_of_not_gt this, obtain p [primep pdvdb], from exists_prime_and_dvd this, show false, from H₁ p primep pdvdb), show b = 1, from (le.antisymm (le_of_lt_succ `b < 2`) (succ_le_of_lt `b > 0`)) end /- Here we state this in terms of the rationals, ℚ. The main difficulty is casting between ℕ, ℤ, and ℚ. -/ section open rat int nat decidable theorem denom_eq_one_of_pow_eq {q : ℚ} {n : ℕ} {c : ℤ} (npos : n > 0) (H : q^n = c) : denom q = 1 := let a := num q, b := denom q in have b ≠ 0, from ne_of_gt (denom_pos q), have bnz : b ≠ (0 : ℚ), from assume H, `b ≠ 0` (of_int.inj H), have bnnz : (#rat b^n ≠ 0), from assume bneqz, bnz (eq_zero_of_pow_eq_zero bneqz), have a^n / b^n = c, using bnz, by rewrite [*of_int_pow, -(!div_pow bnz), -eq_num_div_denom, -H], have a^n = c * b^n, from eq.symm (mul_eq_of_eq_div bnnz this⁻¹), have a^n = c * b^n, -- int version using this, by rewrite [-of_int_pow at this, -of_int_mul at this]; exact of_int.inj this, have (abs a)^n = abs c * (abs b)^n, using this, by rewrite [-int.abs_pow, this, int.abs_mul, int.abs_pow], have H₁ : (nat_abs a)^n = nat_abs c * (nat_abs b)^n, using this, by apply of_nat.inj; rewrite [int.of_nat_mul, +of_nat_pow, +of_nat_nat_abs]; assumption, have H₂ : nat.coprime (nat_abs a) (nat_abs b), from of_nat.inj !coprime_num_denom, have nat_abs b = 1, from by_cases (suppose q = 0, by rewrite this) (suppose q ≠ 0, have a ≠ 0, from suppose a = 0, `q ≠ 0` (by rewrite [eq_num_div_denom, `a = 0`, zero_div]), have nat_abs a ≠ 0, from suppose nat_abs a = 0, `a ≠ 0` (eq_zero_of_nat_abs_eq_zero this), show nat_abs b = 1, from (root_irrational npos (pos_of_ne_zero this) H₂ H₁)), show b = 1, using this, by rewrite [-of_nat_nat_abs_of_nonneg (le_of_lt !denom_pos), this] theorem eq_num_pow_of_pow_eq {q : ℚ} {n : ℕ} {c : ℤ} (npos : n > 0) (H : q^n = c) : c = (num q)^n := have denom q = 1, from denom_eq_one_of_pow_eq npos H, have of_int c = (num q)^n, using this, by rewrite [-H, eq_num_div_denom q at {1}, this, div_one, of_int_pow], show c = (num q)^n , from of_int.inj this end /- As a corollary, for n > 1, the nth root of a prime is irrational. -/ section open nat theorem not_eq_pow_of_prime {p n : ℕ} (a : ℕ) (ngt1 : n > 1) (primep : prime p) : p ≠ a^n := assume peq : p = a^n, have npos : n > 0, from lt.trans dec_trivial ngt1, have pnez : p ≠ 0, from (suppose p = 0, show false, by let H := (pos_of_prime primep); rewrite this at H; exfalso; exact !lt.irrefl H), have agtz : a > 0, from pos_of_ne_zero (suppose a = 0, show false, using npos pnez, by revert peq; rewrite [this, zero_pow npos]; exact pnez), have n * mult p a = 1, from calc n * mult p a = mult p (a^n) : using agtz, by rewrite [mult_pow n agtz primep] ... = mult p p : peq ... = 1 : mult_self (gt_one_of_prime primep), have n ∣ 1, from dvd_of_mul_right_eq this, have n = 1, from eq_one_of_dvd_one this, show false, using this, by rewrite this at ngt1; exact !lt.irrefl ngt1 open int rat theorem root_prime_irrational {p n : ℕ} {q : ℚ} (qnonneg : q ≥ 0) (ngt1 : n > 1) (primep : prime p) : q^n ≠ p := have numq : num q ≥ 0, from num_nonneg_of_nonneg qnonneg, have npos : n > 0, from lt.trans dec_trivial ngt1, suppose q^n = p, have p = (num q)^n, from eq_num_pow_of_pow_eq npos this, have p = (nat_abs (num q))^n, using this numq, by apply of_nat.inj; rewrite [this, of_nat_pow, of_nat_nat_abs_of_nonneg numq], show false, from not_eq_pow_of_prime _ ngt1 primep this end /- Thaetetus, who lives in the fourth century BC, is said to have proved the irrationality of square roots up to seventeen. In Chapter 4 of /Why Prove it Again/, John Dawson notes that Thaetetus may have used an approach similar to the one below. (See data/nat/gcd.lean for the key theorem, "div_gcd_eq_div_gcd".) -/ section open int example {a b c : ℤ} (co : coprime a b) (apos : a > 0) (bpos : b > 0) (H : a * a = c * (b * b)) : b = 1 := assert H₁ : gcd (c * b) a = gcd c a, from gcd_mul_right_cancel_of_coprime _ (coprime_swap co), have a * a = c * b * b, by rewrite -mul.assoc at H; apply H, have a div (gcd a b) = c * b div gcd (c * b) a, from div_gcd_eq_div_gcd this bpos apos, have a = c * b div gcd c a, using this, by revert this; rewrite [↑coprime at co, co, div_one, H₁]; intros; assumption, have a = b * (c div gcd c a), using this, by revert this; rewrite [mul.comm, !mul_div_assoc !gcd_dvd_left]; intros; assumption, have b ∣ a, from dvd_of_mul_right_eq this⁻¹, have b ∣ gcd a b, from dvd_gcd this !dvd.refl, have b ∣ 1, using this, by rewrite [↑coprime at co, co at this]; apply this, show b = 1, from eq_one_of_dvd_one (le_of_lt bpos) this end
3d66f3959ece58c1c928ad96bc998f24145d9a6f
4fa161becb8ce7378a709f5992a594764699e268
/src/field_theory/finite.lean
ebe93ac8507c9f8e8ebf03ef8ce42f411f011a62
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
10,070
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Joey van Langen, Casper Putz -/ import data.equiv.ring import data.zmod.basic import linear_algebra.basis import ring_theory.integral_domain /-! # Finite fields This file contains basic results about finite fields. Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. ## Main results 1. Every finite integral domain is a field (`field_of_integral_domain`). 2. The unit group of a finite field is a cyclic group of order `q - 1`. (`finite_field.is_cyclic` and `card_units`) 3. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is - `q-1` if `q-1 ∣ i` - `0` otherwise 4. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`. See `card'` for a variant. ## Notation Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. -/ variables {K : Type*} [field K] [fintype K] variables {R : Type*} [integral_domain R] local notation `q` := fintype.card K open_locale big_operators namespace finite_field open finset function section polynomial open polynomial /-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n` polynomial -/ lemma card_image_polynomial_eval [fintype R] [decidable_eq R] {p : polynomial R} (hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card := finset.card_le_mul_card_image _ _ (λ a _, calc _ = (p - C a).roots.card : congr_arg card (by simp [finset.ext_iff, mem_roots_sub_C hp, -sub_eq_add_neg]) ... ≤ _ : card_roots_sub_C' hp) /-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/ lemma exists_root_sum_quadratic [fintype R] {f g : polynomial R} (hf2 : degree f = 2) (hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 := by letI := classical.dec_eq R; exact suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))), begin simp only [disjoint_left, mem_image] at this, push_neg at this, rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩, exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩ end, assume hd : disjoint _ _, lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $ calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card ≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_of_subset (subset_univ _)) ... = fintype.card R + fintype.card R : two_mul _ ... < nat_degree f * (univ.image (λ x : R, eval x f)).card + nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card : add_lt_add_of_lt_of_le (lt_of_le_of_ne (card_image_polynomial_eval (by rw hf2; exact dec_trivial)) (mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR]))) (card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial)) ... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card : by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2, nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add] end polynomial lemma card_units : fintype.card (units K) = fintype.card K - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : K)⟩)], haveI := set_fintype {a : K | a ≠ 0}, haveI := set_fintype (@set.univ K), rw [fintype.card_congr (equiv.units_equiv_ne_zero _), ← @set.card_insert _ _ {a : K | a ≠ 0} _ (not_not.2 (eq.refl (0 : K))) (set.fintype_insert _ _), fintype.card_congr (equiv.set.univ K).symm], congr; simp [set.ext_iff, classical.em] end lemma prod_univ_units_id_eq_neg_one : (∏ x : units K, x) = (-1 : units K) := begin classical, have : (∏ x in (@univ (units K) _).erase (-1), x) = 1, from prod_involution (λ x _, x⁻¹) (by simp) (λ a, by simp [units.inv_eq_self_iff] {contextual := tt}) (λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt}) (by simp), rw [← insert_erase (mem_univ (-1 : units K)), prod_insert (not_mem_erase _ _), this, mul_one] end lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (fintype.card K - 1) = 1 := calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : units K) : by rw [units.coe_pow, units.coe_mk0] ... = 1 : by { classical, rw [← card_units, pow_card_eq_one], refl } variable (K) theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := begin haveI hp : fact p.prime := char_p.char_is_prime K p, letI : vector_space (zmod p) K := { .. (zmod.cast_hom (dvd_refl _) K).to_semimodule }, obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K, rw zmod.card at h, refine ⟨⟨n, _⟩, hp, h⟩, apply or.resolve_left (nat.eq_zero_or_pos n), rintro rfl, rw nat.pow_zero at h, have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) }, exact absurd this zero_ne_one, end theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩ @[simp] lemma cast_card_eq_zero : (q : K) = 0 := begin rcases char_p.exists K with ⟨p, _char_p⟩, resetI, rcases card K p with ⟨n, hp, hn⟩, simp only [char_p.cast_eq_zero_iff K p, hn], conv { congr, rw [← nat.pow_one p] }, exact nat.pow_dvd_pow _ n.2, end lemma forall_pow_eq_one_iff (i : ℕ) : (∀ x : units K, x ^ i = 1) ↔ q - 1 ∣ i := begin obtain ⟨x, hx⟩ := is_cyclic.exists_generator (units K), classical, rw [← card_units, ← order_of_eq_card_of_forall_mem_gpowers hx, order_of_dvd_iff_pow_eq_one], split, { intro h, apply h }, { intros h y, rw ← powers_eq_gpowers at hx, rcases hx y with ⟨j, rfl⟩, rw [← pow_mul, mul_comm, pow_mul, h, one_pow], } end /-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q` is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/ lemma sum_pow_units (i : ℕ) : ∑ x : units K, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 := begin let φ : units K →* K := { to_fun := λ x, x ^ i, map_one' := by rw [units.coe_one, one_pow], map_mul' := by { intros, rw [units.coe_mul, mul_pow] } }, haveI : decidable (φ = 1) := by { classical, apply_instance }, calc ∑ x : units K, φ x = if φ = 1 then fintype.card (units K) else 0 : sum_hom_units φ ... = if (q - 1) ∣ i then -1 else 0 : _, suffices : (q - 1) ∣ i ↔ φ = 1, { simp only [this], split_ifs with h h, swap, refl, rw [card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub], show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ }, rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff], apply forall_congr, intro x, rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply], refl, end /-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q` is equal to `0` if `i < q - 1`. -/ lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) : ∑ x : K, x ^ i = 0 := begin by_cases hi : i = 0, { simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], }, classical, have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h }, let φ : units K ↪ K := ⟨coe, units.ext⟩, have : univ.map φ = univ \ {0}, { ext x, simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero, mem_univ, mem_map, exists_prop_of_true, mem_singleton] }, calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i : by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton, zero_pow (nat.pos_of_ne_zero hi), add_zero] ... = ∑ x : units K, x ^ i : by { rw [← this, univ.sum_map φ], refl } ... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, } end end finite_field namespace zmod open finite_field polynomial lemma sum_two_squares (p : ℕ) [hp : fact p.prime] (x : zmod p) : ∃ a b : zmod p, a^2 + b^2 = x := begin cases hp.eq_two_or_odd with hp2 hp_odd, { unfreezeI, subst p, revert x, exact dec_trivial }, let f : polynomial (zmod p) := X^2, let g : polynomial (zmod p) := X^2 - C x, obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 := @exists_root_sum_quadratic _ _ _ f g (degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]), refine ⟨a, b, _⟩, rw ← sub_eq_zero, simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab, end end zmod namespace char_p lemma sum_two_squares (R : Type*) [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) : ∃ a b : ℕ, (a^2 + b^2 : R) = x := begin haveI := char_is_prime_of_pos R p, obtain ⟨a, b, hab⟩ := zmod.sum_two_squares p x, refine ⟨a.val, b.val, _⟩, simpa using congr_arg (zmod.cast_hom (dvd_refl _) R) hab end end char_p open_locale nat open zmod /-- The Fermat-Euler totient theorem. `nat.modeq.pow_totient` is an alternative statement of the same theorem. -/ @[simp] lemma zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ φ n = 1 := by rw [← card_units_eq_totient, pow_card_eq_one] /-- The Fermat-Euler totient theorem. `zmod.pow_totient` is an alternative statement of the same theorem. -/ lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] := begin cases n, {simp}, rw ← zmod.eq_iff_modeq_nat, let x' : units (zmod (n+1)) := zmod.unit_of_coprime _ h, have := zmod.pow_totient x', apply_fun (coe : units (zmod (n+1)) → zmod (n+1)) at this, simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one, nat.cast_one, cast_unit_of_coprime, units.coe_pow], end
b53cf73378ddcf0ee4e5b1b8bd158a7bf47472b5
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/ring/pi.lean
33f58e1f7d6c6190b71075975db0aeb893a3f36e
[ "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
2,588
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import tactic.pi_instances import algebra.group.pi import algebra.ring.basic /-! # Pi instances for ring This file defines instances for ring, semiring and related structures on Pi Types -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance mul_zero_class [Π i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance distrib [Π i, distrib $ f i] : distrib (Π i : I, f i) := by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance semiring [∀ i, semiring $ f i] : semiring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), neg := has_neg.neg, .. }; tactic.pi_instance_derive_field instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), neg := has_neg.neg, .. }; tactic.pi_instance_derive_field /-- A family of ring homomorphisms `f a : γ →+* β a` defines a ring homomorphism `pi.ring_hom f : γ →+* Π a, β a` given by `pi.ring_hom f x b = f b x`. -/ protected def ring_hom {α : Type u} {β : α → Type v} [R : Π a : α, semiring (β a)] {γ : Type w} [semiring γ] (f : Π a : α, γ →+* β a) : γ →+* Π a, β a := { to_fun := λ x b, f b x, map_add' := λ x y, funext $ λ z, (f z).map_add x y, map_mul' := λ x y, funext $ λ z, (f z).map_mul x y, map_one' := funext $ λ z, (f z).map_one, map_zero' := funext $ λ z, (f z).map_zero } end pi section ring_hom variable {I : Type*} -- The indexing type variable (f : I → Type*) -- The family of types already equipped with instances variables [Π i, semiring (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ def ring_hom.apply (i : I) : (Π i, f i) →+* f i := { ..(monoid_hom.apply f i), ..(add_monoid_hom.apply f i) } @[simp] lemma ring_hom.apply_apply (i : I) (g : Π i, f i) : (ring_hom.apply f i) g = g i := rfl end ring_hom
0c99e3f44ff19f3f8ccba944ec534f85b40f7b4a
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/complex/basic.lean
74951e27e6bbf9546fba4fa37bdb98f3c3b55e37
[ "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
30,931
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro -/ import data.real.sqrt /-! # The complex numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The complex numbers are modelled as ℝ^2 in the obvious way and it is shown that they form a field of characteristic zero. The result that the complex numbers are algebraically closed, see `field_theory.algebraic_closure`. -/ open_locale big_operators open set function /-! ### Definition and basic arithmmetic -/ /-- Complex numbers consist of two `real`s: a real part `re` and an imaginary part `im`. -/ structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex open_locale complex_conjugate noncomputable instance : decidable_eq ℂ := classical.dec_eq _ /-- The equivalence between the complex numbers and `ℝ × ℝ`. -/ @[simps apply] def equiv_real_prod : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], λ h, ext h.1 h.2⟩ theorem re_surjective : surjective re := λ x, ⟨⟨x, 0⟩, rfl⟩ theorem im_surjective : surjective im := λ y, ⟨⟨0, y⟩, rfl⟩ @[simp] theorem range_re : range re = univ := re_surjective.range_eq @[simp] theorem range_im : range im = univ := im_surjective.range_eq instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl lemma of_real_def (r : ℝ) : (r : ℂ) = ⟨r, 0⟩ := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ theorem of_real_injective : function.injective (coe : ℝ → ℂ) := λ z w, congr_arg re instance can_lift : can_lift ℂ ℝ coe (λ z, z.im = 0) := { prf := λ z hz, ⟨z.re, ext rfl hz.symm⟩ } /-- The product of a set on the real axis and a set on the imaginary axis of the complex plane, denoted by `s ×ℂ t`. -/ def _root_.set.re_prod_im (s t : set ℝ) : set ℂ := re ⁻¹' s ∩ im ⁻¹' t infix ` ×ℂ `:72 := set.re_prod_im lemma mem_re_prod_im {z : ℂ} {s t : set ℝ} : z ∈ s ×ℂ t ↔ z.re ∈ s ∧ z.im ∈ t := iff.rfl instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl @[simp] theorem of_real_eq_one {z : ℝ} : (z : ℂ) = 1 ↔ z = 1 := of_real_inj theorem of_real_ne_one {z : ℝ} : (z : ℂ) ≠ 1 ↔ z ≠ 1 := not_congr of_real_eq_one instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_sub ℂ := ⟨λ z w, ⟨z.re - w.re, z.im - w.im⟩⟩ instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma of_real_mul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp lemma of_real_mul' (r : ℝ) (z : ℂ) : (↑r * z) = ⟨r * z.re, r * z.im⟩ := ext (of_real_mul_re _ _) (of_real_mul_im _ _) /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_mul (z : ℂ) : I * z = ⟨-z.im, z.re⟩ := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp lemma mul_I_re (z : ℂ) : (z * I).re = -z.im := by simp lemma mul_I_im (z : ℂ) : (z * I).im = z.re := by simp lemma I_mul_re (z : ℂ) : (I * z).re = -z.im := by simp lemma I_mul_im (z : ℂ) : (I * z).im = z.re := by simp @[simp] lemma equiv_real_prod_symm_apply (p : ℝ × ℝ) : equiv_real_prod.symm p = p.1 + p.2 * I := by { ext; simp [equiv_real_prod] } /-! ### Commutative ring instance and lemmas -/ /- We use a nonstandard formula for the `ℕ` and `ℤ` actions to make sure there is no diamond from the other actions they inherit through the `ℝ`-action on `ℂ` and action transitivity defined in `data.complex.module.lean`. -/ instance : nontrivial ℂ := pullback_nonzero re rfl rfl instance : add_comm_group ℂ := by refine_struct { zero := (0 : ℂ), add := (+), neg := has_neg.neg, sub := has_sub.sub, nsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩, zsmul := λ n z, ⟨n • z.re - 0 * z.im, n • z.im + 0 * z.re⟩ }; intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf} instance : add_group_with_one ℂ := { nat_cast := λ n, ⟨n, 0⟩, nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ _, by ext; simp [nat.cast], int_cast := λ n, ⟨n, 0⟩, int_cast_of_nat := λ _, by ext; simp [λ n, show @coe ℕ ℂ ⟨_⟩ n = ⟨n, 0⟩, from rfl], int_cast_neg_succ_of_nat := λ _, by ext; simp [λ n, show @coe ℕ ℂ ⟨_⟩ n = ⟨n, 0⟩, from rfl], one := 1, .. complex.add_comm_group } instance : comm_ring ℂ := by refine_struct { zero := (0 : ℂ), add := (+), one := 1, mul := (*), npow := @npow_rec _ ⟨(1 : ℂ)⟩ ⟨(*)⟩, .. complex.add_group_with_one }; intros; try { refl }; apply ext_iff.2; split; simp; {ring1 <|> ring_nf} /-- This shortcut instance ensures we do not find `ring` via the noncomputable `complex.field` instance. -/ instance : ring ℂ := by apply_instance /-- This shortcut instance ensures we do not find `comm_semiring` via the noncomputable `complex.field` instance. -/ instance : comm_semiring ℂ := infer_instance /-- The "real part" map, considered as an additive group homomorphism. -/ def re_add_group_hom : ℂ →+ ℝ := { to_fun := re, map_zero' := zero_re, map_add' := add_re } @[simp] lemma coe_re_add_group_hom : (re_add_group_hom : ℂ → ℝ) = re := rfl /-- The "imaginary part" map, considered as an additive group homomorphism. -/ def im_add_group_hom : ℂ →+ ℝ := { to_fun := im, map_zero' := zero_im, map_add' := add_im } @[simp] lemma coe_im_add_group_hom : (im_add_group_hom : ℂ → ℝ) = im := rfl @[simp] lemma I_pow_bit0 (n : ℕ) : I ^ (bit0 n) = (-1) ^ n := by rw [pow_bit0', I_mul_I] @[simp] lemma I_pow_bit1 (n : ℕ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [pow_bit1', I_mul_I] /-! ### Complex conjugation -/ /-- This defines the complex conjugate as the `star` operation of the `star_ring ℂ`. It is recommended to use the ring endomorphism version `star_ring_end`, available under the notation `conj` in the locale `complex_conjugate`. -/ instance : star_ring ℂ := { star := λ z, ⟨z.re, -z.im⟩, star_involutive := λ x, by simp only [eta, neg_neg], star_mul := λ a b, by ext; simp [add_comm]; ring, star_add := λ a b, by ext; simp [add_comm] } @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl lemma conj_of_real (r : ℝ) : conj (r : ℂ) = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp lemma conj_bit0 (z : ℂ) : conj (bit0 z) = bit0 (conj z) := ext_iff.2 $ by simp [bit0] lemma conj_bit1 (z : ℂ) : conj (bit1 z) = bit1 (conj z) := ext_iff.2 $ by simp [bit0] @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp lemma conj_eq_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, by rw [e, conj_of_real]⟩ lemma conj_eq_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := conj_eq_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ lemma conj_eq_iff_im {z : ℂ} : conj z = z ↔ z.im = 0 := ⟨λ h, add_self_eq_zero.mp (neg_eq_iff_add_eq_zero.mp (congr_arg im h)), λ h, ext rfl (neg_eq_iff_add_eq_zero.mpr (add_self_eq_zero.mpr h))⟩ -- `simp_nf` complains about this being provable by `is_R_or_C.star_def` even -- though it's not imported by this file. @[simp, nolint simp_nf] lemma star_def : (has_star.star : ℂ → ℂ) = conj := rfl /-! ### Norm squared -/ /-- The norm squared function. -/ @[pp_nodot] def norm_sq : ℂ →*₀ ℝ := { to_fun := λ z, z.re * z.re + z.im * z.im, map_zero' := by simp, map_one' := by simp, map_mul' := λ z w, by { dsimp, ring } } lemma norm_sq_apply (z : ℂ) : norm_sq z = z.re * z.re + z.im * z.im := rfl @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_mk (x y : ℝ) : norm_sq ⟨x, y⟩ = x * x + y * y := rfl lemma norm_sq_add_mul_I (x y : ℝ) : norm_sq (x + y * I) = x ^ 2 + y ^ 2 := by rw [← mk_eq_add_mul_I, norm_sq_mk, sq, sq] lemma norm_sq_eq_conj_mul_self {z : ℂ} : (norm_sq z : ℂ) = conj z * z := by { ext; simp [norm_sq, mul_comm], } @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := norm_sq.map_zero @[simp] lemma norm_sq_one : norm_sq 1 = 1 := norm_sq.map_one @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma range_norm_sq : range norm_sq = Ici 0 := subset.antisymm (range_subset_iff.2 norm_sq_nonneg) $ λ x hx, ⟨real.sqrt x, by rw [norm_sq_of_real, real.mul_self_sqrt hx]⟩ lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := (norm_sq_nonneg z).lt_iff_ne.trans $ not_congr (eq_comm.trans norm_sq_eq_zero) @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] /-- The coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [sq, I_mul_I] @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by { rw [sub_eq_add_neg, norm_sq_add], simp only [ring_hom.map_neg, mul_neg, neg_re, tactic.ring.add_neg_eq_sub, norm_sq_neg] } /-! ### Inversion -/ noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ by simp protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] /-! ### Field instance and lemmas -/ noncomputable instance : field ℂ := { inv := has_inv.inv, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring, ..complex.nontrivial } @[simp] lemma I_zpow_bit0 (n : ℤ) : I ^ (bit0 n) = (-1) ^ n := by rw [zpow_bit0', I_mul_I] @[simp] lemma I_zpow_bit1 (n : ℤ) : I ^ (bit1 n) = (-1) ^ n * I := by rw [zpow_bit1', I_mul_I] lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] lemma conj_inv (x : ℂ) : conj (x⁻¹) = (conj x)⁻¹ := star_inv' _ @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := map_div₀ of_real r s @[simp, norm_cast] lemma of_real_zpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := map_zpow₀ of_real r n @[simp] lemma div_I (z : ℂ) : z / I = -(z * I) := (div_eq_iff_mul_eq I_ne_zero).2 $ by simp [mul_assoc] @[simp] lemma inv_I : I⁻¹ = -I := by simp [inv_eq_one_div] @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := map_inv₀ norm_sq z @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := map_div₀ norm_sq z w /-! ### Cast lemmas -/ @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := map_nat_cast of_real n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : ℂ) = n := map_int_cast of_real n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : ℂ) = n := map_rat_cast of_real n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ instance char_zero_complex : char_zero ℂ := char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h /-- A complex number `z` plus its conjugate `conj z` is `2` times its real part. -/ theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by simp only [add_conj, of_real_mul, of_real_one, of_real_bit0, mul_div_cancel_left (z.re:ℂ) two_ne_zero] /-- A complex number `z` minus its conjugate `conj z` is `2i` times its imaginary part. -/ theorem im_eq_sub_conj (z : ℂ) : (z.im : ℂ) = (z - conj(z))/(2 * I) := by simp only [sub_conj, of_real_mul, of_real_one, of_real_bit0, mul_right_comm, mul_div_cancel_left _ (mul_ne_zero two_ne_zero I_ne_zero : 2 * I ≠ 0)] /-! ### Absolute value -/ namespace abs_theory -- We develop enough theory to bundle `abs` into an `absolute_value` before making things public; -- this is so there's not two versions of it hanging around. local notation (name := abs) `abs` z := ((norm_sq z).sqrt) private lemma mul_self_abs (z : ℂ) : (abs z) * (abs z) = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) private lemma abs_nonneg' (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ lemma abs_conj (z : ℂ) : (abs (conj z)) = abs z := by simp private lemma abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z := begin rw [mul_self_le_mul_self_iff (abs_nonneg z.re) (abs_nonneg' _), abs_mul_abs_self, mul_self_abs], apply re_sq_le_norm_sq end private lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 private lemma abs_mul (z w : ℂ) : (abs (z * w)) = (abs z) * abs w := by rw [norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)] private lemma abs_add (z w : ℂ) : (abs (z + w)) ≤ (abs z) + abs w := (mul_self_le_mul_self_iff (abs_nonneg' (z + w)) (add_nonneg (abs_nonneg' z) (abs_nonneg' w))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (zero_lt_two' ℝ), ←real.sqrt_mul $ norm_sq_nonneg z, ←norm_sq_conj w, ←map_mul], exact re_le_abs (z * conj w) end /-- The complex absolute value function, defined as the square root of the norm squared. -/ noncomputable def _root_.complex.abs : absolute_value ℂ ℝ := { to_fun := λ x, abs x, map_mul' := abs_mul, nonneg' := abs_nonneg', eq_zero' := λ _, (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero, add_le' := abs_add } end abs_theory lemma abs_def : (abs : ℂ → ℝ) = λ z, (norm_sq z).sqrt := rfl lemma abs_apply {z : ℂ} : abs z = (norm_sq z).sqrt := rfl @[simp, norm_cast] lemma abs_of_real (r : ℝ) : abs r = |r| := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) lemma sq_abs (z : ℂ) : abs z ^ 2 = norm_sq z := real.sq_sqrt (norm_sq_nonneg _) @[simp] lemma sq_abs_sub_sq_re (z : ℂ) : abs z ^ 2 - z.re ^ 2 = z.im ^ 2 := by rw [sq_abs, norm_sq_apply, ← sq, ← sq, add_sub_cancel'] @[simp] lemma sq_abs_sub_sq_im (z : ℂ) : abs z ^ 2 - z.im ^ 2 = z.re ^ 2 := by rw [← sq_abs_sub_sq_re, sub_sub_cancel] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) @[simp] lemma range_abs : range abs = Ici 0 := subset.antisymm (range_subset_iff.2 abs.nonneg) $ λ x hx, ⟨x, abs_of_nonneg hx⟩ @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := abs_theory.abs_conj z @[simp] lemma abs_prod {ι : Type*} (s : finset ι) (f : ι → ℂ) : abs (s.prod f) = s.prod (λ i, abs (f i)) := map_prod abs _ _ @[simp] lemma abs_pow (z : ℂ) (n : ℕ) : abs (z ^ n) = abs z ^ n := map_pow abs z n @[simp] lemma abs_zpow (z : ℂ) (n : ℤ) : abs (z ^ n) = abs z ^ n := map_zpow₀ abs z n lemma abs_re_le_abs (z : ℂ) : |z.re| ≤ abs z := real.abs_le_sqrt $ by { rw [norm_sq_apply, ← sq], exact le_add_of_nonneg_right (mul_self_nonneg _) } lemma abs_im_le_abs (z : ℂ) : |z.im| ≤ abs z := real.abs_le_sqrt $ by { rw [norm_sq_apply, ← sq, ← sq], exact le_add_of_nonneg_left (sq_nonneg _) } lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 @[simp] lemma abs_re_lt_abs {z : ℂ} : |z.re| < abs z ↔ z.im ≠ 0 := by rw [abs, absolute_value.coe_mk, mul_hom.coe_mk, real.lt_sqrt (abs_nonneg _), norm_sq_apply, _root_.sq_abs, ← sq, lt_add_iff_pos_right, mul_self_pos] @[simp] lemma abs_im_lt_abs {z : ℂ} : |z.im| < abs z ↔ z.re ≠ 0 := by simpa using @abs_re_lt_abs (z * I) @[simp] lemma abs_abs (z : ℂ) : |(abs z)| = abs z := _root_.abs_of_nonneg (abs.nonneg _) lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ |z.re| + |z.im| := by simpa [re_add_im] using abs.add_le z.re (z.im * I) lemma abs_le_sqrt_two_mul_max (z : ℂ) : abs z ≤ real.sqrt 2 * max (|z.re|) (|z.im|) := begin cases z with x y, simp only [abs_apply, norm_sq_mk, ← sq], wlog hle : |x| ≤ |y|, { rw [add_comm, max_comm], exact this _ _ (le_of_not_le hle), }, calc real.sqrt (x ^ 2 + y ^ 2) ≤ real.sqrt (y ^ 2 + y ^ 2) : real.sqrt_le_sqrt (add_le_add_right (sq_le_sq.2 hle) _) ... = real.sqrt 2 * max (|x|) (|y|) : by rw [max_eq_right hle, ← two_mul, real.sqrt_mul two_pos.le, real.sqrt_sq_eq_abs], end lemma abs_re_div_abs_le_one (z : ℂ) : |z.re / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs.pos hz), one_mul, abs_re_le_abs] } lemma abs_im_div_abs_le_one (z : ℂ) : |z.im / z.abs| ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs.pos hz), one_mul, abs_im_le_abs] } @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] @[simp, norm_cast] lemma int_cast_abs (n : ℤ) : ↑|n| = abs n := by rw [← of_real_int_cast, abs_of_real, int.cast_abs] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by simp [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)] /-- We put a partial order on ℂ so that `z ≤ w` exactly if `w - z` is real and nonnegative. Complex numbers with different imaginary parts are incomparable. -/ protected def partial_order : partial_order ℂ := { le := λ z w, z.re ≤ w.re ∧ z.im = w.im, lt := λ z w, z.re < w.re ∧ z.im = w.im, lt_iff_le_not_le := λ z w, by { dsimp, rw lt_iff_le_not_le, tauto }, le_refl := λ x, ⟨le_rfl, rfl⟩, le_trans := λ x y z h₁ h₂, ⟨h₁.1.trans h₂.1, h₁.2.trans h₂.2⟩, le_antisymm := λ z w h₁ h₂, ext (h₁.1.antisymm h₂.1) h₁.2 } section complex_order localized "attribute [instance] complex.partial_order" in complex_order lemma le_def {z w : ℂ} : z ≤ w ↔ z.re ≤ w.re ∧ z.im = w.im := iff.rfl lemma lt_def {z w : ℂ} : z < w ↔ z.re < w.re ∧ z.im = w.im := iff.rfl @[simp, norm_cast] lemma real_le_real {x y : ℝ} : (x : ℂ) ≤ (y : ℂ) ↔ x ≤ y := by simp [le_def] @[simp, norm_cast] lemma real_lt_real {x y : ℝ} : (x : ℂ) < (y : ℂ) ↔ x < y := by simp [lt_def] @[simp, norm_cast] lemma zero_le_real {x : ℝ} : (0 : ℂ) ≤ (x : ℂ) ↔ 0 ≤ x := real_le_real @[simp, norm_cast] lemma zero_lt_real {x : ℝ} : (0 : ℂ) < (x : ℂ) ↔ 0 < x := real_lt_real lemma not_le_iff {z w : ℂ} : ¬(z ≤ w) ↔ w.re < z.re ∨ z.im ≠ w.im := by rw [le_def, not_and_distrib, not_le] lemma not_lt_iff {z w : ℂ} : ¬(z < w) ↔ w.re ≤ z.re ∨ z.im ≠ w.im := by rw [lt_def, not_and_distrib, not_lt] lemma not_le_zero_iff {z : ℂ} : ¬z ≤ 0 ↔ 0 < z.re ∨ z.im ≠ 0 := not_le_iff lemma not_lt_zero_iff {z : ℂ} : ¬z < 0 ↔ 0 ≤ z.re ∨ z.im ≠ 0 := not_lt_iff lemma eq_re_of_real_le {r : ℝ} {z : ℂ} (hz : (r : ℂ) ≤ z) : z = z.re := by { ext, refl, simp only [←(complex.le_def.1 hz).2, complex.zero_im, complex.of_real_im] } /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a strictly ordered ring. -/ protected def strict_ordered_comm_ring : strict_ordered_comm_ring ℂ := { zero_le_one := ⟨zero_le_one, rfl⟩, add_le_add_left := λ w z h y, ⟨add_le_add_left h.1 _, congr_arg2 (+) rfl h.2⟩, mul_pos := λ z w hz hw, by simp [lt_def, mul_re, mul_im, ← hz.2, ← hw.2, mul_pos hz.1 hw.1], ..complex.partial_order, ..complex.comm_ring, ..complex.nontrivial } localized "attribute [instance] complex.strict_ordered_comm_ring" in complex_order /-- With `z ≤ w` iff `w - z` is real and nonnegative, `ℂ` is a star ordered ring. (That is, a star ring in which the nonnegative elements are those of the form `star z * z`.) -/ protected def star_ordered_ring : star_ordered_ring ℂ := { nonneg_iff := λ r, by { refine ⟨λ hr, ⟨real.sqrt r.re, _⟩, λ h, _⟩, { have h₁ : 0 ≤ r.re := by { rw [le_def] at hr, exact hr.1 }, have h₂ : r.im = 0 := by { rw [le_def] at hr, exact hr.2.symm }, ext, { simp only [of_real_im, star_def, of_real_re, sub_zero, conj_re, mul_re, mul_zero, ←real.sqrt_mul h₁ r.re, real.sqrt_mul_self h₁] }, { simp only [h₂, add_zero, of_real_im, star_def, zero_mul, conj_im, mul_im, mul_zero, neg_zero] } }, { obtain ⟨s, rfl⟩ := h, simp only [←norm_sq_eq_conj_mul_self, norm_sq_nonneg, zero_le_real, star_def] } }, ..complex.strict_ordered_comm_ring } localized "attribute [instance] complex.star_ordered_ring" in complex_order end complex_order /-! ### Cauchy sequences -/ local notation `abs'` := has_abs.abs theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs.abs_abv_sub_le_abv_sub _ _) (hi j hj)⟩ /-- The limit of a Cauchy sequence of complex numbers. -/ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← ring_hom.map_sub, abs_conj]; exact hi j hj⟩ /-- The complex conjugate of a complex Cauchy sequence, as a complex Cauchy sequence. -/ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) /-- The absolute value of a complex Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs.abs_abv_sub_le_abv_sub _ _) (hi j hj)⟩) variables {α : Type*} (s : finset α) @[simp, norm_cast] lemma of_real_prod (f : α → ℝ) : ((∏ i in s, f i : ℝ) : ℂ) = ∏ i in s, (f i : ℂ) := ring_hom.map_prod of_real _ _ @[simp, norm_cast] lemma of_real_sum (f : α → ℝ) : ((∑ i in s, f i : ℝ) : ℂ) = ∑ i in s, (f i : ℂ) := ring_hom.map_sum of_real _ _ @[simp] lemma re_sum (f : α → ℂ) : (∑ i in s, f i).re = ∑ i in s, (f i).re := re_add_group_hom.map_sum f s @[simp] lemma im_sum (f : α → ℂ) : (∑ i in s, f i).im = ∑ i in s, (f i).im := im_add_group_hom.map_sum f s end complex
ef5b1473a461d100985cf13888b46fdeaf061aa8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/covering/vitali.lean
00af34b0a68e17e1fdc4e8d822a2fbc66e196748
[ "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
26,058
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.basic import measure_theory.constructions.borel_space.basic import measure_theory.covering.vitali_family /-! # Vitali covering theorems > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The topological Vitali covering theorem, in its most classical version, states the following. Consider a family of balls `(B (x_i, r_i))_{i ∈ I}` in a metric space, with uniformly bounded radii. Then one can extract a disjoint subfamily indexed by `J ⊆ I`, such that any `B (x_i, r_i)` is included in a ball `B (x_j, 5 r_j)`. We prove this theorem in `vitali.exists_disjoint_subfamily_covering_enlargment_closed_ball`. It is deduced from a more general version, called `vitali.exists_disjoint_subfamily_covering_enlargment`, which applies to any family of sets together with a size function `δ` (think "radius" or "diameter"). We deduce the measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 6 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. It is proved in `vitali.exists_disjoint_covering_ae`. A way to restate this theorem is to say that the set of closed sets `a` with nonempty interior covering a fixed proportion `1/C` of the ball `closed_ball x (3 * diam a)` forms a Vitali family. This version is given in `vitali.vitali_family`. -/ variables {α ι : Type*} open set metric measure_theory topological_space filter open_locale nnreal classical ennreal topology namespace vitali /-- Vitali covering theorem: given a set `t` of subsets of a type, one may extract a disjoint subfamily `u` such that the `τ`-enlargment of this family covers all elements of `t`, where `τ > 1` is any fixed number. When `t` is a family of balls, the `τ`-enlargment of `ball x r` is `ball x ((1+2τ) r)`. In general, it is expressed in terms of a function `δ` (think "radius" or "diameter"), positive and bounded on all elements of `t`. The condition is that every element `a` of `t` should intersect an element `b` of `u` of size larger than that of `a` up to `τ`, i.e., `δ b ≥ δ a / τ`. We state the lemma slightly more generally, with an indexed family of sets `B a` for `a ∈ t`, for wider applicability. -/ theorem exists_disjoint_subfamily_covering_enlargment (B : ι → set α) (t : set ι) (δ : ι → ℝ) (τ : ℝ) (hτ : 1 < τ) (δnonneg : ∀ a ∈ t, 0 ≤ δ a) (R : ℝ) (δle : ∀ a ∈ t, δ a ≤ R) (hne : ∀ a ∈ t, (B a).nonempty) : ∃ u ⊆ t, u.pairwise_disjoint B ∧ ∀ a ∈ t, ∃ b ∈ u, (B a ∩ B b).nonempty ∧ δ a ≤ τ * δ b := begin /- The proof could be formulated as a transfinite induction. First pick an element of `t` with `δ` as large as possible (up to a factor of `τ`). Then among the remaining elements not intersecting the already chosen one, pick another element with large `δ`. Go on forever (transfinitely) until there is nothing left. Instead, we give a direct Zorn-based argument. Consider a maximal family `u` of disjoint sets with the following property: if an element `a` of `t` intersects some element `b` of `u`, then it intersects some `b' ∈ u` with `δ b' ≥ δ a / τ`. Such a maximal family exists by Zorn. If this family did not intersect some element `a ∈ t`, then take an element `a' ∈ t` which does not intersect any element of `u`, with `δ a'` almost as large as possible. One checks easily that `u ∪ {a'}` still has this property, contradicting the maximality. Therefore, `u` intersects all elements of `t`, and by definition it satisfies all the desired properties. -/ let T : set (set ι) := {u | u ⊆ t ∧ u.pairwise_disjoint B ∧ ∀ a ∈ t, ∀ b ∈ u, (B a ∩ B b).nonempty → ∃ c ∈ u, (B a ∩ B c).nonempty ∧ δ a ≤ τ * δ c}, -- By Zorn, choose a maximal family in the good set `T` of disjoint families. obtain ⟨u, uT, hu⟩ : ∃ u ∈ T, ∀ v ∈ T, u ⊆ v → v = u, { refine zorn_subset _ (λ U UT hU, _), refine ⟨⋃₀ U, _, λ s hs, subset_sUnion_of_mem hs⟩, simp only [set.sUnion_subset_iff, and_imp, exists_prop, forall_exists_index, mem_sUnion, set.mem_set_of_eq], refine ⟨λ u hu, (UT hu).1, (pairwise_disjoint_sUnion hU.directed_on).2 (λ u hu, (UT hu).2.1), λ a hat b u uU hbu hab, _⟩, obtain ⟨c, cu, ac, hc⟩ : ∃ (c : ι) (H : c ∈ u), (B a ∩ B c).nonempty ∧ δ a ≤ τ * δ c := (UT uU).2.2 a hat b hbu hab, exact ⟨c, ⟨u, uU, cu⟩, ac, hc⟩ }, -- the only nontrivial bit is to check that every `a ∈ t` intersects an element `b ∈ u` with -- comparatively large `δ b`. Assume this is not the case, then we will contradict the maximality. refine ⟨u, uT.1, uT.2.1, λ a hat, _⟩, contrapose! hu, have a_disj : ∀ c ∈ u, disjoint (B a) (B c), { assume c hc, by_contra, rw not_disjoint_iff_nonempty_inter at h, obtain ⟨d, du, ad, hd⟩ : ∃ (d : ι) (H : d ∈ u), (B a ∩ B d).nonempty ∧ δ a ≤ τ * δ d := uT.2.2 a hat c hc h, exact lt_irrefl _ ((hu d du ad).trans_le hd) }, -- Let `A` be all the elements of `t` which do not intersect the family `u`. It is nonempty as it -- contains `a`. We will pick an element `a'` of `A` with `δ a'` almost as large as possible. let A := {a' | a' ∈ t ∧ ∀ c ∈ u, disjoint (B a') (B c)}, have Anonempty : A.nonempty := ⟨a, hat, a_disj⟩, let m := Sup (δ '' A), have bddA : bdd_above (δ '' A), { refine ⟨R, λ x xA, _⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact δle a' ha'.1 }, obtain ⟨a', a'A, ha'⟩ : ∃ a' ∈ A, m / τ ≤ δ a', { have : 0 ≤ m := (δnonneg a hat).trans (le_cSup bddA (mem_image_of_mem _ ⟨hat, a_disj⟩)), rcases eq_or_lt_of_le this with mzero|mpos, { refine ⟨a, ⟨hat, a_disj⟩, _⟩, simpa only [← mzero, zero_div] using δnonneg a hat }, { have I : m / τ < m, { rw div_lt_iff (zero_lt_one.trans hτ), conv_lhs { rw ← mul_one m }, exact (mul_lt_mul_left mpos).2 hτ }, rcases exists_lt_of_lt_cSup (nonempty_image_iff.2 Anonempty) I with ⟨x, xA, hx⟩, rcases (mem_image _ _ _).1 xA with ⟨a', ha', rfl⟩, exact ⟨a', ha', hx.le⟩, } }, clear hat hu a_disj a, have a'_ne_u : a' ∉ u := λ H, (hne _ a'A.1).ne_empty (disjoint_self.1 (a'A.2 _ H)), -- we claim that `u ∪ {a'}` still belongs to `T`, contradicting the maximality of `u`. refine ⟨insert a' u, ⟨_, _, _⟩, subset_insert _ _, (ne_insert_of_not_mem _ a'_ne_u).symm⟩, -- check that `u ∪ {a'}` is made of elements of `t`. { rw insert_subset, exact ⟨a'A.1, uT.1⟩ }, -- check that `u ∪ {a'}` is a disjoint family. This follows from the fact that `a'` does not -- intersect `u`. { exact uT.2.1.insert (λ b bu ba', a'A.2 b bu) }, -- check that every element `c` of `t` intersecting `u ∪ {a'}` intersects an element of this -- family with large `δ`. { assume c ct b ba'u hcb, -- if `c` already intersects an element of `u`, then it intersects an element of `u` with -- large `δ` by the assumption on `u`, and there is nothing left to do. by_cases H : ∃ d ∈ u, (B c ∩ B d).nonempty, { rcases H with ⟨d, du, hd⟩, rcases uT.2.2 c ct d du hd with ⟨d', d'u, hd'⟩, exact ⟨d', mem_insert_of_mem _ d'u, hd'⟩ }, -- otherwise, `c` belongs to `A`. The element of `u ∪ {a'}` that it intersects has to be `a'`. -- moreover, `δ c` is smaller than the maximum `m` of `δ` over `A`, which is `≤ δ a' / τ` -- thanks to the good choice of `a'`. This is the desired inequality. { push_neg at H, simp only [← not_disjoint_iff_nonempty_inter, not_not] at H, rcases mem_insert_iff.1 ba'u with rfl|H', { refine ⟨b, mem_insert _ _, hcb, _⟩, calc δ c ≤ m : le_cSup bddA (mem_image_of_mem _ ⟨ct, H⟩) ... = τ * (m / τ) : by { field_simp [(zero_lt_one.trans hτ).ne'], ring } ... ≤ τ * δ b : mul_le_mul_of_nonneg_left ha' (zero_le_one.trans hτ.le) }, { rw ← not_disjoint_iff_nonempty_inter at hcb, exact (hcb (H _ H')).elim } } } end /-- Vitali covering theorem, closed balls version: given a family `t` of closed balls, one can extract a disjoint subfamily `u ⊆ t` so that all balls in `t` are covered by the 5-times dilations of balls in `u`. -/ theorem exists_disjoint_subfamily_covering_enlargment_closed_ball [metric_space α] (t : set ι) (x : ι → α) (r : ι → ℝ) (R : ℝ) (hr : ∀ a ∈ t, r a ≤ R) : ∃ u ⊆ t, u.pairwise_disjoint (λ a, closed_ball (x a) (r a)) ∧ ∀ a ∈ t, ∃ b ∈ u, closed_ball (x a) (r a) ⊆ closed_ball (x b) (5 * r b) := begin rcases eq_empty_or_nonempty t with rfl|tnonempty, { exact ⟨∅, subset.refl _, pairwise_disjoint_empty, by simp⟩ }, by_cases ht : ∀ a ∈ t, r a < 0, { exact ⟨t, subset.rfl, λ a ha b hb hab, by simp only [function.on_fun, closed_ball_eq_empty.2 (ht a ha), empty_disjoint], λ a ha, ⟨a, ha, by simp only [closed_ball_eq_empty.2 (ht a ha), empty_subset]⟩⟩ }, push_neg at ht, let t' := {a ∈ t | 0 ≤ r a}, rcases exists_disjoint_subfamily_covering_enlargment (λ a, closed_ball (x a) (r a)) t' r 2 one_lt_two (λ a ha, ha.2) R (λ a ha, hr a ha.1) (λ a ha, ⟨x a, mem_closed_ball_self ha.2⟩) with ⟨u, ut', u_disj, hu⟩, have A : ∀ a ∈ t', ∃ b ∈ u, closed_ball (x a) (r a) ⊆ closed_ball (x b) (5 * r b), { assume a ha, rcases hu a ha with ⟨b, bu, hb, rb⟩, refine ⟨b, bu, _⟩, have : dist (x a) (x b) ≤ r a + r b := dist_le_add_of_nonempty_closed_ball_inter_closed_ball hb, apply closed_ball_subset_closed_ball', linarith }, refine ⟨u, ut'.trans (λ a ha, ha.1), u_disj, λ a ha, _⟩, rcases le_or_lt 0 (r a) with h'a|h'a, { exact A a ⟨ha, h'a⟩ }, { rcases ht with ⟨b, rb⟩, rcases A b ⟨rb.1, rb.2⟩ with ⟨c, cu, hc⟩, refine ⟨c, cu, by simp only [closed_ball_eq_empty.2 h'a, empty_subset]⟩ }, end /-- The measurable Vitali covering theorem. Assume one is given a family `t` of closed sets with nonempty interior, such that each `a ∈ t` is included in a ball `B (x, r)` and covers a definite proportion of the ball `B (x, 3 r)` for a given measure `μ` (think of the situation where `μ` is a doubling measure and `t` is a family of balls). Consider a (possibly non-measurable) set `s` at which the family is fine, i.e., every point of `s` belongs to arbitrarily small elements of `t`. Then one can extract from `t` a disjoint subfamily that covers almost all `s`. For more flexibility, we give a statement with a parameterized family of sets. -/ theorem exists_disjoint_covering_ae [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (s : set α) (t : set ι) (C : ℝ≥0) (r : ι → ℝ) (c : ι → α) (B : ι → set α) (hB : ∀ a ∈ t, B a ⊆ closed_ball (c a) (r a)) (μB : ∀ a ∈ t, μ (closed_ball (c a) (3 * r a)) ≤ C * μ (B a)) (ht : ∀ a ∈ t, (interior (B a)).nonempty) (h't : ∀ a ∈ t, is_closed (B a)) (hf : ∀ x ∈ s, ∀ (ε > (0 : ℝ)), ∃ a ∈ t, r a ≤ ε ∧ c a = x) : ∃ u ⊆ t, u.countable ∧ u.pairwise_disjoint B ∧ μ (s \ ⋃ a ∈ u, B a) = 0 := begin /- The idea of the proof is the following. Assume for simplicity that `μ` is finite. Applying the abstract Vitali covering theorem with `δ = r` given by `hf`, one obtains a disjoint subfamily `u`, such that any element of `t` intersects an element of `u` with comparable radius. Fix `ε > 0`. Since the elements of `u` have summable measure, one can remove finitely elements `w_1, ..., w_n`. so that the measure of the remaining elements is `< ε`. Consider now a point `z` not in the `w_i`. There is a small ball around `z` not intersecting the `w_i` (as they are closed), an element `a ∈ t` contained in this small ball (as the family `t` is fine at `z`) and an element `b ∈ u` intersecting `a`, with comparable radius (by definition of `u`). Then `z` belongs to the enlargement of `b`. This shows that `s \ (w_1 ∪ ... ∪ w_n)` is contained in `⋃ (b ∈ u \ {w_1, ... w_n}) (enlargement of b)`. The measure of the latter set is bounded by `∑ (b ∈ u \ {w_1, ... w_n}) C * μ b` (by the doubling property of the measure), which is at most `C ε`. Letting `ε` tend to `0` shows that `s` is almost everywhere covered by the family `u`. For the real argument, the measure is only locally finite. Therefore, we implement the same strategy, but locally restricted to balls on which the measure is finite. For this, we do not use the whole family `t`, but a subfamily `t'` supported on small balls (which is possible since the family is assumed to be fine at every point of `s`). -/ -- choose around each `x` a small ball on which the measure is finite have : ∀ x, ∃ R, 0 < R ∧ R ≤ 1 ∧ μ (closed_ball x (20 * R)) < ∞, { assume x, obtain ⟨R, Rpos, μR⟩ : ∃ (R : ℝ) (hR : 0 < R), μ (closed_ball x R) < ∞ := (μ.finite_at_nhds x).exists_mem_basis nhds_basis_closed_ball, refine ⟨min 1 (R/20), _, min_le_left _ _, _⟩, { simp only [true_and, lt_min_iff, zero_lt_one], linarith }, { apply lt_of_le_of_lt (measure_mono _) μR, apply closed_ball_subset_closed_ball, calc 20 * min 1 (R / 20) ≤ 20 * (R/20) : mul_le_mul_of_nonneg_left (min_le_right _ _) (by norm_num) ... = R : by ring } }, choose R hR0 hR1 hRμ, -- we restrict to a subfamily `t'` of `t`, made of elements small enough to ensure that -- they only see a finite part of the measure, and with a doubling property let t' := {a ∈ t | r a ≤ R (c a)}, -- extract a disjoint subfamily `u` of `t'` thanks to the abstract Vitali covering theorem. obtain ⟨u, ut', u_disj, hu⟩ : ∃ u ⊆ t', u.pairwise_disjoint B ∧ ∀ a ∈ t', ∃ b ∈ u, (B a ∩ B b).nonempty ∧ r a ≤ 2 * r b, { have A : ∀ a ∈ t', r a ≤ 1, { assume a ha, apply ha.2.trans (hR1 (c a)), }, have A' : ∀ a ∈ t', (B a).nonempty := λ a hat', set.nonempty.mono interior_subset (ht a hat'.1), refine exists_disjoint_subfamily_covering_enlargment B t' r 2 one_lt_two (λ a ha, _) 1 A A', exact nonempty_closed_ball.1 ((A' a ha).mono (hB a ha.1)) }, have ut : u ⊆ t := λ a hau, (ut' hau).1, -- As the space is second countable, the family is countable since all its sets have nonempty -- interior. have u_count : u.countable := u_disj.countable_of_nonempty_interior (λ a ha, ht a (ut ha)), -- the family `u` will be the desired family refine ⟨u, λ a hat', (ut' hat').1, u_count, u_disj, _⟩, -- it suffices to show that it covers almost all `s` locally around each point `x`. refine null_of_locally_null _ (λ x hx, _), -- let `v` be the subfamily of `u` made of those sets intersecting the small ball `ball x (r x)` let v := {a ∈ u | (B a ∩ ball x (R x)).nonempty }, have vu : v ⊆ u := λ a ha, ha.1, -- they are all contained in a fixed ball of finite measure, thanks to our choice of `t'` obtain ⟨K, μK, hK⟩ : ∃ K, μ (closed_ball x K) < ∞ ∧ ∀ a ∈ u, (B a ∩ ball x (R x)).nonempty → B a ⊆ closed_ball x K, { have Idist_v : ∀ a ∈ v, dist (c a) x ≤ r a + R x, { assume a hav, apply dist_le_add_of_nonempty_closed_ball_inter_closed_ball, refine hav.2.mono _, apply inter_subset_inter _ ball_subset_closed_ball, exact hB a (ut (vu hav)) }, set R0 := Sup (r '' v) with R0_def, have R0_bdd : bdd_above (r '' v), { refine ⟨1, λ r' hr', _⟩, rcases (mem_image _ _ _).1 hr' with ⟨b, hb, rfl⟩, exact le_trans (ut' (vu hb)).2 (hR1 (c b)) }, rcases le_total R0 (R x) with H|H, { refine ⟨20 * R x, hRμ x, λ a au hax, _⟩, refine (hB a (ut au)).trans _, apply closed_ball_subset_closed_ball', have : r a ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨au, hax⟩), linarith [Idist_v a ⟨au, hax⟩, hR0 x] }, { have R0pos : 0 < R0 := (hR0 x).trans_le H, have vnonempty : v.nonempty, { by_contra, rw [nonempty_iff_ne_empty, not_not] at h, simp only [h, real.Sup_empty, image_empty] at R0_def, exact lt_irrefl _ (R0pos.trans_le (le_of_eq R0_def)) }, obtain ⟨a, hav, R0a⟩ : ∃ a ∈ v, R0/2 < r a, { obtain ⟨r', r'mem, hr'⟩ : ∃ r' ∈ r '' v, R0 / 2 < r' := exists_lt_of_lt_cSup (nonempty_image_iff.2 vnonempty) (half_lt_self R0pos), rcases (mem_image _ _ _).1 r'mem with ⟨a, hav, rfl⟩, exact ⟨a, hav, hr'⟩ }, refine ⟨8 * R0, _, _⟩, { apply lt_of_le_of_lt (measure_mono _) (hRμ (c a)), apply closed_ball_subset_closed_ball', rw dist_comm, linarith [Idist_v a hav, (ut' (vu hav)).2] }, { assume b bu hbx, refine (hB b (ut bu)).trans _, apply closed_ball_subset_closed_ball', have : r b ≤ R0 := le_cSup R0_bdd (mem_image_of_mem _ ⟨bu, hbx⟩), linarith [Idist_v b ⟨bu, hbx⟩] } } }, -- we will show that, in `ball x (R x)`, almost all `s` is covered by the family `u`. refine ⟨_ ∩ ball x (R x), inter_mem_nhds_within _ (ball_mem_nhds _ (hR0 _)), nonpos_iff_eq_zero.mp (le_of_forall_le_of_dense (λ ε εpos, _))⟩, -- the elements of `v` are disjoint and all contained in a finite volume ball, hence the sum -- of their measures is finite. have I : ∑' (a : v), μ (B a) < ∞, { calc ∑' (a : v), μ (B a) = μ (⋃ (a ∈ v), B a) : begin rw measure_bUnion (u_count.mono vu) _ (λ a ha, (h't _ (vu.trans ut ha)).measurable_set), exact u_disj.subset vu end ... ≤ μ (closed_ball x K) : measure_mono (Union₂_subset (λ a ha, hK a (vu ha) ha.2)) ... < ∞ : μK }, -- we can obtain a finite subfamily of `v`, such that the measures of the remaining elements -- add up to an arbitrarily small number, say `ε / C`. obtain ⟨w, hw⟩ : ∃ (w : finset ↥v), ∑' (a : {a // a ∉ w}), μ (B a) < ε / C, { have : 0 < ε / C, by simp only [ennreal.div_pos_iff, εpos.ne', ennreal.coe_ne_top, ne.def, not_false_iff, and_self], exact ((tendsto_order.1 (ennreal.tendsto_tsum_compl_at_top_zero I.ne)).2 _ this).exists }, -- main property: the points `z` of `s` which are not covered by `u` are contained in the -- enlargements of the elements not in `w`. have M : (s \ ⋃ a ∈ u, B a) ∩ ball x (R x) ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a), { assume z hz, set k := ⋃ (a : v) (ha : a ∈ w), B a with hk, have k_closed : is_closed k := is_closed_bUnion w.finite_to_set (λ i hi, h't _ (ut (vu i.2))), have z_notmem_k : z ∉ k, { simp only [not_exists, exists_prop, mem_Union, mem_sep_iff, forall_exists_index, set_coe.exists, not_and, exists_and_distrib_right, subtype.coe_mk], assume b hbv h'b h'z, have : z ∈ (s \ ⋃ a ∈ u, B a) ∩ (⋃ a ∈ u, B a) := mem_inter (mem_of_mem_inter_left hz) (mem_bUnion (vu hbv) h'z), simpa only [diff_inter_self] }, -- since the elements of `w` are closed and finitely many, one can find a small ball around `z` -- not intersecting them have : ball x (R x) \ k ∈ 𝓝 z, { apply is_open.mem_nhds (is_open_ball.sdiff k_closed) _, exact (mem_diff _).2 ⟨mem_of_mem_inter_right hz, z_notmem_k⟩ }, obtain ⟨d, dpos, hd⟩ : ∃ (d : ℝ) (dpos : 0 < d), closed_ball z d ⊆ ball x (R x) \ k := nhds_basis_closed_ball.mem_iff.1 this, -- choose an element `a` of the family `t` contained in this small ball obtain ⟨a, hat, ad, rfl⟩ : ∃ a ∈ t, r a ≤ min d (R z) ∧ c a = z, from hf z ((mem_diff _).1 (mem_of_mem_inter_left hz)).1 (min d (R z)) (lt_min dpos (hR0 z)), have ax : B a ⊆ ball x (R x), { refine (hB a hat).trans _, refine subset.trans _ (hd.trans (diff_subset (ball x (R x)) k)), exact closed_ball_subset_closed_ball (ad.trans (min_le_left _ _)), }, -- it intersects an element `b` of `u` with comparable diameter, by definition of `u` obtain ⟨b, bu, ab, bdiam⟩ : ∃ b ∈ u, (B a ∩ B b).nonempty ∧ r a ≤ 2 * r b, from hu a ⟨hat, ad.trans (min_le_right _ _)⟩, have bv : b ∈ v, { refine ⟨bu, ab.mono _⟩, rw inter_comm, exact inter_subset_inter_right _ ax }, let b' : v := ⟨b, bv⟩, -- `b` can not belong to `w`, as the elements of `w` do not intersect `closed_ball z d`, -- contrary to `b` have b'_notmem_w : b' ∉ w, { assume b'w, have b'k : B b' ⊆ k, from @finset.subset_set_bUnion_of_mem _ _ _ (λ (y : v), B y) _ b'w, have : ((ball x (R x) \ k) ∩ k).nonempty, { apply ab.mono (inter_subset_inter _ b'k), refine ((hB _ hat).trans _).trans hd, exact (closed_ball_subset_closed_ball (ad.trans (min_le_left _ _))) }, simpa only [diff_inter_self, not_nonempty_empty] }, let b'' : {a // a ∉ w} := ⟨b', b'_notmem_w⟩, -- since `a` and `b` have comparable diameters, it follows that `z` belongs to the -- enlargement of `b` have zb : c a ∈ closed_ball (c b) (3 * r b), { rcases ab with ⟨e, ⟨ea, eb⟩⟩, have A : dist (c a) e ≤ r a, from mem_closed_ball'.1 (hB a hat ea), have B : dist e (c b) ≤ r b, from mem_closed_ball.1 (hB b (ut bu) eb), simp only [mem_closed_ball], linarith [dist_triangle (c a) e (c b)] }, suffices H : closed_ball (c b'') (3 * r b'') ⊆ ⋃ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a), from H zb, exact subset_Union (λ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a)) b'' }, -- now that we have proved our main inclusion, we can use it to estimate the measure of the points -- in `ball x (r x)` not covered by `u`. haveI : encodable v := (u_count.mono vu).to_encodable, calc μ ((s \ ⋃ a ∈ u, B a) ∩ ball x (R x)) ≤ μ (⋃ (a : {a // a ∉ w}), closed_ball (c a) (3 * r a)) : measure_mono M ... ≤ ∑' (a : {a // a ∉ w}), μ (closed_ball (c a) (3 * r a)) : measure_Union_le _ ... ≤ ∑' (a : {a // a ∉ w}), C * μ (B a) : ennreal.tsum_le_tsum (λ a, μB a (ut (vu a.1.2))) ... = C * ∑' (a : {a // a ∉ w}), μ (B a) : ennreal.tsum_mul_left ... ≤ C * (ε / C) : mul_le_mul_left' hw.le _ ... ≤ ε : ennreal.mul_div_le end /-- Assume that around every point there are arbitrarily small scales at which the measure is doubling. Then the set of closed sets `a` with nonempty interior contained in `closed_ball x r` and covering a fixed proportion `1/C` of the ball `closed_ball x (3 * r)` forms a Vitali family. This is essentially a restatement of the measurable Vitali theorem. -/ protected def vitali_family [metric_space α] [measurable_space α] [opens_measurable_space α] [second_countable_topology α] (μ : measure α) [is_locally_finite_measure μ] (C : ℝ≥0) (h : ∀ x, ∃ᶠ r in 𝓝[>] 0, μ (closed_ball x (3 * r)) ≤ C * μ (closed_ball x r)) : vitali_family μ := { sets_at := λ x, {a | is_closed a ∧ (interior a).nonempty ∧ ∃ r, (a ⊆ closed_ball x r ∧ μ (closed_ball x (3 * r)) ≤ C * μ a)}, measurable_set' := λ x a ha, ha.1.measurable_set, nonempty_interior := λ x a ha, ha.2.1, nontrivial := λ x ε εpos, begin obtain ⟨r, μr, rpos, rε⟩ : ∃ r, μ (closed_ball x (3 * r)) ≤ C * μ (closed_ball x r) ∧ r ∈ Ioc (0 : ℝ) ε := ((h x).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_rfl, εpos⟩)).exists, refine ⟨closed_ball x r, ⟨is_closed_ball, _, ⟨r, subset.rfl, μr⟩⟩, closed_ball_subset_closed_ball rε⟩, exact (nonempty_ball.2 rpos).mono (ball_subset_interior_closed_ball) end, covering := begin assume s f fsubset ffine, let t : set (ℝ × α × set α) := {p | p.2.2 ⊆ closed_ball p.2.1 p.1 ∧ μ (closed_ball p.2.1 (3 * p.1)) ≤ C * μ p.2.2 ∧ (interior p.2.2).nonempty ∧ is_closed p.2.2 ∧ p.2.2 ∈ f p.2.1 ∧ p.2.1 ∈ s}, have A : ∀ x ∈ s, ∀ (ε : ℝ), ε > 0 → (∃ (p : ℝ × α × set α) (Hp : p ∈ t), p.1 ≤ ε ∧ p.2.1 = x), { assume x xs ε εpos, rcases ffine x xs ε εpos with ⟨a, ha, h'a⟩, rcases fsubset x xs ha with ⟨a_closed, a_int, ⟨r, ar, μr⟩⟩, refine ⟨⟨min r ε, x, a⟩, ⟨_, _, a_int, a_closed, ha, xs⟩, min_le_right _ _, rfl⟩, { rcases min_cases r ε with h'|h'; rwa h'.1 }, { apply le_trans (measure_mono (closed_ball_subset_closed_ball _)) μr, exact mul_le_mul_of_nonneg_left (min_le_left _ _) zero_le_three } }, rcases exists_disjoint_covering_ae μ s t C (λ p, p.1) (λ p, p.2.1) (λ p, p.2.2) (λ p hp, hp.1) (λ p hp, hp.2.1) (λ p hp, hp.2.2.1) (λ p hp, hp.2.2.2.1) A with ⟨t', t't, t'_count, t'_disj, μt'⟩, refine ⟨(λ (p : ℝ × α × set α), p.2) '' t', _, _, _, _⟩, { rintros - ⟨q, hq, rfl⟩, exact (t't hq).2.2.2.2.2 }, { rintros p ⟨q, hq, rfl⟩ p' ⟨q', hq', rfl⟩ hqq', exact t'_disj hq hq' (ne_of_apply_ne _ hqq') }, { rintros - ⟨q, hq, rfl⟩, exact (t't hq).2.2.2.2.1 }, { convert μt' using 3, rw bUnion_image } end } end vitali
476845af1cce530f00a3b2a24dc8d832d6e5c8a7
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Init/Control/Option.lean
38a58762fe5df1aeff8b362ac612426ac2f38c16
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,880
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Data.Option.Basic import Init.Control.Basic import Init.Control.Except universes u v instance {α} : ToBool (Option α) := ⟨Option.toBool⟩ def OptionT (m : Type u → Type v) (α : Type u) : Type v := m (Option α) @[inline] def OptionT.run {m : Type u → Type v} {α : Type u} (x : OptionT m α) : m (Option α) := x namespace OptionT variables {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def bind (x : OptionT m α) (f : α → OptionT m β) : OptionT m β := id (α := m (Option β)) do match (← x) with | some a => f a | none => pure none @[inline] protected def pure (a : α) : OptionT m α := id (α := m (Option α)) do pure (some a) instance : Monad (OptionT m) := { pure := OptionT.pure bind := OptionT.bind } @[inline] protected def orElse (x : OptionT m α) (y : OptionT m α) : OptionT m α := id (α := m (Option α)) do match (← x) with | some a => pure (some a) | _ => y @[inline] protected def fail : OptionT m α := id (α := m (Option α)) do pure none instance : Alternative (OptionT m) := { failure := OptionT.fail orElse := OptionT.orElse } @[inline] protected def lift (x : m α) : OptionT m α := id (α := m (Option α)) do return some (← x) instance : MonadLift m (OptionT m) := ⟨OptionT.lift⟩ instance : MonadFunctor m (OptionT m) := ⟨fun f x => f x⟩ @[inline] protected def tryCatch (x : OptionT m α) (handle : Unit → OptionT m α) : OptionT m α := id (α := m (Option α)) do let some a ← x | handle () pure a instance : MonadExceptOf Unit (OptionT m) := { throw := fun _ => OptionT.fail tryCatch := OptionT.tryCatch } end OptionT
60a9982835035fad7dd8f4e8ec96e6e506b37964
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Elab/Tactic/Basic.lean
2fdd00d44b8498bcd8e051061c1b9bdfab9d2065
[ "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
14,282
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectMVars import Lean.Parser.Command import Lean.Meta.PPGoal import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Contradiction import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Subst import Lean.Elab.Util import Lean.Elab.Term import Lean.Elab.Binders namespace Lean.Elab open Meta /- Assign `mvarId := sorry` -/ def admitGoal (mvarId : MVarId) : MetaM Unit := withMVarContext mvarId do let mvarType ← inferType (mkMVar mvarId) assignExprMVar mvarId (← mkSorry mvarType (synthetic := true)) def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) m!"\n\n" def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := withPPInaccessibleNames do logError <| MessageData.tagged `Tactic.unsolvedGoals <| m!"unsolved goals\n{goalsToMessageData goals}" goals.forM fun mvarId => admitGoal mvarId namespace Tactic structure Context where main : MVarId -- declaration name of the executing elaborator, used by `mkTacticInfo` to persist it in the info tree elaborator : Name structure State where goals : List MVarId deriving Inhabited structure SavedState where term : Term.SavedState tactic : State abbrev TacticM := ReaderT Context $ StateRefT State TermElabM abbrev Tactic := Syntax → TacticM Unit -- 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`. instance : Monad TacticM := { inferInstanceAs (Monad TacticM) with } def getGoals : TacticM (List MVarId) := return (← get).goals def setGoals (mvarIds : List MVarId) : TacticM Unit := modify fun s => { s with goals := mvarIds } def pruneSolvedGoals : TacticM Unit := do let gs ← getGoals let gs ← gs.filterM fun g => not <$> isExprMVarAssigned g setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals getGoals @[inline] private def TacticM.runCore (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx |>.run s @[inline] private def TacticM.runCore' (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.runCore ctx s def run (mvarId : MVarId) (x : TacticM Unit) : TermElabM (List MVarId) := withMVarContext mvarId do let savedSyntheticMVars := (← get).syntheticMVars modify fun s => { s with syntheticMVars := [] } let aux : TacticM (List MVarId) := /- Important: the following `try` does not backtrack the state. This is intentional because we don't want to backtrack the error messages when we catch the "abort internal exception" We must define `run` here because we define `MonadExcept` instance for `TacticM` -/ try x; getUnsolvedGoals catch ex => if isAbortTacticException ex then getUnsolvedGoals else throw ex try aux.runCore' { main := mvarId, elaborator := Name.anonymous } { goals := [mvarId] } finally modify fun s => { s with syntheticMVars := savedSyntheticMVars } protected def saveState : TacticM SavedState := return { term := (← Term.saveState), tactic := (← get) } def SavedState.restore (b : SavedState) : TacticM Unit := do b.term.restore set b.tactic protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Term.Context).currMacroScope protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[builtinInit mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic def mkTacticInfo (mctxBefore : MetavarContext) (goalsBefore : List MVarId) (stx : Syntax) : TacticM Info := return Info.ofTacticInfo { elaborator := (← read).elaborator mctxBefore := mctxBefore goalsBefore := goalsBefore stx := stx mctxAfter := (← getMCtx) goalsAfter := (← getUnsolvedGoals) } def mkInitialTacticInfo (stx : Syntax) : TacticM (TacticM Info) := do let mctxBefore ← getMCtx let goalsBefore ← getUnsolvedGoals return mkTacticInfo mctxBefore goalsBefore stx @[inline] def withTacticInfoContext (stx : Syntax) (x : TacticM α) : TacticM α := do withInfoContext x (← mkInitialTacticInfo stx) /- Important: we must define `evalTacticUsing` and `expandTacticMacroFns` before we define the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages, and this is bad when rethrowing the exception at the `catch` block in these methods. We marked these places with a `(*)` in these methods. -/ private def evalTacticUsing (s : SavedState) (stx : Syntax) (tactics : List (KeyedDeclsAttribute.AttributeEntry Tactic)) : TacticM Unit := do let rec loop | [] => throwErrorAt stx "unexpected syntax {indentD stx}" | evalFn::evalFns => do try withReader ({ · with elaborator := evalFn.decl }) <| withTacticInfoContext stx <| evalFn.value stx catch | ex@(Exception.error _ _) => match evalFns with | [] => throw ex -- (*) | evalFns => s.restore; loop evalFns | ex@(Exception.internal id _) => if id == unsupportedSyntaxExceptionId then s.restore; loop evalFns else throw ex loop tactics mutual partial def expandTacticMacroFns (stx : Syntax) (macros : List (KeyedDeclsAttribute.AttributeEntry Macro)) : TacticM Unit := let rec loop | [] => throwErrorAt stx "tactic '{stx.getKind}' has not been implemented" | m::ms => do let scp ← getCurrMacroScope try withReader ({ · with elaborator := m.decl }) do withTacticInfoContext stx do let stx' ← adaptMacro m.value stx evalTactic stx' catch ex => if ms.isEmpty then throw ex -- (*) loop ms loop macros partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do expandTacticMacroFns stx (macroAttribute.getEntries (← getEnv) stx.getKind) partial def evalTacticAux (stx : Syntax) : TacticM Unit := withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]` stx.getArgs.forM evalTactic else do trace[Elab.step] "{stx}" let s ← Tactic.saveState match tacticElabAttribute.getEntries (← getEnv) stx.getKind with | [] => expandTacticMacro stx | evalFns => evalTacticUsing s stx evalFns | _ => throwError m!"unexpected tactic{indentD stx}" partial def evalTactic (stx : Syntax) : TacticM Unit := evalTacticAux stx end def throwNoGoalsToBeSolved : TacticM α := throwError "no goals to be solved" def done : TacticM Unit := do let gs ← getUnsolvedGoals unless gs.isEmpty do Term.reportUnsolvedGoals gs throwAbortTactic def focus (x : TacticM α) : TacticM α := do let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved setGoals [mvarId] let a ← x let mvarIds' ← getUnsolvedGoals setGoals (mvarIds' ++ mvarIds) pure a def focusAndDone (tactic : TacticM α) : TacticM α := focus do let a ← tactic done pure a /- Close the main goal using the given tactic. If it fails, log the error and `admit` -/ def closeUsingOrAdmit (tac : TacticM Unit) : TacticM Unit := do /- Important: we must define `closeUsingOrAdmit` before we define the instance `MonadExcept` for `TacticM` since it backtracks the state including error messages. -/ let mvarId :: mvarIds ← getUnsolvedGoals | throwNoGoalsToBeSolved try focusAndDone tac catch ex => logException ex admitGoal mvarId setGoals mvarIds instance : MonadBacktrack SavedState TacticM where saveState := Tactic.saveState restoreState b := b.restore @[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do let b ← saveState try x catch ex => b.restore; h ex instance : MonadExcept Exception TacticM where throw := throw tryCatch := Tactic.tryCatch @[inline] protected def orElse {α} (x y : TacticM α) : TacticM α := do try x catch _ => y instance {α} : OrElse (TacticM α) where orElse := Tactic.orElse /- Save the current tactic state for a token `stx`. This method is a no-op if `stx` has no position information. We use this method to save the tactic state at punctuation such as `;` -/ def saveTacticInfoForToken (stx : Syntax) : TacticM Unit := do unless stx.getPos?.isNone do withTacticInfoContext stx (pure ()) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := withMacroExpansionInfo beforeStx afterStx do withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' $ evalTactic stx' def appendGoals (mvarIds : List MVarId) : TacticM Unit := modify fun s => { s with goals := s.goals ++ mvarIds } def replaceMainGoal (mvarIds : List MVarId) : TacticM Unit := do let (mvarId :: mvarIds') ← getGoals | throwNoGoalsToBeSolved modify fun s => { s with goals := mvarIds ++ mvarIds' } /-- Return the first goal. -/ def getMainGoal : TacticM MVarId := do loop (← getGoals) where loop : List MVarId → TacticM MVarId | [] => throwNoGoalsToBeSolved | mvarId :: mvarIds => do if (← isExprMVarAssigned mvarId) then loop mvarIds else setGoals (mvarId :: mvarIds) return mvarId /-- Return the main goal metavariable declaration. -/ def getMainDecl : TacticM MetavarDecl := do getMVarDecl (← getMainGoal) /-- Return the main goal tag. -/ def getMainTag : TacticM Name := return (← getMainDecl).userName /-- Return expected type for the main goal. -/ def getMainTarget : TacticM Expr := do instantiateMVars (← getMainDecl).type /-- Execute `x` using the main goal local context and instances -/ def withMainContext (x : TacticM α) : TacticM α := do withMVarContext (← getMainGoal) x /-- Evaluate `tac` at `mvarId`, and return the list of resulting subgoals. -/ def evalTacticAt (tac : Syntax) (mvarId : MVarId) : TacticM (List MVarId) := do let gs ← getGoals try setGoals [mvarId] evalTactic tac pruneSolvedGoals getGoals finally setGoals gs def ensureHasNoMVars (e : Expr) : TacticM Unit := do let e ← instantiateMVars e let pendingMVars ← getMVars e discard <| Term.logUnassignedUsingErrorInfos pendingMVars if e.hasExprMVar then throwError "tactic failed, resulting expression contains metavariables{indentExpr e}" /-- Close main goal using the given expression. If `checkUnassigned == true`, then `val` must not contain unassinged metavariables. -/ def closeMainGoal (val : Expr) (checkUnassigned := true): TacticM Unit := do if checkUnassigned then ensureHasNoMVars val assignExprMVar (← getMainGoal) val replaceMainGoal [] @[inline] def liftMetaMAtMain (x : MVarId → MetaM α) : TacticM α := do withMainContext do x (← getMainGoal) @[inline] def liftMetaTacticAux (tac : MVarId → MetaM (α × List MVarId)) : TacticM α := do withMainContext do let (a, mvarIds) ← tac (← getMainGoal) replaceMainGoal mvarIds pure a @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux fun mvarId => do let gs ← tactic mvarId pure ((), gs) def tryTactic? (tactic : TacticM α) : TacticM (Option α) := do try pure (some (← tactic)) catch _ => pure none def tryTactic (tactic : TacticM α) : TacticM Bool := do try discard tactic pure true catch _ => pure false /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new untagged goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do let mctx ← getMCtx let mut numAnonymous := 0 for g in newGoals do if mctx.isAnonymousMVar g then numAnonymous := numAnonymous + 1 modifyMCtx fun mctx => do let mut mctx := mctx let mut idx := 1 for g in newGoals do if mctx.isAnonymousMVar g then if numAnonymous == 1 then mctx := mctx.renameMVar g parentTag else mctx := mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx) idx := idx + 1 pure mctx /- Recall that `ident' := ident <|> Term.hole` -/ def getNameOfIdent' (id : Syntax) : Name := if id.isIdent then id.getId else `_ def getFVarId (id : Syntax) : TacticM FVarId := withRef id do let fvar? ← Term.isLocalIdent? id; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError "unknown variable '{id.getId}'" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainContext do ids.mapM getFVarId /-- Use position of `=> $body` for error messages. If there is a line break before `body`, the message will be displayed on `=>` only, but the "full range" for the info view will still include `body`. -/ def withCaseRef [Monad m] [MonadRef m] (arrow body : Syntax) (x : m α) : m α := withRef (mkNullNode #[arrow, body]) x builtin_initialize registerTraceClass `Elab.tactic end Lean.Elab.Tactic
89bbe180d075771fc8f74a93392244ba2575cfa3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/category/Module/monoidal.lean
a06c3f94f2527f36b9122f91ad70e8396d86b56f
[ "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
7,518
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Scott Morrison -/ import category_theory.monoidal.braided import algebra.category.Module.basic import linear_algebra.tensor_product /-! # The symmetric monoidal category structure on R-modules Mostly this uses existing machinery in `linear_algebra.tensor_product`. We just need to provide a few small missing pieces to build the `monoidal_category` instance and then the `symmetric_category` instance. If you're happy using the bundled `Module R`, it may be possible to mostly use this as an interface and not need to interact much with the implementation details. -/ universes u open category_theory namespace Module variables {R : Type u} [comm_ring R] namespace monoidal_category -- The definitions inside this namespace are essentially private. -- After we build the `monoidal_category (Module R)` instance, -- you should use that API. open_locale tensor_product /-- (implementation) tensor product of R-modules -/ def tensor_obj (M N : Module R) : Module R := Module.of R (M ⊗[R] N) /-- (implementation) tensor product of morphisms R-modules -/ def tensor_hom {M N M' N' : Module R} (f : M ⟶ N) (g : M' ⟶ N') : tensor_obj M M' ⟶ tensor_obj N N' := tensor_product.map f g lemma tensor_id (M N : Module R) : tensor_hom (𝟙 M) (𝟙 N) = 𝟙 (Module.of R (↥M ⊗ ↥N)) := by tidy lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom f₁ f₂ ≫ tensor_hom g₁ g₂ := by tidy /-- (implementation) the associator for R-modules -/ def associator (M N K : Module R) : tensor_obj (tensor_obj M N) K ≅ tensor_obj M (tensor_obj N K) := linear_equiv.to_Module_iso (tensor_product.assoc R M N K) lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom (tensor_hom f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ tensor_hom f₁ (tensor_hom f₂ f₃) := begin apply tensor_product.ext_threefold, intros x y z, refl end lemma pentagon (W X Y Z : Module R) : tensor_hom (associator W X Y).hom (𝟙 Z) ≫ (associator W (tensor_obj X Y) Z).hom ≫ tensor_hom (𝟙 W) (associator X Y Z).hom = (associator (tensor_obj W X) Y Z).hom ≫ (associator W X (tensor_obj Y Z)).hom := begin apply tensor_product.ext_fourfold, intros w x y z, refl end /-- (implementation) the left unitor for R-modules -/ def left_unitor (M : Module.{u} R) : Module.of R (R ⊗[R] M) ≅ M := (linear_equiv.to_Module_iso (tensor_product.lid R M) : of R (R ⊗ M) ≅ of R M).trans (of_self_iso M) lemma left_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom (𝟙 (Module.of R R)) f ≫ (left_unitor N).hom = (left_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.lid_tmul, tensor_product.lid_tmul], rw linear_map.map_smul, refl, end /-- (implementation) the right unitor for R-modules -/ def right_unitor (M : Module.{u} R) : Module.of R (M ⊗[R] R) ≅ M := (linear_equiv.to_Module_iso (tensor_product.rid R M) : of R (M ⊗ R) ≅ of R M).trans (of_self_iso M) lemma right_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom f (𝟙 (Module.of R R)) ≫ (right_unitor N).hom = (right_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.rid_tmul, tensor_product.rid_tmul], rw linear_map.map_smul, refl, end lemma triangle (M N : Module.{u} R) : (associator M (Module.of R R) N).hom ≫ tensor_hom (𝟙 M) (left_unitor N).hom = tensor_hom (right_unitor M).hom (𝟙 N) := begin apply tensor_product.ext_threefold, intros x y z, change R at y, dsimp [tensor_hom, associator], erw [tensor_product.lid_tmul, tensor_product.rid_tmul], apply (tensor_product.smul_tmul _ _ _).symm end end monoidal_category open monoidal_category instance Module.monoidal_category : monoidal_category (Module.{u} R) := { -- data tensor_obj := tensor_obj, tensor_hom := @tensor_hom _ _, tensor_unit := Module.of R R, associator := associator, left_unitor := left_unitor, right_unitor := right_unitor, -- properties tensor_id' := λ M N, tensor_id M N, tensor_comp' := λ M N K M' N' K' f g h, tensor_comp f g h, associator_naturality' := λ M N K M' N' K' f g h, associator_naturality f g h, left_unitor_naturality' := λ M N f, left_unitor_naturality f, right_unitor_naturality' := λ M N f, right_unitor_naturality f, pentagon' := λ M N K L, pentagon M N K L, triangle' := λ M N, triangle M N, } /-- Remind ourselves that the monoidal unit, being just `R`, is still a commutative ring. -/ instance : comm_ring ((𝟙_ (Module.{u} R) : Module.{u} R) : Type u) := (by apply_instance : comm_ring R) namespace monoidal_category @[simp] lemma hom_apply {K L M N : Module.{u} R} (f : K ⟶ L) (g : M ⟶ N) (k : K) (m : M) : (f ⊗ g) (k ⊗ₜ m) = f k ⊗ₜ g m := rfl @[simp] lemma left_unitor_hom_apply {M : Module.{u} R} (r : R) (m : M) : ((λ_ M).hom : 𝟙_ (Module R) ⊗ M ⟶ M) (r ⊗ₜ[R] m) = r • m := tensor_product.lid_tmul m r @[simp] lemma right_unitor_hom_apply {M : Module.{u} R} (m : M) (r : R) : ((ρ_ M).hom : M ⊗ 𝟙_ (Module R) ⟶ M) (m ⊗ₜ r) = r • m := tensor_product.rid_tmul m r @[simp] lemma associator_hom_apply {M N K : Module.{u} R} (m : M) (n : N) (k : K) : ((α_ M N K).hom : (M ⊗ N) ⊗ K ⟶ M ⊗ (N ⊗ K)) ((m ⊗ₜ n) ⊗ₜ k) = (m ⊗ₜ (n ⊗ₜ k)) := rfl end monoidal_category /-- (implementation) the braiding for R-modules -/ def braiding (M N : Module R) : tensor_obj M N ≅ tensor_obj N M := linear_equiv.to_Module_iso (tensor_product.comm R M N) @[simp] lemma braiding_naturality {X₁ X₂ Y₁ Y₂ : Module.{u} R} (f : X₁ ⟶ Y₁) (g : X₂ ⟶ Y₂) : (f ⊗ g) ≫ (Y₁.braiding Y₂).hom = (X₁.braiding X₂).hom ≫ (g ⊗ f) := begin apply tensor_product.ext, intros x y, refl end @[simp] lemma hexagon_forward (X Y Z : Module.{u} R) : (α_ X Y Z).hom ≫ (braiding X _).hom ≫ (α_ Y Z X).hom = ((braiding X Y).hom ⊗ 𝟙 Z) ≫ (α_ Y X Z).hom ≫ (𝟙 Y ⊗ (braiding X Z).hom) := begin apply tensor_product.ext_threefold, intros x y z, refl, end @[simp] lemma hexagon_reverse (X Y Z : Module.{u} R) : (α_ X Y Z).inv ≫ (braiding _ Z).hom ≫ (α_ Z X Y).inv = (𝟙 X ⊗ (Y.braiding Z).hom) ≫ (α_ X Z Y).inv ≫ ((X.braiding Z).hom ⊗ 𝟙 Y) := begin apply (cancel_epi (α_ X Y Z).hom).1, apply tensor_product.ext_threefold, intros x y z, refl, end /-- The symmetric monoidal structure on `Module R`. -/ instance Module.symmetric_category : symmetric_category (Module.{u} R) := { braiding := braiding, braiding_naturality' := λ X₁ X₂ Y₁ Y₂ f g, braiding_naturality f g, hexagon_forward' := hexagon_forward, hexagon_reverse' := hexagon_reverse, } namespace monoidal_category @[simp] lemma braiding_hom_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).hom : M ⊗ N ⟶ N ⊗ M) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] lemma braiding_inv_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).inv : N ⊗ M ⟶ M ⊗ N) (n ⊗ₜ m) = m ⊗ₜ n := rfl end monoidal_category end Module
d1a56ffccee7bc88cf4ba7e09347d56a9130466a
74d9d5f45c6ce5c4f2faf215c04a68eab55fe525
/src/differentiability/normed_space.lean
dfd0ff276b3329153f7293e56d7174b41be18171
[]
no_license
joshpoll/differential_geometry
290bb8a934ca3b3b6b707d810e6d4b941710b710
57e00a7e37b7c4c73c847429171ff63d3a48def5
refs/heads/master
1,584,551,626,391
1,527,747,643,000
1,527,747,643,000
135,014,993
1
0
null
null
null
null
UTF-8
Lean
false
false
14,803
lean
-- Inspired by Patrick Massot -- This approach differs from that of Patrick's by using continuity instead of boundedness. As with Caratheodory, this hides norms and epsilon-deltas as much as possible. -- Boundedness and continuity for linear operators are equivalent on the most common spaces of study, but may diverge on other spaces. -- continuity also provides more general proofs than norm arguments. -- admittedly, with the more powerful norm_num, the gap between the two approaches is smaller. I still believe continuous is the right way forward. It still replicates less work than boundedness -- TODO: Lean still doesn't have pointwise continuity(!). We want that to make proofs more general. It's pretty simple to do. -- TODO: continuous at 0/arbitrary point => continuous everywhere -- see http://matrixeditions.com/FA.Chap3.1-4.pdf (among others) -- TODO: copy module.lean and linear_map_module.lean import algebra.field import tactic.norm_num import analysis.topology.continuity import .norm import order.complete_lattice open lattice noncomputable theory local attribute [instance] classical.prop_decidable local notation f `→_{`:50 a `}`:0 b := filter.tendsto f (nhds a) (nhds b) universes u v w x variables {k : Type u} variables {E : Type v} variables {F : Type w} variables {G : Type x} structure is_continuous_linear_map' {k : Type u} {E : Type v} {F : Type w} [normed_field k] [normed_space k E] [normed_space k F] (L : E → F) extends is_linear_map L : Prop := (continuous : continuous L) -- def is_continuous_linear_map' (L : E → F) := (is_linear_map L) ∧ (continuous L) -- ways to combine is_continuous_linear_map' proofs namespace is_continuous_linear_map' variables [normed_field k] [normed_space k E] [normed_space k F] [normed_space k G] variable {L : E → F} include k lemma zero : is_continuous_linear_map' (λ (x:E), (0:F)) := ⟨is_linear_map.map_zero, continuous_const⟩ lemma id : is_continuous_linear_map' (id : E → E) := ⟨is_linear_map.id, continuous_id⟩ -- Remark: smul and add should follow immediately from the fact that normed vectors spaces are topological vector spaces -- this seems harder than its bounded counterpart (which is admittedly nontrivial) lemma smul (c : k) (H : is_continuous_linear_map' L) : is_continuous_linear_map' (λ e, c•L e) := sorry lemma neg (H : is_continuous_linear_map' L) : is_continuous_linear_map' (λ e, -L e) := begin rcases H with ⟨lin, cont⟩, split, { exact is_linear_map.map_neg lin }, { exact continuous_neg cont } end lemma add {L : E → F} {M : E → F} (HL : is_continuous_linear_map' L) (HM : is_continuous_linear_map' M) : is_continuous_linear_map' (λ e, L e + M e) := begin rcases HL with ⟨lin_L, cont_L⟩, rcases HM with ⟨lin_M , cont_M⟩, split, { exact is_linear_map.map_add lin_L lin_M }, { exact continuous_add cont_L cont_M } end lemma sub {L : E → F} {M : E → F} (HL : is_continuous_linear_map' L) (HM : is_continuous_linear_map' M) : is_continuous_linear_map' (λ e, L e - M e) := add HL (neg HM) lemma comp {L : E → F} {M : F → G} (HL : is_continuous_linear_map' L) (HM : is_continuous_linear_map' M) : is_continuous_linear_map' (M ∘ L) := begin rcases HL with ⟨lin_L, cont_L⟩, rcases HM with ⟨lin_M, cont_M⟩, split, { exact is_linear_map.comp lin_M lin_L }, { exact continuous.comp cont_L cont_M } end end is_continuous_linear_map' -- some holdover code about bounded linear maps. it will eventually be useful, but not currently used, because is_continuous_linear_map' is better structure is_bounded_linear_map {k : Type u} {E : Type v} {F : Type w} [normed_field k] [normed_space k E] [normed_space k F] (L : E → F) extends is_linear_map L : Prop := (bounded : ∃ M > 0, ∀ x : E, ∥L x∥ ≤ M * ∥x∥) namespace is_bounded_linear_map variables [normed_field k] [normed_space k E] [normed_space k F] [normed_space k G] include k lemma continuous {L : E → F} (H : is_bounded_linear_map L) : continuous L := begin rcases H with ⟨lin, M, Mpos, ineq⟩, apply continuous_iff_tendsto.2, intro x, apply tendsto_iff_norm_tendsto_zero.2, replace ineq := λ e, calc ∥L e - L x∥ = ∥L (e - x)∥ : by rw [←(lin.sub e x)] ... ≤ M*∥e-x∥ : ineq (e-x), have lim1 : (λ (x:E), M) →_{x} M := tendsto_const_nhds, have lim2 : (λ e, e-x) →_{x} 0 := begin have limId := continuous_iff_tendsto.1 continuous_id x, have limx : (λ (e : E), -x) →_{x} -x := tendsto_const_nhds, have := tendsto_add limId limx, simp at this, simpa using this, end, replace lim2 := filter.tendsto.comp lim2 lim_norm_zero, apply squeeze_zero, { simp[norm_nonneg] }, { exact ineq }, { simpa using tendsto_mul lim1 lim2 } end -- not sure why this fails now lemma lim_zero_bounded_linear_map {L : E → F} (H : is_bounded_linear_map L) : (L →_{0} 0) := by simpa [H.left.zero] using continuous_iff_tendsto.1 H.continuous 0 end is_bounded_linear_map -- Next lemma is stated for real normed space but it would work as soon as the base field is an extension of ℝ lemma bounded_continuous_linear_map {E : Type*} [normed_space ℝ E] {F : Type*} [normed_space ℝ F] {L : E → F} (h : is_continuous_linear_map' L) : is_bounded_linear_map L := begin rcases h with ⟨lin, cont⟩, split, assumption, replace cont := continuous_of_metric.1 cont 1 (by norm_num), swap, exact 0, rw[lin.zero] at cont, rcases cont with ⟨δ, δ_pos, H⟩, revert H, repeat { conv in (_ < _ ) { rw norm_dist } }, intro H, existsi (δ/2)⁻¹, have half_δ_pos := half_pos δ_pos, split, exact (inv_pos half_δ_pos), intro x, by_cases h : x = 0, { simp [h, lin.zero] }, -- case x = 0 { -- case x ≠ 0 have norm_x_pos : ∥x∥ > 0 := norm_pos_iff.2 h, have norm_x : ∥x∥ ≠ 0 := mt norm_zero_iff_zero.1 h, let p := ∥x∥*(δ/2)⁻¹, have p_pos : p > 0 := mul_pos norm_x_pos (inv_pos $ half_δ_pos), have p0 := ne_of_gt p_pos, let q := (δ/2)*∥x∥⁻¹, have q_pos : q > 0 := div_pos half_δ_pos norm_x_pos, have q0 := ne_of_gt q_pos, have triv := calc p*q = ∥x∥*((δ/2)⁻¹*(δ/2))*∥x∥⁻¹ : by simp[mul_assoc] ... = 1 : by simp [(inv_mul_cancel $ ne_of_gt half_δ_pos), mul_inv_cancel norm_x], have norm_calc := calc ∥q•x∥ = abs(q)*∥x∥ : by {rw norm_smul, refl} ... = q*∥x∥ : by rw [abs_of_nonneg $ le_of_lt q_pos] ... = δ/2 : by simp [mul_assoc, inv_mul_cancel norm_x] ... < δ : half_lt_self δ_pos, exact calc ∥L x∥ = ∥L (1•x)∥: by simp ... = ∥L ((p*q)•x) ∥ : by {rw [←triv] } ... = ∥L (p•q•x) ∥ : by rw mul_smul ... = ∥p•L (q•x) ∥ : by rw lin.smul ... = abs(p)*∥L (q•x) ∥ : by { rw norm_smul, refl} ... = p*∥L (q•x) ∥ : by rw [abs_of_nonneg $ le_of_lt $ p_pos] ... ≤ p*1 : le_of_lt $ mul_lt_mul_of_pos_left (H norm_calc) p_pos ... = p : by simp ... = (δ/2)⁻¹*∥x∥ : by simp[mul_comm] } end /- Continuous Linear Maps -/ -- the following approach is based off that of poly in number_theory/dioph.lean, which also packages together functions with their proofs -- for now, k is implicit def clm {k : Type*} (E : Type*) (F : Type*) [normed_field k] [normed_space k E] [normed_space k F] := { L : E → F // is_continuous_linear_map' L } -- TODO: I think clm should be a structure/class (what's the difference?) that extends linear_map (which isn't a structure/class...) and continuous (which also isn't a structure/class). perhaps it should just be coercible instead namespace clm variables [normed_field k] [normed_space k E] [normed_space k F] [normed_space k G] include k -- TODO: how to get multiplication notation? -- we can treat a clm as a function instance : has_coe_to_fun (clm E F) := ⟨_, λ L, L.1⟩ -- treat clm application as "multiplication" and give it the right space -- Need it to be tupled so continuity makes sense naturally (could also use the approach in topological_structures.lean) -- TODO: this feels really bad. The notation is always exposed. Need to find a better way def clm_app_pair (p : (clm E F) × E) := p.1 p.2 local notation L `⬝`:70 v := clm_app_pair ⟨L, v⟩ @[simp] theorem clm_app_pair_eval (L : clm E F) (v) : (L⬝v) = L v := rfl -- proof data -- isc is short for is_clm def isc (L : clm E F) : is_continuous_linear_map' L := L.2 -- functional extensionality def ext {L M : clm E F} (e : ∀ v, L⬝v = M⬝v) : L = M := subtype.eq (funext e) -- construct isc given function that is extensionally equal def subst (L : clm E F) (M : E → F) (e : ∀ v, L⬝v = M v) : clm E F := -- TODO: I don't know how the proof part works ⟨M, by rw ← (funext e : coe_fn L = M); exact L.isc⟩ -- TODO: this rewrite rule doesn't typecheck!! (it was taken directly from poly unless I messed that up) -- @[simp] theorem subst_eval (L M e v) : subst L M e v = M v := rfl -- composition -- TODO: this should probably be an instance def clm_comp : clm E F → clm F G → clm E G := λ L M, ⟨λ v, M (L v), is_continuous_linear_map'.comp L.2 M.2⟩ local notation M `∘` L := clm_comp L M -- each of the identities and operations comes with an instance that tells Lean what it is and a simplification lemma that gives Lean a hint about how to "evaluate" it -- zero map def zero : clm E F := ⟨λ v, 0, is_continuous_linear_map'.zero⟩ instance : has_zero (clm E F) := ⟨clm.zero⟩ @[simp] theorem zero_eval (v) : (0 : clm E F)⬝v = 0 := rfl -- identity map -- TODO: not sure if this is necessary or even desirable def one : clm E E := ⟨λ v, v, is_continuous_linear_map'.id⟩ instance : has_one (clm E E) := ⟨clm.one⟩ @[simp] theorem one_eval (v) : (1 : clm E E)⬝v = v := rfl def add : clm E F → clm E F → clm E F := λ L M, ⟨L + M, is_continuous_linear_map'.add L.isc M.isc⟩ instance : has_add (clm E F) := ⟨clm.add⟩ @[simp] theorem add_eval : Π (L M : clm E F) v, (L + M)⬝v = L⬝v + M⬝v | ⟨L, pL⟩ ⟨M, pM⟩ v := rfl def neg : clm E F → clm E F := λ L, ⟨λ v, -(L⬝v), is_continuous_linear_map'.neg L.isc⟩ instance : has_neg (clm E F) := ⟨clm.neg⟩ def sub : clm E F → clm E F → clm E F := λ L M, L + (-M) instance : has_sub (clm E F) := ⟨clm.sub⟩ @[simp] theorem sub_eval : Π (L M : clm E F) v, (L - M)⬝v = L⬝v - M⬝v | ⟨L, pL⟩ ⟨M, pM⟩ v := rfl -- TODO: this proof doesn't work even though it does for poly -- possibly b/c neg and sub are defined differently? -- TODO: this feels weird being disconnected from neg @[simp] theorem neg_eval (L : clm E F) (v) : (-L)⬝v = -(L⬝v) := sorry -- show (0 - L) v = _, by simp def smul : k → clm E F → clm E F := λ c L, ⟨λ v, c•(L⬝v), is_continuous_linear_map'.smul c L.isc⟩ instance : has_scalar k (clm E F) := ⟨clm.smul⟩ -- TODO: prove it @[simp] theorem smul_eval : Π c (L : clm E F) v, (c•L)⬝v = c•(L⬝v) := sorry -- need these instances up here to prove stuff about the op norm -- TODO: go straight to module? instance : add_comm_group (clm E F) := by refine { add := (+), zero := 0, neg := has_neg.neg, .. }; { intros; exact ext (λ v, by simp) } -- TODO: use refine instance : module k (clm E F) := { smul := (•), smul_add := by intros; exact ext (λ v, by simp [smul_add]), add_smul := by intros; exact ext (λ v, by simp [add_smul]), mul_smul := by intros; exact ext (λ v, by simp [mul_smul]), one_smul := by intros; exact ext (λ v, by simp [one_smul]), } /- Operator Norm -/ -- TODO: this might be better in a different section, but we'll keep it here for now -- TODO: leverage boundedness proof above to show that Inf has a value -- TODO: big ops should make this easier to define (I think) def op_norm : clm E F → ℝ := λ L, Inf { M : ℝ | M ≥ 0 ∧ ∀ v : E, ∥L⬝v∥ ≤ M * ∥v∥ } -- TODO: implement has_norm -- instance : has_norm (clm E F) := ⟨clm.op_norm⟩ -- an alternate version that allows for easier proofs theorem op_norm_alt : ∀ L : clm E F, op_norm L = Sup { c : ℝ | ∃ v, ∥v∥ ≤ 1 ∧ ∥L⬝v∥ = c } := sorry theorem op_norm_inhabited {L : clm E F} : (0:ℝ) ∈ { c : ℝ | ∃ v, ∥v∥ ≤ 1 ∧ ∥L⬝v∥ = c } := begin existsi (0:E), split, simp [zero_le_one], apply norm_zero_iff_zero.2, -- follows from L being a linear map end -- TODO: uglier than it should be theorem op_norm_nonneg {L : clm E F} : op_norm L ≥ 0 := begin unfold op_norm ge, apply real.lb_le_Inf, -- bounded { simp, have : is_bounded_linear_map L, begin -- TODO: I think what's going wrong here is I should have a companion proof that clms and blms are isomorphic -- exact bounded_continuous_linear_map L.isc, admit end, rcases this with ⟨linear, M, M_pos, M_bound⟩, existsi _, split, apply le_of_lt, assumption, assumption }, { intro, simp, intros, assumption } end theorem op_norm_zero_iff_zero {L : clm E F} : op_norm L = 0 ↔ L = 0 := begin split, { rw [op_norm_alt], admit }, admit end theorem op_norm_pos_homo : ∀ c (L : clm E F), op_norm (c•L) = ∥c∥ * op_norm L := sorry theorem op_norm_triangle : ∀ (L M : clm E F), op_norm (L + M) ≤ op_norm L + op_norm M := begin intros, simp [op_norm_alt], admit end -- TODO: is there a way to get the auto-induced metric from a norm without doing any work? Don't do this for now def op_dist : clm E F → clm E F → ℝ := λ L M, op_norm (L - M) theorem op_dist_self : ∀ x : clm E F, op_dist x x = 0 := begin intros, unfold op_dist, apply op_norm_zero_iff_zero.2, simp [add_left_neg] end theorem op_dist_eq_of_dist_eq_zero : ∀ (x y : clm E F), op_dist x y = 0 → x = y := begin unfold op_dist, intros x y h, apply sub_eq_zero.1, apply op_norm_zero_iff_zero.1, assumption end -- TODO: clm is an instance of normed_space theorem op_dist_comm : ∀ (x y : clm E F), op_dist x y = op_dist y x := begin intros, simp [op_dist, op_norm], congr, funext, admit, -- the propositions are the same by the pos_homo for the underlying norm end theorem op_dist_triangle : ∀ (x y z : clm E F), op_dist x z ≤ op_dist x y + op_dist y z := begin intros, unfold op_dist, calc op_norm (x - z) = op_norm ((x - y) + (y - z)) : by simp ... ≤ op_norm (x - y) + op_norm (y - z) : by apply op_norm_triangle end /- Continuous Linear Maps form a normed vector space. -/ -- This is crucial for differentiation. -- TODO: solve instance : metric_space (clm E F) := { dist := op_dist, dist_self := op_dist_self, eq_of_dist_eq_zero := op_dist_eq_of_dist_eq_zero, dist_comm := op_dist_comm, dist_triangle := op_dist_triangle } instance : normed_space k (clm E F) := { norm := op_norm, dist_eq := by intros; refl, norm_smul := op_norm_pos_homo } end clm
2c71e73bae039d8967926b48382f74d2bdb6839b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/unique_factorization_domain.lean
c121ebee4c9cbaa194834af9ae1ff5b2c672a377
[ "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
56,594
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Aaron Anderson -/ import algebra.gcd_monoid.basic import ring_theory.integral_domain import ring_theory.noetherian /-! # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop := (well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _)) export wf_dvd_monoid (well_founded_dvd_not_unit) @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring.wf_dvd_monoid [comm_ring α] [is_domain α] [is_noetherian_ring α] : wf_dvd_monoid α := ⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _), ext, exact ideal.span_singleton_lt_span_singleton.symm }⟩ namespace wf_dvd_monoid variables [comm_monoid_with_zero α] open associates nat theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α := ⟨begin haveI := h, refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ variables [wf_dvd_monoid α] instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) := ⟨begin refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) := subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit local attribute [elab_as_eliminator] well_founded.fix lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_rfl⟩) (well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, hi.2.trans (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a := wf_dvd_monoid.induction_on_irreducible a (λ h, (h rfl).elim) (λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i ::ₘ s, ⟨by clear _let_match; finish, by { rw multiset.prod_cons, exact hs.2.mul_left _ }⟩⟩) end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates [comm_cancel_monoid_with_zero α] (h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α := wf_dvd_monoid.of_wf_dvd_monoid_associates ⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩ theorem wf_dvd_monoid.iff_well_founded_associates [comm_cancel_monoid_with_zero α] : wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) := ⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- unique factorization monoids. These are defined as `comm_cancel_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_exists_unique_irreducible_factors` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factors` -/ class unique_factorization_monoid (α : Type*) [comm_cancel_monoid_with_zero α] extends wf_dvd_monoid α : Prop := (irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a) /-- Can't be an instance because it would cause a loop `ufm → wf_dvd_monoid → ufm → ...`. -/ lemma ufm_of_gcd_of_wf_dvd_monoid [comm_cancel_monoid_with_zero α] [wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α := { irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime .. ‹wf_dvd_monoid α› } instance associates.ufm [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] : unique_factorization_monoid (associates α) := { irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff, apply unique_factorization_monoid.irreducible_iff_prime, } .. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) } end prio namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α] theorem exists_prime_factors (a : α) : a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a := by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime, apply wf_dvd_monoid.exists_factors a } @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := begin simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃, exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃, end lemma factors_unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit (is_unit_iff_dvd_one.2 ((multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_monoid lemma prime_factors_unique [comm_cancel_monoid_with_zero α] : ∀ {f g : multiset α}, (∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem $ λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit $ is_unit_iff_dvd_one.2 $ (multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this)) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (hf p (by simp)) (λ q hq, hg _ hq) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::ₘ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)), end) /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ lemma prime_factors_irreducible [comm_cancel_monoid_with_zero α] {a : α} {f : multiset α} (ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) : ∃ p, a ~ᵤ p ∧ f = {p} := begin haveI := classical.dec_eq α, refine multiset.induction_on f (λ h, (ha.not_unit (associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1, rintros p s _ ⟨u, hu⟩ hs, use p, have hs0 : s = 0, { by_contra hs0, obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0, apply (hs q (by simp [hq])).2.1, refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _, { rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu, mul_comm, mul_comm p _, mul_assoc], simp, }, apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _), apply (hs p (multiset.mem_cons_self _ _)).2.1 }, simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *, exact ⟨associated.symm ⟨u, hu⟩, rfl⟩, end section exists_prime_factors variables [comm_cancel_monoid_with_zero α] variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) include pf lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α := ⟨begin classical, apply rel_hom.well_founded (rel_hom.mk _ _) (with_top.well_founded_lt nat.lt_wf), { intro a, by_cases h : a = 0, { exact ⊤ }, exact (classical.some (pf a h)).card }, rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩, rw dif_neg ane0, by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] }, rw [dif_neg h, with_top.coe_lt_coe], have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] }, calc multiset.card (classical.some (pf a ane0)) < _ + multiset.card (classical.some (pf c cne0)) : lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _))) ... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) : (multiset.card_add _ _).symm ... = multiset.card (classical.some (pf b h)) : multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _), { convert (classical.some_spec (pf c cne0)).2.symm, rw [con, multiset.prod_zero] }, { intros x hadd, rw multiset.mem_add at hadd, cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd }, { rw multiset.prod_add, transitivity a * c, { apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 }, { rw ← b_eq, apply (classical.some_spec (pf _ _)).2.symm, } } end⟩ lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p := begin by_cases hp0 : p = 0, { simp [hp0] }, refine ⟨λ h, _, prime.irreducible⟩, obtain ⟨f, hf⟩ := pf p hp0, obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf, rw hq.prime_iff, exact hf.1 q (multiset.mem_singleton_self _) end theorem unique_factorization_monoid.of_exists_prime_factors : unique_factorization_monoid α := { irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf, .. wf_dvd_monoid.of_exists_prime_factors pf } end exists_prime_factors theorem unique_factorization_monoid.iff_exists_prime_factors [comm_cancel_monoid_with_zero α] : unique_factorization_monoid α ↔ (∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) := ⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h, unique_factorization_monoid.of_exists_prime_factors⟩ theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) (p : α) : irreducible p ↔ prime p := ⟨by letI := classical.dec_eq α; exact λ hpi, ⟨hpi.ne_zero, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0, have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0, begin cases eif x hx0 with fx hfx, cases eif a ha0 with fa hfa, cases eif b hb0 with fb hfb, have h : multiset.rel associated (p ::ₘ fx) (fa + fb), { apply uif, { exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), }, { exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), }, calc multiset.prod (p ::ₘ fx) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact hfx.2.mul_left _ ... ~ᵤ (fa).prod * (fb).prod : hfa.2.symm.mul_mul hfb.2.symm ... = _ : by rw multiset.prod_add, }, exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ hq.dvd_iff_dvd_left.2 $ hfa.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ hq.dvd_iff_dvd_left.2 $ hfb.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqb)) end⟩, prime.irreducible⟩ theorem unique_factorization_monoid.of_exists_unique_irreducible_factors [comm_cancel_monoid_with_zero α] (eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a) (uif : ∀ (f g : multiset α), (∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) : unique_factorization_monoid α := unique_factorization_monoid.of_exists_prime_factors (by { convert eif, simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif }) namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [decidable_eq α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else classical.some (unique_factorization_monoid.exists_prime_factors a h) theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a := begin rw [factors, dif_neg ane0], exact (classical.some_spec (exists_prime_factors a ane0)).2 end theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x := begin rw [factors], split_ifs with ane0, { simp only [multiset.not_mem_zero, forall_false_left, forall_const] }, intros x hx, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx, end theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x := λ x h, (prime_of_factor x h).irreducible lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ factors b) (factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _)) irreducible_of_factor (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ factors b) : by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) end unique_factorization_monoid namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero α] [decidable_eq α] [normalization_monoid α] variables [unique_factorization_monoid α] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def normalized_factors (a : α) : multiset α := multiset.map normalize $ factors a theorem normalized_factors_prod {a : α} (ane0 : a ≠ 0) : associated (normalized_factors a).prod a := begin rw [normalized_factors, factors, dif_neg ane0], refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2, rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk, multiset.map_map], congr' 2, ext, rw [function.comp_apply, associates.mk_normalize], end theorem prime_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → prime x := begin rw [normalized_factors, factors], split_ifs with ane0, { simp }, intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩, rw (normalize_associated _).prime_iff, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy, end theorem irreducible_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → irreducible x := λ x h, (prime_of_normalized_factor x h).irreducible theorem normalize_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → normalize x = x := begin rw [normalized_factors, factors], split_ifs with h, { simp }, intros x hx, obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx, apply normalize_idem end lemma normalized_factors_irreducible {a : α} (ha : irreducible a) : normalized_factors a = {normalize a} := begin obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha ⟨prime_of_normalized_factor, normalized_factors_prod ha.ne_zero⟩, have p_mem : p ∈ normalized_factors a, { rw hp, exact multiset.mem_singleton_self _ }, convert hp, rwa [← normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated] end lemma exists_mem_normalized_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ normalized_factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p ::ₘ normalized_factors b) (normalized_factors a), from factors_unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_normalized_factor _)) irreducible_of_normalized_factor (associated.symm $ calc multiset.prod (normalized_factors a) ~ᵤ a : normalized_factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p ::ₘ normalized_factors b) : by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) @[simp] lemma normalized_factors_zero : normalized_factors (0 : α) = 0 := by simp [normalized_factors, factors] @[simp] lemma normalized_factors_one : normalized_factors (1 : α) = 0 := begin nontriviality α using [normalized_factors, factors], rw ← multiset.rel_zero_right, apply factors_unique irreducible_of_normalized_factor, { intros x hx, exfalso, apply multiset.not_mem_zero x hx }, { simp [normalized_factors_prod (@one_ne_zero α _ _)] }, apply_instance end @[simp] lemma normalized_factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : normalized_factors (x * y) = normalized_factors x + normalized_factors y := begin have h : (normalize : α → α) = associates.out ∘ associates.mk, { ext, rw [function.comp_apply, associates.out_mk], }, rw [← multiset.map_id' (normalized_factors (x * y)), ← multiset.map_id' (normalized_factors x), ← multiset.map_id' (normalized_factors y), ← multiset.map_congr normalize_normalized_factor, ← multiset.map_congr normalize_normalized_factor, ← multiset.map_congr normalize_normalized_factor, ← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm, ← multiset.map_map associates.out], refine congr rfl _, apply multiset.map_mk_eq_map_mk_of_rel, apply factors_unique, { intros x hx, rcases multiset.mem_add.1 hx with hx | hx; exact irreducible_of_normalized_factor x hx }, { exact irreducible_of_normalized_factor }, { rw multiset.prod_add, exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans (normalized_factors_prod (mul_ne_zero hx hy)).symm } end @[simp] lemma normalized_factors_pow {x : α} (n : ℕ) : normalized_factors (x ^ n) = n • normalized_factors x := begin induction n with n ih, { simp }, by_cases h0 : x = 0, { simp [h0, zero_pow n.succ_pos, smul_zero] }, rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih], end lemma dvd_iff_normalized_factors_le_normalized_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) : x ∣ y ↔ normalized_factors x ≤ normalized_factors y := begin split, { rintro ⟨c, rfl⟩, simp [hx, right_ne_zero_of_mul hy] }, { rw [← (normalized_factors_prod hx).dvd_iff_dvd_left, ← (normalized_factors_prod hy).dvd_iff_dvd_right], apply multiset.prod_dvd_prod } end lemma zero_not_mem_normalized_factors (x : α) : (0 : α) ∉ normalized_factors x := λ h, prime.ne_zero (prime_of_normalized_factor _ h) rfl lemma dvd_of_mem_normalized_factors {a p : α} (H : p ∈ normalized_factors a) : p ∣ a := begin by_cases hcases : a = 0, { rw hcases, exact dvd_zero p }, { exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) }, end end unique_factorization_monoid namespace unique_factorization_monoid open_locale classical open multiset associates noncomputable theory variables [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] /-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/ protected def normalization_monoid : normalization_monoid α := normalization_monoid_of_monoid_hom_right_inverse { to_fun := λ a : associates α, if a = 0 then 0 else ((normalized_factors a).map (classical.some mk_surjective.has_right_inverse : associates α → α)).prod, map_one' := by simp, map_mul' := λ x y, by { by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, simp [hx, hy] } } begin intro x, dsimp, by_cases hx : x = 0, { simp [hx] }, have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) = (id : associates α → associates α), { ext x, rw [function.comp_apply, mk_monoid_hom_apply, classical.some_spec mk_surjective.has_right_inverse x], refl }, rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id, ← associated_iff_eq], apply normalized_factors_prod hx end instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩ end unique_factorization_monoid namespace unique_factorization_monoid variables {R : Type*} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R] lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0) (h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d := λ d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (λ x hx _ _, hx) (λ d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) : (∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (λ h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0) (no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors /-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b, ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) : ∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩ section multiplicity variables [nontrivial R] [normalization_monoid R] [decidable_eq R] variables [decidable_rel (has_dvd.dvd : R → R → Prop)] open multiplicity multiset lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : ℕ} (ha : irreducible a) (hb : b ≠ 0) : ↑n ≤ multiplicity a b ↔ repeat (normalize a) n ≤ normalized_factors b := begin rw ← pow_dvd_iff_le_multiplicity, revert b, induction n with n ih, { simp }, intros b hb, split, { rintro ⟨c, rfl⟩, rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb, rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ, normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, ← ih hb.2], apply dvd.intro _ rfl }, { rw [multiset.le_iff_exists_add], rintro ⟨u, hu⟩, rw [← (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat], exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) } end lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b ≠ 0) : multiplicity a b = (normalized_factors b).count (normalize a) := begin apply le_antisymm, { apply enat.le_of_lt_add_one, rw [← nat.cast_one, ← nat.cast_add, lt_iff_not_ge, ge_iff_le, le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], simp }, rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], end end multiplicity end unique_factorization_monoid namespace associates open unique_factorization_monoid associated multiset variables [comm_cancel_monoid_with_zero α] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `normalized_factors` are only unique up to associated elements, while the multisets in `factor_set α` are unique by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [comm_cancel_monoid_with_zero α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑(a + b) : factor_set α) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h theorem factor_set.prod_eq_zero_iff [nontrivial α] (p : factor_set α) : p.prod = 0 ↔ p = ⊤ := begin induction p using with_top.rec_top_coe, { simp only [iff_self, eq_self_iff_true, associates.prod_top] }, simp only [prod_coe, with_top.coe_ne_top, iff_false, prod_eq_zero_iff, multiset.mem_map], rintro ⟨⟨a, ha⟩, -, eq⟩, rw [subtype.coe_mk] at eq, exact ha.ne_zero eq, end /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) : factor_set α → ℕ | none := 0 | (some s) := s.count p variables [dec_irr : Π (p : associates α), decidable (irreducible p)] include dec_irr /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count [decidable_eq (associates α)] (p : associates α) : factor_set α → ℕ := if hp : irreducible p then bcount ⟨p, hp⟩ else 0 @[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) (s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:= by { dunfold count, split_ifs, refl } @[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) : count p (0 : factor_set α) = 0 := by { dunfold count, split_ifs, refl } lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) : count p = 0 := dif_neg hp omit dec_irr /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop | _ ⊤ := true | p (some l) := p ∈ l include dec_irr /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set α`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem (p : associates α) (s : factor_set α) : Prop := if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩ @[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) : factor_set_mem p s = (p ∈ s) := rfl lemma mem_factor_set_top {p : associates α} {hp : irreducible p} : p ∈ (⊤ : factor_set α) := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial end lemma mem_factor_set_some {p : associates α} {hp : irreducible p} {l : multiset {a : associates α // irreducible a }} : p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl end lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p) (s : factor_set α) : ¬ p ∈ s := λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false), by rwa [dif_neg hp] at h omit dec_irr variable [unique_factorization_monoid α] theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _), { exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end theorem factor_set.unique [nontrivial α] {p q : factor_set α} (h : p.prod = q.prod) : p = q := begin induction p using with_top.rec_top_coe; induction q using with_top.rec_top_coe, { refl }, { rw [eq_comm, ←factor_set.prod_eq_zero_iff, ←h, associates.prod_top] }, { rw [←factor_set.prod_eq_zero_iff, h, associates.prod_top] }, { congr' 1, rw ←multiset.map_eq_map subtype.coe_injective, apply unique' _ _ h; { intros a ha, obtain ⟨⟨a', irred⟩, -, rfl⟩ := multiset.mem_map.mp ha, rwa [subtype.coe_mk] } }, end theorem prod_le_prod_iff_le [nontrivial α] {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin classical, rintros ⟨c, eqc⟩, refine multiset.le_iff_exists_add.2 ⟨factors c, unique' hq (λ x hx, _) _⟩, { obtain h|h := multiset.mem_add.1 hx, { exact hp x h }, { exact irreducible_of_factor _ h } }, { rw [eqc, multiset.prod_add], congr, refine associated_iff_eq.mp (factors_prod (λ hc, _)).symm, refine not_irreducible_zero (hq _ _), rw [←prod_eq_zero_iff, eqc, hc, mul_zero] } end prod_le_prod variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)] include dec /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors' (a : α) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩) (irreducible_of_factor) @[simp] theorem map_subtype_coe_factors' {a : α} : (factors' a).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (h : a ~ᵤ b) : factors' a = factors' b := begin obtain rfl|hb := eq_or_ne b 0, { rw associated_zero_iff_eq_zero at h, rw h }, have ha : a ≠ 0, { contrapose! hb with ha, rw [←associated_zero_iff_eq_zero, ←ha], exact h.symm }, rw [←multiset.map_eq_map subtype.coe_injective, map_subtype_coe_factors', map_subtype_coe_factors', ←rel_associated_iff_map_eq_map], exact factors_unique irreducible_of_factor irreducible_of_factor ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), end include dec' /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a := by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) } @[simp] theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem prod_factors [nontrivial α] (s : factor_set α) : s.prod.factors = s := factor_set.unique $ factors_prod _ theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec dec' theorem eq_of_prod_eq_prod [nontrivial α] {a b : factor_set α} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec dec' @[simp] theorem factors_mul [nontrivial α] (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono [nontrivial α] : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le [nontrivial α] {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono omit dec dec' theorem prod_le [nontrivial α] {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec dec' noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ noncomputable instance [nontrivial α] : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.order_top, .. associates.order_bot } lemma sup_mul_inf [nontrivial α] (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end include dec_irr lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := begin by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p }, obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0, rw [← associates.factors_prod a], rw [← ha', factors_mk a0 nza] at hm ⊢, erw prod_coe, apply multiset.dvd_prod, apply multiset.mem_map.mpr, exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩ end omit dec' lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0} (h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a := by { haveI := classical.dec_eq (associates α), apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp, rw factors_mk _ hz, apply mem_factor_set_some.2 h_mem } omit dec_irr lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a := begin obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd, apply multiset.mem_pmap.mpr, use q, use hq, exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq)) end include dec_irr lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 }, { apply mem_factors'_of_dvd ha0 } end include dec' lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) : (associates.mk p) ∈ factors (associates.mk a) := begin rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd) end lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : (associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp }, { apply mem_factors_of_dvd ha0 hp } end lemma exists_prime_dvd_of_not_inf_one {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) : ∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b := begin have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0, { contrapose! h with hf, change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1, rw hf, exact multiset.prod_zero }, rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz, obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz), rw multiset.inf_eq_inter at p0_mem, obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0, refine ⟨p, _, _, _⟩, { rw [← irreducible_iff_prime, ← irreducible_mk], exact p0_irr }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left, apply ha, }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right, apply hb } end theorem coprime_iff_inf_one [nontrivial α] {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) : (associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d := begin split, { intros hg p ha hb hp, refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _), rw ← hg, exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) }, { contrapose, intros hg hc, obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg, exact hc hpa hpb hp } end omit dec_irr theorem factors_prime_pow [nontrivial α] {p : associates α} (hp : irreducible p) (k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) := eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat, multiset.prod_repeat, subtype.coe_mk]) include dec_irr theorem prime_pow_dvd_iff_le [nontrivial α] {m p : associates α} (h₁ : m ≠ 0) (h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors := begin obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁, rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le, ← factors_le, factors_prime_pow h₂, factors_mk _ nz], exact with_top.coe_le_coe end theorem le_of_count_ne_zero [nontrivial α] {m p : associates α} (h0 : m ≠ 0) (hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m := begin rw [← pos_iff_ne_zero], intro h, rw [← pow_one p], apply (prime_pow_dvd_iff_le h0 hp).2, simpa only end theorem count_mul [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) : count p (factors (a * b)) = count p a.factors + count p b.factors := begin obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha, obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb, rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add, ← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp, multiset.count_add, count_some hp, count_some hp] end theorem count_of_coprime [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) : count p a.factors = 0 ∨ count p b.factors = 0 := begin rw [or_iff_not_imp_left, ← ne.def], intro hca, contrapose! hab with hcb, exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb, (irreducible_iff_prime.mp hp)⟩, end theorem count_mul_of_coprime [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors := begin cases count_of_coprime ha hb hab hp with hz hb0, { tauto }, apply or.intro_right, rw [count_mul ha hb hp, hb0, add_zero] end theorem count_mul_of_coprime' [nontrivial α] {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) : count p (a * b).factors = count p a.factors ∨ count p (a * b).factors = count p b.factors := begin rw [count_mul ha hb hp], cases count_of_coprime ha hb hab hp with ha0 hb0, { apply or.intro_right, rw [ha0, zero_add] }, { apply or.intro_left, rw [hb0, add_zero] } end theorem dvd_count_of_dvd_count_mul [nontrivial α] {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0) {p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors := begin cases count_of_coprime ha hb hab hp with hz h, { rw hz, exact dvd_zero k }, { rw [count_mul ha hb hp, h] at habk, exact habk } end omit dec_irr @[simp] lemma factors_one [nontrivial α] : factors (1 : associates α) = 0 := begin apply eq_of_prod_eq_prod, rw associates.factors_prod, exact multiset.prod_zero, end @[simp] theorem pow_factors [nontrivial α] {a : associates α} {k : ℕ} : (a ^ k).factors = k • a.factors := begin induction k with n h, { rw [zero_nsmul, pow_zero], exact factors_one }, { rw [pow_succ, succ_nsmul, factors_mul, h] } end include dec_irr lemma count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : count p (a ^ k).factors = k * count p a.factors := begin induction k with n h, { rw [pow_zero, factors_one, zero_mul, count_zero hp] }, { rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring } end theorem dvd_count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p) (k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right } theorem is_pow_of_dvd_count [nontrivial α] {a : associates α} (ha : a ≠ 0) {k : ℕ} (hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) : ∃ (b : associates α), a = b ^ k := begin obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha, rw [factors_mk a0 hz] at hk, have hk' : ∀ p, p ∈ (factors' a0) → k ∣ (factors' a0).count p, { rintros p -, have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] }, rw [pp, ← count_some p.2], exact hk p.val p.2 }, obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk', use (u : factor_set α).prod, apply eq_of_factors_eq_factors, rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu], exact with_bot.coe_nsmul u k end omit dec omit dec_irr omit dec' theorem eq_pow_of_mul_eq_pow [nontrivial α] {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : associates α), a = d ^ k := begin classical, by_cases hk0 : k = 0, { use 1, rw [hk0, pow_zero] at h ⊢, apply (mul_eq_one_iff.1 h).1 }, { refine is_pow_of_dvd_count ha _, intros p hp, apply dvd_count_of_dvd_count_mul ha hb hp hab, rw h, apply dvd_count_pow _ hp, rintros rfl, rw zero_pow' _ hk0 at h, cases mul_eq_zero.mp h; contradiction } end end associates section open associates unique_factorization_monoid lemma associates.quot_out {α : Type*} [comm_monoid α] (a : associates α): associates.mk (quot.out (a)) = a := by rw [←quot_mk_eq_mk, quot.out_eq] /-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α := { gcd := λa b, quot.out (associates.mk a ⊓ associates.mk b : associates α), lcm := λa b, quot.out (associates.mk a ⊔ associates.mk b : associates α), gcd_dvd_left := λ a b, by { rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le], exact inf_le_left }, gcd_dvd_right := λ a b, by { rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le], exact inf_le_right }, dvd_gcd := λ a b c hac hab, by { rw [←mk_dvd_mk, (associates.mk c ⊓ associates.mk b).quot_out, dvd_eq_le, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff], exact ⟨hac, hab⟩ }, lcm_zero_left := λ a, by { have : associates.mk (0 : α) = ⊤ := rfl, rw [this, top_sup_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, lcm_zero_right := λ a, by { have : associates.mk (0 : α) = ⊤ := rfl, rw [this, sup_top_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, gcd_mul_lcm := λ a b, by { rw [←mk_eq_mk_iff_associated, ←associates.mk_mul_mk, ←associated_iff_eq, associates.quot_out, associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } } /-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α] [normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : normalized_gcd_monoid α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, by { rw [← out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk], exact normalize_associated (a * b) }, normalize_gcd := assume a b, by convert normalize_out _, normalize_lcm := assume a b, by convert normalize_out _, .. ‹normalization_monoid α› } end namespace unique_factorization_monoid /-- If `y` is a nonzero element of a unique factorization monoid with finitely many units (e.g. `ℤ`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/ noncomputable def fintype_subtype_dvd {M : Type*} [comm_cancel_monoid_with_zero M] [unique_factorization_monoid M] [fintype (units M)] (y : M) (hy : y ≠ 0) : fintype {x // x ∣ y} := begin haveI : nontrivial M := ⟨⟨y, 0, hy⟩⟩, haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid, haveI := classical.dec_eq M, haveI := classical.dec_eq (associates M), -- We'll show `λ (u : units M) (f ⊆ factors y) → u * Π f` is injective -- and has image exactly the divisors of `y`. refine fintype.of_finset (((normalized_factors y).powerset.to_finset.product (finset.univ : finset (units M))).image (λ s, (s.snd : M) * s.fst.prod)) (λ x, _), simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true, multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map], split, { rintros ⟨s, hs, rfl⟩, have prod_s_ne : s.fst.prod ≠ 0, { intro hz, apply hy (eq_zero_of_zero_dvd _), have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz, rw ← (normalized_factors_prod hy).dvd_iff_dvd_right, exact multiset.dvd_prod (multiset.mem_of_le hs hz) }, show (s.snd : M) * s.fst.prod ∣ y, rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul, ← (normalized_factors_prod hy).dvd_iff_dvd_right], exact multiset.prod_dvd_prod hs }, { rintro (h : x ∣ y), have hx : x ≠ 0, { refine mt (λ hx, _) hy, rwa [hx, zero_dvd_iff] at h }, obtain ⟨u, hu⟩ := normalized_factors_prod hx, refine ⟨⟨normalized_factors x, u⟩, _, (mul_comm _ _).trans hu⟩, exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h } end end unique_factorization_monoid
3a51d2328119ba7cb3782123c94d0d65fb3d86e0
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/override/geomOverride.lean
77224eacd113d042535a90216b5fdb1f7c73bea1
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
3,249
lean
import ..imperative_DSL.environment import ..eval.geometryEval open lang.euclideanGeometry3 def assignGeometry3Space : environment.env → lang.euclideanGeometry3.spaceVar → lang.euclideanGeometry3.spaceExpr → environment.env | i v e := { g:={sp := (λ r, if (spaceVarEq v r) then (euclideanGeometry3Eval e i) else (i.g.sp r)), ..i.g}, ..i } def assignGeometry3Frame : environment.env → lang.euclideanGeometry3.frameVar → lang.euclideanGeometry3.frameExpr → environment.env | i v e := { g:={fr := (λ r, if (frameVarEq v r) then (euclideanGeometry3FrameEval e i) else (i.g.fr r)), ..i.g}, ..i } def assignGeometry3Transform : environment.env → lang.euclideanGeometry3.TransformVar → lang.euclideanGeometry3.TransformExpr → environment.env | i v e := { g:={tr := (λ r, if (transformVarEq v r) then (euclideanGeometry3TransformEval e i) else (i.g.tr r)), ..i.g}, ..i } def assignGeometry3Vector : environment.env → lang.euclideanGeometry3.CoordinateVectorVar → lang.euclideanGeometry3.CoordinateVectorExpr → environment.env | i v e := { g:={vec := (λ r, if (vectorVarEq v r) then (euclideanGeometry3CoordinateVectorEval e i) else (i.g.vec r)), ..i.g}, ..i } def assignGeometry3Point : environment.env → lang.euclideanGeometry3.CoordinatePointVar → lang.euclideanGeometry3.CoordinatePointExpr → environment.env | i v e := { g:={pt := (λ r, if (pointVarEq v r) then (euclideanGeometry3CoordinatePointEval e i) else (i.g.pt r)), ..i.g}, ..i } def assignGeometry3Scalar : environment.env → lang.euclideanGeometry3.ScalarVar → lang.euclideanGeometry3.ScalarExpr → environment.env | i v e := { g:={s := (λ r, if (scalarVarEq v r) then (euclideanGeometry3ScalarEval e i) else (i.g.s r)), ..i.g}, ..i } def assignGeometry3Angle : environment.env → lang.euclideanGeometry3.AngleVar → lang.euclideanGeometry3.AngleExpr → environment.env | i v e := { g:={a := (λ r, if (angleVarEq v r) then (euclideanGeometry3AngleEval e i) else (i.g.a r)), ..i.g}, ..i } def assignGeometry3Orientation : environment.env → lang.euclideanGeometry3.OrientationVar → lang.euclideanGeometry3.OrientationExpr → environment.env | i v e := { g:={or := (λ r, if (orientationVarEq v r) then (euclideanGeometry3OrientationEval e i) else (i.g.or r)), ..i.g}, ..i } def assignGeometry3Rotation : environment.env → lang.euclideanGeometry3.RotationVar → lang.euclideanGeometry3.RotationExpr → environment.env | i v e := { g:={r := (λ r, if (rotationVarEq v r) then (euclideanGeometry3RotationEval e i) else (i.g.r r)), ..i.g}, ..i }
6472b54804539ecb9558fece8f4447fc3cb3635e
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Ring.lean
514f6e8f182e5107c0b30253e79edcfc93d2561f
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
14,667
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Ring structure Ring (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) (zero : A) (lunit_zero : (∀ {x : A} , (plus zero x) = x)) (runit_zero : (∀ {x : A} , (plus x zero) = x)) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) (commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z)))) (rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x)))) (neg : (A → A)) (leftInverse_inv_op_zero : (∀ {x : A} , (plus x (neg x)) = zero)) (rightInverse_inv_op_zero : (∀ {x : A} , (plus (neg x) x) = zero)) (one : A) (lunit_one : (∀ {x : A} , (times one x) = x)) (runit_one : (∀ {x : A} , (times x one) = x)) (leftZero_op_zero : (∀ {x : A} , (times zero x) = zero)) (rightZero_op_zero : (∀ {x : A} , (times x zero) = zero)) open Ring structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) (zeroS : AS) (negS : (AS → AS)) (oneS : AS) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (zeroP : (Prod A A)) (negP : ((Prod A A) → (Prod A A))) (oneP : (Prod A A)) (lunit_0P : (∀ {xP : (Prod A A)} , (plusP zeroP xP) = xP)) (runit_0P : (∀ {xP : (Prod A A)} , (plusP xP zeroP) = xP)) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) (commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP))) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP)))) (rightDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP (plusP yP zP) xP) = (plusP (timesP yP xP) (timesP zP xP)))) (leftInverse_inv_op_0P : (∀ {xP : (Prod A A)} , (plusP xP (negP xP)) = zeroP)) (rightInverse_inv_op_0P : (∀ {xP : (Prod A A)} , (plusP (negP xP) xP) = zeroP)) (lunit_1P : (∀ {xP : (Prod A A)} , (timesP oneP xP) = xP)) (runit_1P : (∀ {xP : (Prod A A)} , (timesP xP oneP) = xP)) (leftZero_op_0P : (∀ {xP : (Prod A A)} , (timesP zeroP xP) = zeroP)) (rightZero_op_0P : (∀ {xP : (Prod A A)} , (timesP xP zeroP) = zeroP)) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (Ring A1)) (Ri2 : (Ring A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Ri1) x1 x2)) = ((times Ri2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ri1) x1 x2)) = ((plus Ri2) (hom x1) (hom x2)))) (pres_zero : (hom (zero Ri1)) = (zero Ri2)) (pres_neg : (∀ {x1 : A1} , (hom ((neg Ri1) x1)) = ((neg Ri2) (hom x1)))) (pres_one : (hom (one Ri1)) = (one Ri2)) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (Ring A1)) (Ri2 : (Ring A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Ri1) x1 x2) ((times Ri2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ri1) x1 x2) ((plus Ri2) y1 y2)))))) (interp_zero : (interp (zero Ri1) (zero Ri2))) (interp_neg : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((neg Ri1) x1) ((neg Ri2) y1))))) (interp_one : (interp (one Ri1) (one Ri2))) inductive RingTerm : Type | timesL : (RingTerm → (RingTerm → RingTerm)) | plusL : (RingTerm → (RingTerm → RingTerm)) | zeroL : RingTerm | negL : (RingTerm → RingTerm) | oneL : RingTerm open RingTerm inductive ClRingTerm (A : Type) : Type | sing : (A → ClRingTerm) | timesCl : (ClRingTerm → (ClRingTerm → ClRingTerm)) | plusCl : (ClRingTerm → (ClRingTerm → ClRingTerm)) | zeroCl : ClRingTerm | negCl : (ClRingTerm → ClRingTerm) | oneCl : ClRingTerm open ClRingTerm inductive OpRingTerm (n : ℕ) : Type | v : ((fin n) → OpRingTerm) | timesOL : (OpRingTerm → (OpRingTerm → OpRingTerm)) | plusOL : (OpRingTerm → (OpRingTerm → OpRingTerm)) | zeroOL : OpRingTerm | negOL : (OpRingTerm → OpRingTerm) | oneOL : OpRingTerm open OpRingTerm inductive OpRingTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRingTerm2) | sing2 : (A → OpRingTerm2) | timesOL2 : (OpRingTerm2 → (OpRingTerm2 → OpRingTerm2)) | plusOL2 : (OpRingTerm2 → (OpRingTerm2 → OpRingTerm2)) | zeroOL2 : OpRingTerm2 | negOL2 : (OpRingTerm2 → OpRingTerm2) | oneOL2 : OpRingTerm2 open OpRingTerm2 def simplifyCl {A : Type} : ((ClRingTerm A) → (ClRingTerm A)) | (plusCl zeroCl x) := x | (plusCl x zeroCl) := x | (timesCl oneCl x) := x | (timesCl x oneCl) := x | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | zeroCl := zeroCl | (negCl x1) := (negCl (simplifyCl x1)) | oneCl := oneCl | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRingTerm n) → (OpRingTerm n)) | (plusOL zeroOL x) := x | (plusOL x zeroOL) := x | (timesOL oneOL x) := x | (timesOL x oneOL) := x | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | zeroOL := zeroOL | (negOL x1) := (negOL (simplifyOpB x1)) | oneOL := oneOL | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRingTerm2 n A) → (OpRingTerm2 n A)) | (plusOL2 zeroOL2 x) := x | (plusOL2 x zeroOL2) := x | (timesOL2 oneOL2 x) := x | (timesOL2 x oneOL2) := x | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | zeroOL2 := zeroOL2 | (negOL2 x1) := (negOL2 (simplifyOp x1)) | oneOL2 := oneOL2 | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Ring A) → (RingTerm → A)) | Ri (timesL x1 x2) := ((times Ri) (evalB Ri x1) (evalB Ri x2)) | Ri (plusL x1 x2) := ((plus Ri) (evalB Ri x1) (evalB Ri x2)) | Ri zeroL := (zero Ri) | Ri (negL x1) := ((neg Ri) (evalB Ri x1)) | Ri oneL := (one Ri) def evalCl {A : Type} : ((Ring A) → ((ClRingTerm A) → A)) | Ri (sing x1) := x1 | Ri (timesCl x1 x2) := ((times Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri (plusCl x1 x2) := ((plus Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri zeroCl := (zero Ri) | Ri (negCl x1) := ((neg Ri) (evalCl Ri x1)) | Ri oneCl := (one Ri) def evalOpB {A : Type} {n : ℕ} : ((Ring A) → ((vector A n) → ((OpRingTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (timesOL x1 x2) := ((times Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars (plusOL x1 x2) := ((plus Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars zeroOL := (zero Ri) | Ri vars (negOL x1) := ((neg Ri) (evalOpB Ri vars x1)) | Ri vars oneOL := (one Ri) def evalOp {A : Type} {n : ℕ} : ((Ring A) → ((vector A n) → ((OpRingTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (timesOL2 x1 x2) := ((times Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars (plusOL2 x1 x2) := ((plus Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars zeroOL2 := (zero Ri) | Ri vars (negOL2 x1) := ((neg Ri) (evalOp Ri vars x1)) | Ri vars oneOL2 := (one Ri) def inductionB {P : (RingTerm → Type)} : ((∀ (x1 x2 : RingTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : RingTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P zeroL) → ((∀ (x1 : RingTerm) , ((P x1) → (P (negL x1)))) → ((P oneL) → (∀ (x : RingTerm) , (P x))))))) | ptimesl pplusl p0l pnegl p1l (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl p0l pnegl p1l x1) (inductionB ptimesl pplusl p0l pnegl p1l x2)) | ptimesl pplusl p0l pnegl p1l (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl p0l pnegl p1l x1) (inductionB ptimesl pplusl p0l pnegl p1l x2)) | ptimesl pplusl p0l pnegl p1l zeroL := p0l | ptimesl pplusl p0l pnegl p1l (negL x1) := (pnegl _ (inductionB ptimesl pplusl p0l pnegl p1l x1)) | ptimesl pplusl p0l pnegl p1l oneL := p1l def inductionCl {A : Type} {P : ((ClRingTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRingTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClRingTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P zeroCl) → ((∀ (x1 : (ClRingTerm A)) , ((P x1) → (P (negCl x1)))) → ((P oneCl) → (∀ (x : (ClRingTerm A)) , (P x)))))))) | psing ptimescl ppluscl p0cl pnegcl p1cl (sing x1) := (psing x1) | psing ptimescl ppluscl p0cl pnegcl p1cl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl p0cl pnegcl p1cl x1) (inductionCl psing ptimescl ppluscl p0cl pnegcl p1cl x2)) | psing ptimescl ppluscl p0cl pnegcl p1cl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl p0cl pnegcl p1cl x1) (inductionCl psing ptimescl ppluscl p0cl pnegcl p1cl x2)) | psing ptimescl ppluscl p0cl pnegcl p1cl zeroCl := p0cl | psing ptimescl ppluscl p0cl pnegcl p1cl (negCl x1) := (pnegcl _ (inductionCl psing ptimescl ppluscl p0cl pnegcl p1cl x1)) | psing ptimescl ppluscl p0cl pnegcl p1cl oneCl := p1cl def inductionOpB {n : ℕ} {P : ((OpRingTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRingTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpRingTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P zeroOL) → ((∀ (x1 : (OpRingTerm n)) , ((P x1) → (P (negOL x1)))) → ((P oneOL) → (∀ (x : (OpRingTerm n)) , (P x)))))))) | pv ptimesol pplusol p0ol pnegol p1ol (v x1) := (pv x1) | pv ptimesol pplusol p0ol pnegol p1ol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol p0ol pnegol p1ol x1) (inductionOpB pv ptimesol pplusol p0ol pnegol p1ol x2)) | pv ptimesol pplusol p0ol pnegol p1ol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol p0ol pnegol p1ol x1) (inductionOpB pv ptimesol pplusol p0ol pnegol p1ol x2)) | pv ptimesol pplusol p0ol pnegol p1ol zeroOL := p0ol | pv ptimesol pplusol p0ol pnegol p1ol (negOL x1) := (pnegol _ (inductionOpB pv ptimesol pplusol p0ol pnegol p1ol x1)) | pv ptimesol pplusol p0ol pnegol p1ol oneOL := p1ol def inductionOp {n : ℕ} {A : Type} {P : ((OpRingTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRingTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpRingTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P zeroOL2) → ((∀ (x1 : (OpRingTerm2 n A)) , ((P x1) → (P (negOL2 x1)))) → ((P oneOL2) → (∀ (x : (OpRingTerm2 n A)) , (P x))))))))) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 x2)) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 x2)) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 zeroOL2 := p0ol2 | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 (negOL2 x1) := (pnegol2 _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 x1)) | pv2 psing2 ptimesol2 pplusol2 p0ol2 pnegol2 p1ol2 oneOL2 := p1ol2 def stageB : (RingTerm → (Staged RingTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | zeroL := (Now zeroL) | (negL x1) := (stage1 negL (codeLift1 negL) (stageB x1)) | oneL := (Now oneL) def stageCl {A : Type} : ((ClRingTerm A) → (Staged (ClRingTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | zeroCl := (Now zeroCl) | (negCl x1) := (stage1 negCl (codeLift1 negCl) (stageCl x1)) | oneCl := (Now oneCl) def stageOpB {n : ℕ} : ((OpRingTerm n) → (Staged (OpRingTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | zeroOL := (Now zeroOL) | (negOL x1) := (stage1 negOL (codeLift1 negOL) (stageOpB x1)) | oneOL := (Now oneOL) def stageOp {n : ℕ} {A : Type} : ((OpRingTerm2 n A) → (Staged (OpRingTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | zeroOL2 := (Now zeroOL2) | (negOL2 x1) := (stage1 negOL2 (codeLift1 negOL2) (stageOp x1)) | oneOL2 := (Now oneOL2) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (zeroT : (Repr A)) (negT : ((Repr A) → (Repr A))) (oneT : (Repr A)) end Ring
3c660574b4ce7f07c87ecf4b62f04be64786e62a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/stirling.lean
ae5e25a3b556b3c966dfa6c66686ae78c0abdfca
[ "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,865
lean
/- Copyright (c) 2022. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Firsching, Fabian Kruse, Nikolas Kuhn -/ import analysis.p_series import analysis.special_functions.log.deriv import tactic.positivity import data.real.pi.wallis /-! # Stirling's formula This file proves Stirling's formula for the factorial. It states that $n!$ grows asymptotically like $\sqrt{2\pi n}(\frac{n}{e})^n$. ## Proof outline The proof follows: <https://proofwiki.org/wiki/Stirling%27s_Formula>. We proceed in two parts. ### Part 1 We consider the fraction sequence $a_n$ of fractions $\frac{n!}{\sqrt{2n}(\frac{n}{e})^n}$ and prove that this sequence converges against a real, positive number $a$. For this the two main ingredients are - taking the logarithm of the sequence and - use the series expansion of $\log(1 + x)$. ### Part 2 We use the fact that the series defined in part 1 converges againt a real number $a$ and prove that $a = \sqrt{\pi}$. Here the main ingredient is the convergence of the Wallis product. -/ open_locale topological_space real big_operators nat open finset filter nat real namespace stirling /-! ### Part 1 https://proofwiki.org/wiki/Stirling%27s_Formula#Part_1 -/ /-- Define `stirling_seq n` as $\frac{n!}{\sqrt{2n}(\frac{n}{e})^n}$. Stirling's formula states that this sequence has limit $\sqrt(π)$. -/ noncomputable def stirling_seq (n : ℕ) : ℝ := n! / (sqrt (2 * n) * (n / exp 1) ^ n) @[simp] lemma stirling_seq_zero : stirling_seq 0 = 0 := by rw [stirling_seq, cast_zero, mul_zero, real.sqrt_zero, zero_mul, div_zero] @[simp] lemma stirling_seq_one : stirling_seq 1 = exp 1 / sqrt 2 := by rw [stirling_seq, pow_one, factorial_one, cast_one, mul_one, mul_one_div, one_div_div] /-- We have the expression `log (stirling_seq (n + 1)) = log(n + 1)! - 1 / 2 * log(2 * n) - n * log ((n + 1) / e)`. -/ lemma log_stirling_seq_formula (n : ℕ) : log (stirling_seq n.succ) = log n.succ!- 1 / 2 * log (2 * n.succ) - n.succ * log (n.succ / exp 1) := by rw [stirling_seq, log_div, log_mul, sqrt_eq_rpow, log_rpow, real.log_pow, tsub_tsub]; try { apply ne_of_gt }; positivity -- TODO: Make `positivity` handle `≠ 0` goals /-- The sequence `log (stirling_seq (m + 1)) - log (stirling_seq (m + 2))` has the series expansion `∑ 1 / (2 * (k + 1) + 1) * (1 / 2 * (m + 1) + 1)^(2 * (k + 1))` -/ lemma log_stirling_seq_diff_has_sum (m : ℕ) : has_sum (λ k : ℕ, (1 : ℝ) / (2 * k.succ + 1) * ((1 / (2 * m.succ + 1)) ^ 2) ^ k.succ) (log (stirling_seq m.succ) - log (stirling_seq m.succ.succ)) := begin change has_sum ((λ b : ℕ, 1 / (2 * (b : ℝ) + 1) * ((1 / (2 * m.succ + 1)) ^ 2) ^ b) ∘ succ) _, refine (has_sum_nat_add_iff 1).mpr _, convert (has_sum_log_one_add_inv $ cast_pos.mpr (succ_pos m)).mul_left ((m.succ : ℝ) + 1 / 2), { ext k, rw [← pow_mul, pow_add], push_cast, have : 2 * (k : ℝ) + 1 ≠ 0, {norm_cast, exact succ_ne_zero (2*k)}, have : 2 * ((m : ℝ) + 1) + 1 ≠ 0, {norm_cast, exact succ_ne_zero (2*m.succ)}, field_simp, ring }, { have h : ∀ (x : ℝ) (hx : x ≠ 0), 1 + x⁻¹ = (x + 1) / x, { intros, rw [_root_.add_div, div_self hx, inv_eq_one_div], }, simp only [log_stirling_seq_formula, log_div, log_mul, log_exp, factorial_succ, cast_mul, cast_succ, cast_zero, range_one, sum_singleton, h] { discharger := `[norm_cast, apply_rules [mul_ne_zero, succ_ne_zero, factorial_ne_zero, exp_ne_zero]] }, ring }, end /-- The sequence `log ∘ stirling_seq ∘ succ` is monotone decreasing -/ lemma log_stirling_seq'_antitone : antitone (real.log ∘ stirling_seq ∘ succ) := antitone_nat_of_succ_le $ λ n, sub_nonneg.mp $ (log_stirling_seq_diff_has_sum n).nonneg $ λ m, by positivity /-- We have a bound for successive elements in the sequence `log (stirling_seq k)`. -/ lemma log_stirling_seq_diff_le_geo_sum (n : ℕ) : log (stirling_seq n.succ) - log (stirling_seq n.succ.succ) ≤ (1 / (2 * n.succ + 1)) ^ 2 / (1 - (1 / (2 * n.succ + 1)) ^ 2) := begin have h_nonneg : 0 ≤ ((1 / (2 * (n.succ : ℝ) + 1)) ^ 2) := sq_nonneg _, have g : has_sum (λ k : ℕ, ((1 / (2 * (n.succ : ℝ) + 1)) ^ 2) ^ k.succ) ((1 / (2 * n.succ + 1)) ^ 2 / (1 - (1 / (2 * n.succ + 1)) ^ 2)), { refine (has_sum_geometric_of_lt_1 h_nonneg _).mul_left ((1 / (2 * (n.succ : ℝ) + 1)) ^ 2), rw [one_div, inv_pow], exact inv_lt_one (one_lt_pow ((lt_add_iff_pos_left 1).mpr $ by positivity) two_ne_zero) }, have hab : ∀ (k : ℕ), (1 / (2 * (k.succ : ℝ) + 1)) * ((1 / (2 * n.succ + 1)) ^ 2) ^ k.succ ≤ ((1 / (2 * n.succ + 1)) ^ 2) ^ k.succ, { refine λ k, mul_le_of_le_one_left (pow_nonneg h_nonneg k.succ) _, rw one_div, exact inv_le_one (le_add_of_nonneg_left $ by positivity) }, exact has_sum_le hab (log_stirling_seq_diff_has_sum n) g, end /-- We have the bound `log (stirling_seq n) - log (stirling_seq (n+1))` ≤ 1/(4 n^2) -/ lemma log_stirling_seq_sub_log_stirling_seq_succ (n : ℕ) : log (stirling_seq n.succ) - log (stirling_seq n.succ.succ) ≤ 1 / (4 * n.succ ^ 2) := begin have h₁ : 0 < 4 * ((n : ℝ) + 1) ^ 2 := by positivity, have h₃ : 0 < (2 * ((n : ℝ) + 1) + 1) ^ 2 := by positivity, have h₂ : 0 < 1 - (1 / (2 * ((n : ℝ) + 1) + 1)) ^ 2, { rw ← mul_lt_mul_right h₃, have H : 0 < (2 * ((n : ℝ) + 1) + 1) ^ 2 - 1 := by nlinarith [@cast_nonneg ℝ _ n], convert H using 1; field_simp [h₃.ne'] }, refine (log_stirling_seq_diff_le_geo_sum n).trans _, push_cast, rw div_le_div_iff h₂ h₁, field_simp [h₃.ne'], rw div_le_div_right h₃, ring_nf, norm_cast, linarith, end /-- For any `n`, we have `log_stirling_seq 1 - log_stirling_seq n ≤ 1/4 * ∑' 1/k^2` -/ lemma log_stirling_seq_bounded_aux : ∃ (c : ℝ), ∀ (n : ℕ), log (stirling_seq 1) - log (stirling_seq n.succ) ≤ c := begin let d := ∑' k : ℕ, (1 : ℝ) / k.succ ^ 2, use (1 / 4 * d : ℝ), let log_stirling_seq' : ℕ → ℝ := λ k, log (stirling_seq k.succ), intro n, have h₁ : ∀ k, log_stirling_seq' k - log_stirling_seq' (k + 1) ≤ 1 / 4 * (1 / k.succ ^ 2) := by { intro k, convert log_stirling_seq_sub_log_stirling_seq_succ k using 1, field_simp, }, have h₂ : ∑ (k : ℕ) in range n, (1 : ℝ) / (k.succ) ^ 2 ≤ d := by { exact sum_le_tsum (range n) (λ k _, by positivity) ((summable_nat_add_iff 1).mpr $ real.summable_one_div_nat_pow.mpr one_lt_two) }, calc log (stirling_seq 1) - log (stirling_seq n.succ) = log_stirling_seq' 0 - log_stirling_seq' n : rfl ... = ∑ k in range n, (log_stirling_seq' k - log_stirling_seq' (k + 1)) : by rw ← sum_range_sub' log_stirling_seq' n ... ≤ ∑ k in range n, (1/4) * (1 / k.succ^2) : sum_le_sum (λ k _, h₁ k) ... = 1 / 4 * ∑ k in range n, 1 / k.succ ^ 2 : by rw mul_sum ... ≤ 1 / 4 * d : mul_le_mul_of_nonneg_left h₂ $ by positivity, end /-- The sequence `log_stirling_seq` is bounded below for `n ≥ 1`. -/ lemma log_stirling_seq_bounded_by_constant : ∃ c, ∀ (n : ℕ), c ≤ log (stirling_seq n.succ) := begin obtain ⟨d, h⟩ := log_stirling_seq_bounded_aux, exact ⟨log (stirling_seq 1) - d, λ n, sub_le_comm.mp (h n)⟩, end /-- The sequence `stirling_seq` is positive for `n > 0` -/ lemma stirling_seq'_pos (n : ℕ) : 0 < stirling_seq n.succ := by { unfold stirling_seq, positivity } /-- The sequence `stirling_seq` has a positive lower bound. -/ lemma stirling_seq'_bounded_by_pos_constant : ∃ a, 0 < a ∧ ∀ n : ℕ, a ≤ stirling_seq n.succ := begin cases log_stirling_seq_bounded_by_constant with c h, refine ⟨exp c, exp_pos _, λ n, _⟩, rw ← le_log_iff_exp_le (stirling_seq'_pos n), exact h n, end /-- The sequence `stirling_seq ∘ succ` is monotone decreasing -/ lemma stirling_seq'_antitone : antitone (stirling_seq ∘ succ) := λ n m h, (log_le_log (stirling_seq'_pos m) (stirling_seq'_pos n)).mp (log_stirling_seq'_antitone h) /-- The limit `a` of the sequence `stirling_seq` satisfies `0 < a` -/ lemma stirling_seq_has_pos_limit_a : ∃ (a : ℝ), 0 < a ∧ tendsto stirling_seq at_top (𝓝 a) := begin obtain ⟨x, x_pos, hx⟩ := stirling_seq'_bounded_by_pos_constant, have hx' : x ∈ lower_bounds (set.range (stirling_seq ∘ succ)) := by simpa [lower_bounds] using hx, refine ⟨_, lt_of_lt_of_le x_pos (le_cInf (set.range_nonempty _) hx'), _⟩, rw ←filter.tendsto_add_at_top_iff_nat 1, exact tendsto_at_top_cinfi stirling_seq'_antitone ⟨x, hx'⟩, end /-! ### Part 2 https://proofwiki.org/wiki/Stirling%27s_Formula#Part_2 -/ /-- For `n : ℕ`, define `w n` as `2^(4*n) * n!^4 / ((2*n)!^2 * (2*n + 1))` -/ noncomputable def w (n : ℕ) : ℝ := (2 ^ (4 * n) * n! ^ 4) / ((2 * n)!^ 2 * (2 * n + 1)) /-- The sequence `w n` converges to `π/2` -/ lemma tendsto_w_at_top: tendsto (λ (n : ℕ), w n) at_top (𝓝 (π/2)) := begin convert tendsto_prod_pi_div_two, funext n, induction n with n ih, { rw [w, prod_range_zero, cast_zero, mul_zero, pow_zero, one_mul, mul_zero, factorial_zero, cast_one, one_pow, one_pow, one_mul, mul_zero, zero_add, div_one] }, rw [w, prod_range_succ, ←ih, w, _root_.div_mul_div_comm, _root_.div_mul_div_comm], refine (div_eq_div_iff _ _).mpr _, any_goals { exact ne_of_gt (by positivity) }, simp_rw [nat.mul_succ, factorial_succ, pow_succ], push_cast, ring_nf, end /-- The sequence `n / (2 * n + 1)` tends to `1/2` -/ lemma tendsto_self_div_two_mul_self_add_one : tendsto (λ (n : ℕ), (n : ℝ) / (2 * n + 1)) at_top (𝓝 (1 / 2)) := begin conv { congr, skip, skip, rw [one_div, ←add_zero (2 : ℝ)] }, refine (((tendsto_const_div_at_top_nhds_0_nat 1).const_add (2 : ℝ)).inv₀ ((add_zero (2 : ℝ)).symm ▸ two_ne_zero)).congr' (eventually_at_top.mpr ⟨1, λ n hn, _⟩), rw [add_div' (1 : ℝ) (2 : ℝ) (n : ℝ) (cast_ne_zero.mpr (one_le_iff_ne_zero.mp hn)), inv_div], end /-- For any `n ≠ 0`, we have the identity `(stirling_seq n)^4/(stirling_seq (2*n))^2 * (n / (2 * n + 1)) = w n`. -/ lemma stirling_seq_pow_four_div_stirling_seq_pow_two_eq (n : ℕ) (hn : n ≠ 0) : ((stirling_seq n) ^ 4 / (stirling_seq (2 * n)) ^ 2) * (n / (2 * n + 1)) = w n := begin rw [bit0_eq_two_mul, stirling_seq, pow_mul, stirling_seq, w], simp_rw [div_pow, mul_pow], rw [sq_sqrt, sq_sqrt], any_goals { positivity }, have : (n : ℝ) ≠ 0, from cast_ne_zero.mpr hn, have : (exp 1) ≠ 0, from exp_ne_zero 1, have : ((2 * n)!: ℝ) ≠ 0, from cast_ne_zero.mpr (factorial_ne_zero (2 * n)), have : 2 * (n : ℝ) + 1 ≠ 0, by {norm_cast, exact succ_ne_zero (2*n)}, field_simp, simp only [mul_pow, mul_comm 2 n, mul_comm 4 n, pow_mul], ring, end /-- Suppose the sequence `stirling_seq` (defined above) has the limit `a ≠ 0`. Then the sequence `w` has limit `a^2/2` -/ lemma second_wallis_limit (a : ℝ) (hane : a ≠ 0) (ha : tendsto stirling_seq at_top (𝓝 a)) : tendsto w at_top (𝓝 (a ^ 2 / 2)):= begin refine tendsto.congr' (eventually_at_top.mpr ⟨1, λ n hn, stirling_seq_pow_four_div_stirling_seq_pow_two_eq n (one_le_iff_ne_zero.mp hn)⟩) _, have h : a ^ 2 / 2 = (a ^ 4 / a ^ 2) * (1 / 2), { rw [mul_one_div, ←mul_one_div (a ^ 4) (a ^ 2), one_div, ←pow_sub_of_lt a], norm_num }, rw h, exact ((ha.pow 4).div ((ha.comp (tendsto_id.const_mul_at_top' two_pos)).pow 2) (pow_ne_zero 2 hane)).mul tendsto_self_div_two_mul_self_add_one, end /-- **Stirling's Formula** -/ theorem tendsto_stirling_seq_sqrt_pi : tendsto (λ (n : ℕ), stirling_seq n) at_top (𝓝 (sqrt π)) := begin obtain ⟨a, hapos, halimit⟩ := stirling_seq_has_pos_limit_a, have hπ : π / 2 = a ^ 2 / 2 := tendsto_nhds_unique tendsto_w_at_top (second_wallis_limit a (ne_of_gt hapos) halimit), rwa [(div_left_inj' (show (2 : ℝ) ≠ 0, from two_ne_zero)).mp hπ, sqrt_sq hapos.le], end end stirling
b98f88e1e91c646d4a7ca9fbb2c47c968d612f96
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/computability/turing_machine.lean
7cb89dc012cc465c2fdaa32be387841c48263fa8
[ "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
109,942
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order.basic import data.fintype.basic import data.pfun import tactic.apply_fun import logic.function.iterate /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → part output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat (default Γ) n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩ theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, nat.add_sub_cancel' h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, nat.sub_add_cancel], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only [list.inth], cases lt_or_le _ _ with h h, {rw list.nth_append h}, rw list.nth_len_le h, cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂}, rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [nat.add_sub_of_le h, list.length_append, list.length_repeat] }, simp at H, cases lt_or_le i l₁.length with h' h', { simpa only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i }, { simpa only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', option.iget] using H i }, end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons], congr } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f (default _) = default _) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨λ _, default _, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') := ⟨_, pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `part.none`. -/ def eval {σ} (f : σ → option σ) : σ → part σ := pfun.fix (λ s, part.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} (hab : reaches f a b) (hac : reaches f a c) : reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $ part.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ part.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases part.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply part.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply part.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := part.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := part.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (part.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [part.map_eq_map, part.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin letI := classical.dec_eq Γ, let n := fintype.card Γ, obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc (default _) = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e using 1, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : part (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on _, intro l, simp, rw (_ : _ ∘ _ = id), {simp}, funext a, refl end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.inth, list.map], { rw [list.nth_le_nth, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth], cases lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail, list.inth], { rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons], cases lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _), obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (part.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (part.mem_map_iff _).1 H₂, obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases part.mem_unique h₁ h₃, exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
726ceac48171e18007bc86a0f926cd056bd56027
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/backtrackable_estate.lean
113adcc3c8ca4c7dfb8b86dae4bae500917047f4
[ "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
691
lean
import Init.System.IO structure MyState := bs : Nat := 0 -- backtrackable state ps : Nat := 0 -- non backtrackable state instance : Repr MyState where reprPrec s _ := repr (s.bs, s.ps) instance : EStateM.Backtrackable Nat MyState := { save := fun s => s.bs, restore := fun s d => { s with bs := d } } abbrev M := EStateM String MyState def bInc : M Unit := -- increment backtrackble counter modify $ fun s => { s with bs := s.bs + 1 } def pInc : M Unit := -- increment nonbacktrackable counter modify $ fun s => { s with ps := s.ps + 1 } def tst : M MyState := do bInc; pInc; ((bInc *> throw "failed") <|> pInc); pInc; get #eval tst.run' {} -- (some (1, 3))
0725de504969b3d534d1a02b4a414e347395367f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/normed_space/pi_Lp.lean
66dc76d711ce5f6aa54801e28dd6f900d37486c9
[ "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
21,993
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.mean_inequalities import analysis.normed_space.inner_product /-! # `L^p` distance on finite products of metric spaces Given finitely many metric spaces, one can put the max distance on their product, but there is also a whole family of natural distances, indexed by a real parameter `p ∈ [1, ∞)`, that also induce the product topology. We define them in this file. The distance on `Π i, α i` is given by $$ d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}. $$ We give instances of this construction for emetric spaces, metric spaces, normed groups and normed spaces. To avoid conflicting instances, all these are defined on a copy of the original Pi type, named `pi_Lp p hp α`, where `hp : 1 ≤ p`. This assumption is included in the definition of the type to make sure that it is always available to typeclass inference to construct the instances. We ensure that the topology and uniform structure on `pi_Lp p hp α` are (defeq to) the product topology and product uniformity, to be able to use freely continuity statements for the coordinate functions, for instance. In the specific case of the `L^2`-norm, we show that we get an inner product space. We define `euclidean_space 𝕜 n` to be `pi_Lp 2 _ (n → 𝕜)` for any `fintype n`, i.e., the space from functions to `n` to `𝕜` with the `L^2` norm, and register several instances on it (notably that it is a finite-dimensional inner product space). ## Implementation notes We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be distinct. A closely related construction is the `L^p` norm on the space of functions from a measure space to a normed space, where the norm is $$ \left(\int ∥f (x)∥^p dμ\right)^{1/p}. $$ However, the topology induced by this construction is not the product topology, this only defines a seminorm (as almost everywhere zero functions have zero `L^p` norm), and some functions have infinite `L^p` norm. All these subtleties are not present in the case of finitely many metric spaces (which corresponds to the basis which is a finite space with the counting measure), hence it is worth devoting a file to this specific case which is particularly well behaved. The general case is not yet formalized in mathlib. To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit (easy) proof which provides a comparison between these two norms with explicit constants. We also set up the theory for `pseudo_emetric_space` and `pseudo_metric_space`. -/ open real set filter is_R_or_C open_locale big_operators uniformity topological_space nnreal ennreal noncomputable theory variables {ι : Type*} /-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put different distances, and we provide the assumption `hp` in the definition, to make it available to typeclass resolution when it looks for a distance on `pi_Lp p hp α`. -/ @[nolint unused_arguments] def pi_Lp {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) : Type* := Π (i : ι), α i instance {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) [∀ i, inhabited (α i)] : inhabited (pi_Lp p hp α) := ⟨λ i, default (α i)⟩ namespace pi_Lp variables (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) (β : ι → Type*) /-- Canonical bijection between `pi_Lp p hp α` and the original Pi type. We introduce it to be able to compare the `L^p` and `L^∞` distances through it. -/ protected def equiv : pi_Lp p hp α ≃ Π (i : ι), α i := equiv.refl _ section /-! ### The uniformity on finite `L^p` products is the product uniformity In this section, we put the `L^p` edistance on `pi_Lp p hp α`, and we check that the uniformity coming from this edistance coincides with the product uniformity, by showing that the canonical map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and antiLipschitz. We only register this emetric space structure as a temporary instance, as the true instance (to be registered later) will have as uniformity exactly the product uniformity, instead of the one coming from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ variables [∀ i, emetric_space (α i)] [∀ i, pseudo_emetric_space (β i)] [fintype ι] /-- Endowing the space `pi_Lp p hp β` with the `L^p` pseudoedistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this pseudoemetric space and `pseudo_emetric_space.replace_uniformity`. -/ def pseudo_emetric_aux : pseudo_emetric_space (pi_Lp p hp β) := have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, { edist := λ f g, (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p), edist_self := λ f, by simp [edist, ennreal.zero_rpow_of_pos pos, ennreal.zero_rpow_of_pos (inv_pos.2 pos)], edist_comm := λ f g, by simp [edist, edist_comm], edist_triangle := λ f g h, calc (∑ (i : ι), edist (f i) (h i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), (edist (f i) (g i) + edist (g i) (h i)) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), refine finset.sum_le_sum (λ i hi, _), exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (le_trans zero_le_one hp) end ... ≤ (∑ (i : ι), edist (f i) (g i) ^ p) ^ (1 / p) + (∑ (i : ι), edist (g i) (h i) ^ p) ^ (1 / p) : ennreal.Lp_add_le _ _ _ hp } /-- Endowing the space `pi_Lp p hp α` with the `L^p` edistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary emetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this emetric space and `emetric_space.replace_uniformity`. -/ def emetric_aux : emetric_space (pi_Lp p hp α) := { eq_of_edist_eq_zero := λ f g hfg, begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, letI h := pseudo_emetric_aux p hp α, have h : edist f g = (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p) := rfl, simp [h, ennreal.rpow_eq_zero_iff, pos, asymm pos, finset.sum_eq_zero_iff_of_nonneg] at hfg, exact funext hfg end, ..pseudo_emetric_aux p hp α } local attribute [instance] pi_Lp.emetric_aux pi_Lp.pseudo_emetric_aux lemma lipschitz_with_equiv : lipschitz_with 1 (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff, ennreal.coe_one], assume i, calc edist (x i) (y i) = (edist (x i) (y i) ^ p) ^ (1/p) : by simp [← ennreal.rpow_mul, cancel, -one_div] ... ≤ (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), exact finset.single_le_sum (λ i hi, (bot_le : (0 : ℝ≥0∞) ≤ _)) (finset.mem_univ i) end end lemma antilipschitz_with_equiv : antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1/p)) (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have nonneg : 0 ≤ 1 / p := one_div_nonneg.2 (le_of_lt pos), have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp [edist, -one_div], calc (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ nonneg, apply finset.sum_le_sum (λ i hi, _), apply ennreal.rpow_le_rpow _ (le_of_lt pos), exact finset.le_sup (finset.mem_univ i) end ... = (((fintype.card ι : ℝ≥0)) ^ (1/p) : ℝ≥0) * edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) : begin simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const, ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel], have : (fintype.card ι : ℝ≥0∞) = (fintype.card ι : ℝ≥0) := (ennreal.coe_nat (fintype.card ι)).symm, rw [this, ennreal.coe_rpow_of_nonneg _ nonneg] end end lemma aux_uniformity_eq : 𝓤 (pi_Lp p hp β) = @uniformity _ (Pi.uniform_space _) := begin have A : uniform_inducing (pi_Lp.equiv p hp β) := (antilipschitz_with_equiv p hp β).uniform_inducing (lipschitz_with_equiv p hp β).uniform_continuous, have : (λ (x : pi_Lp p hp β × pi_Lp p hp β), ((pi_Lp.equiv p hp β) x.fst, (pi_Lp.equiv p hp β) x.snd)) = id, by ext i; refl, rw [← A.comap_uniformity, this, comap_id] end end /-! ### Instances on finite `L^p` products -/ instance uniform_space [∀ i, uniform_space (β i)] : uniform_space (pi_Lp p hp β) := Pi.uniform_space _ variable [fintype ι] /-- pseudoemetric space instance on the product of finitely many pseudoemetric spaces, using the `L^p` pseudoedistance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_emetric_space (β i)] : pseudo_emetric_space (pi_Lp p hp β) := (pseudo_emetric_aux p hp β).replace_uniformity (aux_uniformity_eq p hp β).symm /-- emetric space instance on the product of finitely many emetric spaces, using the `L^p` edistance, and having as uniformity the product uniformity. -/ instance [∀ i, emetric_space (α i)] : emetric_space (pi_Lp p hp α) := (emetric_aux p hp α).replace_uniformity (aux_uniformity_eq p hp α).symm protected lemma edist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_emetric_space (β i)] (x y : pi_Lp p hp β) : edist x y = (∑ (i : ι), (edist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- pseudometric space instance on the product of finitely many psuedometric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_metric_space (β i)] : pseudo_metric_space (pi_Lp p hp β) := begin /- we construct the instance from the pseudo emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end /-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, metric_space (α i)] : metric_space (pi_Lp p hp α) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine emetric_space.to_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end protected lemma dist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_metric_space (β i)] (x y : pi_Lp p hp β) : dist x y = (∑ (i : ι), (dist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- seminormed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance semi_normed_group [∀i, semi_normed_group (β i)] : semi_normed_group (pi_Lp p hp β) := { norm := λf, (∑ (i : ι), norm (f i) ^ p) ^ (1/p), dist_eq := λ x y, by { simp [pi_Lp.dist, dist_eq_norm, sub_eq_add_neg] }, .. pi.add_comm_group } /-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance normed_group [∀i, normed_group (α i)] : normed_group (pi_Lp p hp α) := { ..pi_Lp.semi_normed_group p hp α } lemma norm_eq {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ p) ^ (1/p) := rfl lemma norm_eq_of_nat {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (n : ℕ) (h : p = n) (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ n) ^ (1/(n : ℝ)) := by simp [norm_eq, h, real.sqrt_eq_rpow, ←real.rpow_nat_cast] variables (𝕜 : Type*) [normed_field 𝕜] /-- The product of finitely many seminormed spaces is a seminormed space, with the `L^p` norm. -/ instance semi_normed_space [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] : semi_normed_space 𝕜 (pi_Lp p hp β) := { norm_smul_le := begin assume c f, have : p * (1 / p) = 1 := mul_div_cancel' 1 (ne_of_gt (lt_of_lt_of_le zero_lt_one hp)), simp only [pi_Lp.norm_eq, norm_smul, mul_rpow, norm_nonneg, ←finset.mul_sum, pi.smul_apply], rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _), this, rpow_one], exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) end, .. pi.module ι β 𝕜 } /-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/ instance normed_space [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] : normed_space 𝕜 (pi_Lp p hp α) := { ..pi_Lp.semi_normed_space p hp α 𝕜 } /- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas for Pi types will not trigger. -/ variables {𝕜 p hp α} [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] (c : 𝕜) (x y : pi_Lp p hp β) (i : ι) @[simp] lemma add_apply : (x + y) i = x i + y i := rfl @[simp] lemma sub_apply : (x - y) i = x i - y i := rfl @[simp] lemma smul_apply : (c • x) i = c • x i := rfl @[simp] lemma neg_apply : (-x) i = - (x i) := rfl end pi_Lp section /-! ### Inner product space structure on product spaces -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ j (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw [←finset.sum_hom finset.univ conj], apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, apply_instance end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } @[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 one_le_two f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ := rfl lemma pi_Lp.norm_eq_of_L2 {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x : pi_Lp 2 one_le_two f) : ∥x∥ = sqrt (∑ (i : ι), ∥x i∥ ^ 2) := by { rw [pi_Lp.norm_eq_of_nat 2]; simp [sqrt_eq_rpow] } /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜) lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ (i : n), ∥x i∥ ^ 2) := pi_Lp.norm_eq_of_L2 x section local attribute [reducible] pi_Lp variables [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma finrank_euclidean_space : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma finrank_euclidean_space_fin {n : ℕ} : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp /-- An orthonormal basis on a fintype `ι` for an inner product space induces an isometry with `euclidean_space 𝕜 ι`. -/ def basis.isometry_euclidean_of_orthonormal (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 ι) := v.equiv_fun.isometry_of_inner begin intros x y, let p : euclidean_space 𝕜 ι := v.equiv_fun x, let q : euclidean_space 𝕜 ι := v.equiv_fun y, have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫, { simp [sum_inner, inner_smul_left, hv.inner_right_fintype] }, convert key, { rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] }, { rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] } end end /-- `ℂ` is isometric to `ℝ²` with the Euclidean inner product. -/ def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) := complex.basis_one_I.isometry_euclidean_of_orthonormal begin rw orthonormal_iff_ite, intros i, fin_cases i; intros j; fin_cases j; simp [real_inner_eq_re_inner] end @[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) : complex.isometry_euclidean.symm x = (x 0) + (x 1) * I := begin convert complex.basis_one_I.equiv_fun_symm_apply x, { simpa }, { simp }, end lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) : ↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z := by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z), complex.isometry_euclidean.symm_apply_apply z] @[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) : complex.isometry_euclidean z 0 = z.re := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } @[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) : complex.isometry_euclidean z 1 = z.im := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } open finite_dimensional /-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space, there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.of_inner_product_space [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := (fin_orthonormal_basis hn).isometry_euclidean_of_orthonormal (fin_orthonormal_basis_orthonormal hn) local attribute [instance] finite_dimensional_of_finrank_eq_succ /-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product space, there exists an isometry from the orthogonal complement of a nonzero singleton to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.from_orthogonal_span_singleton (n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : (𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := linear_isometry_equiv.of_inner_product_space (finrank_orthogonal_span_singleton hv) end
1c17f3bee2d600abf75b44958067e66fc2f2616e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/module/prod.lean
2f19cb78e953a959ec00ebe532df4ea3c7d314f0
[ "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
1,145
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.module.basic import group_theory.group_action.prod /-! # Prod instances for module and multiplicative actions This file defines instances for binary product of modules -/ variables {R : Type*} {S : Type*} {M : Type*} {N : Type*} namespace prod instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] : module R (M × N) := { add_smul := λ a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, zero_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, .. prod.distrib_mul_action } instance {r : semiring R} [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] [no_zero_smul_divisors R M] [no_zero_smul_divisors R N] : no_zero_smul_divisors R (M × N) := ⟨λ c ⟨x, y⟩ h, or_iff_not_imp_left.mpr (λ hc, mk.inj_iff.mpr ⟨(smul_eq_zero.mp (congr_arg fst h)).resolve_left hc, (smul_eq_zero.mp (congr_arg snd h)).resolve_left hc⟩)⟩ end prod
2ba8179459e620ae2d3a867aeabb8fabd0c2bd30
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Std/Data/DList.lean
6f9372125d2c412e9a434b8e1cc965a53f0929ec
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,812
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Std universes u /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) where apply : List α → List α invariant : ∀ l, apply l = apply [] ++ l namespace DList variable {α : Type u} open List def ofList (l : List α) : DList α := ⟨(l ++ ·), fun t => by show _ = (l ++ []) ++ _; rw appendNil⟩ def empty : DList α := ⟨id, fun t => rfl⟩ instance : EmptyCollection (DList α) := ⟨DList.empty⟩ def toList : DList α → List α | ⟨f, h⟩ => f [] def singleton (a : α) : DList α := { apply := fun t => a :: t, invariant := fun t => rfl } def cons : α → DList α → DList α | a, ⟨f, h⟩ => { apply := fun t => a :: f t, invariant := by intro t show a :: f t = a :: f [] ++ t rw [consAppend, h] } def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => { apply := f ∘ g, invariant := by intro t show f (g t) = (f (g [])) ++ t rw [h₁ (g t), h₂ t, ← appendAssoc (f []) (g []) t, ← h₁ (g [])] } def push : DList α → α → DList α | ⟨f, h⟩, a => { apply := fun t => f (a :: t), invariant := by intro t show f (a :: t) = f (a :: nil) ++ t rw [h [a], h (a::t), appendAssoc (f []) [a] t] rfl } instance : Append (DList α) := ⟨DList.append⟩ end DList end Std
225ac78df6e5aed0b0c72b74e2f623521183c03d
3bd26f8e9c7eeb6ae77ac4ba709b5b3c65b8d7cf
/prim_rec.lean
52b694870f6a35f7b1cfaf09741cc29560639965
[]
no_license
koba-e964/lean-work
afac5677efef6905fce29cac44f36f309c3bcd62
6ab0506b9bd4e5a2e1ba6312d4ac6bdaf6ae1594
refs/heads/master
1,659,773,150,740
1,659,289,453,000
1,659,289,453,000
100,273,655
0
0
null
null
null
null
UTF-8
Lean
false
false
8,152
lean
import .fin_seq inductive prim_rec: nat -> Type | zero: prim_rec 0 | succ: prim_rec 1 | proj: forall {n}, fin n -> prim_rec n | comp: forall {k m}, prim_rec k -> (fin k -> prim_rec m) -> prim_rec m | prec: forall {k}, prim_rec k -> prim_rec (k + 2) -> prim_rec (k + 1) namespace prim_rec def eval : forall {k}, prim_rec k -> (fin k -> nat) -> nat | 0 prim_rec.zero _arg := 0 | 1 prim_rec.succ arg := arg 0 + 1 | m (prim_rec.proj idx) arg := arg idx | m (@prim_rec.comp k .(m) (f: prim_rec k) g) arg := eval f (fun i, eval (g i) arg) | .(_) (@prim_rec.prec k f g) arg := let h := fun (v: nat) (arg: fin k -> nat), @nat.rec (fun _, nat) (eval f arg) (fun (v': nat) (prev: nat), eval g (fin_seq.push prev (fin_seq.push v' arg))) v in let ⟨x, y⟩ := fin_seq.pop arg in h x y def sum_of_fin: forall {n}, fin_seq n nat -> nat | 0 _ := 0 | (n' + 1) ls := sum_of_fin (fun i, ls (fin.succ i)) + ls 0 def size_of: forall {k}, prim_rec k -> nat | 0 prim_rec.zero := 1 | 1 prim_rec.succ := 1 | m (prim_rec.proj idx) := 1 | m (@prim_rec.comp k .(m) (f: prim_rec k) g) := size_of f + sum_of_fin (λi, size_of (g i)) + 1 | .(_) (@prim_rec.prec k f g) := size_of f + size_of g + 1 @[simp] lemma zero.is_zero: eval zero fin_seq.empty = 0 := begin reflexivity, end lemma zero.size: size_of zero = 1 := rfl def const: nat -> prim_rec 0 | 0 := zero | (k + 1) := comp succ ({const k}: fin_seq _ _) @[simp] def const.is_const: forall x, eval (const x) fin_seq.empty = x := begin intro x, induction x with x' ih, { reflexivity }, { simp [eval, const], rw ih, }, end lemma const.size: forall x, size_of (const x) = x * 2 + 1 := begin intro x, induction x with x' ih, reflexivity, simp [size_of, const], change 1 + sum_of_fin ({size_of (const x')}) + 1 = x'.succ * 2 + 1, rw ih, simp [sum_of_fin], rw nat.zero_add, rw nat.add_comm 1 _, rw nat.succ_mul x', end @[simp] lemma succ.is_succ: forall x, eval prim_rec.succ ({x}: fin_seq _ _) = x + 1 := fun x, calc eval prim_rec.succ ({x}: fin_seq _ _) = x + 1 : by unfold eval; reflexivity lemma succ.size: size_of succ = 1 := rfl lemma uncurry_1: forall v: nat, fin_seq.pop {v} = ⟨v, fin_seq.empty⟩ := fin_seq.pop_1 lemma curry_at_0: forall k v (rest: fin k -> nat), fin_seq.push v rest 0 = v := begin apply fin_seq.push_at_0 end lemma curry_at_succ: forall k v (rest: fin k -> nat) (i: fin k), fin_seq.push v rest (fin.succ i) = rest i := begin apply fin_seq.push_at_succ, end def id: prim_rec 1 := proj 0 @[simp] lemma id.is_id : forall x, eval id ({x}: fin_seq 1 nat) = x := begin intro x, reflexivity, end lemma id.size: size_of id = 1 := rfl def pred: prim_rec 1 := prec zero (proj 1) @[simp] lemma pred.is_pred: forall x, eval pred ({x}: fin_seq _ _) = x - 1 := begin intro x, cases x with x', { reflexivity }, { reflexivity }, end lemma pred.size: size_of pred = 3 := rfl def is_zero: prim_rec 1 := prec (const 1) (comp zero (fun _, proj 0)) @[simp] lemma is_zero.is_is_zero: forall x, eval is_zero ({x}: fin_seq 1 nat) = if x = 0 then 1 else 0 := begin intro x, cases x with x', { reflexivity }, { reflexivity }, end @[simp] lemma is_zero.is_is_zero_bulk: forall (xs: fin_seq 1 nat), eval is_zero xs = if xs 0 = 0 then 1 else 0 := begin intro xs, rw <- fin_seq.length_1_of_singleton xs, rw is_zero.is_is_zero, simp, end lemma is_zero.size: size_of is_zero = 6 := rfl -- S(x) + y = S(x + y) def add: prim_rec 2 := prec id (comp succ ({proj 0}: fin_seq _ _)) -- sub_rev(x, y) = y - x def sub_rev: prim_rec 2 := prec id (comp pred ({proj 0}: fin_seq _ _)) def sub: prim_rec 2 := comp sub_rev (fin_seq.push (proj 1) {proj 0}) def mul: prim_rec 2 := prec (comp zero (fun _, succ)) (comp add (fin_seq.push (proj 0) {proj 2})) -- logic def le: prim_rec 2 := comp is_zero ({sub}: fin_seq _ _) def ge: prim_rec 2 := comp is_zero ({sub_rev}: fin_seq _ _) -- and(x, y) = if x != 0 then y else 0 def and: prim_rec 2 := prec (comp zero (fun _, proj 0)) (proj 2) -- or(x, y) = if x != 0 then x else y def or: prim_rec 2 := prec id (comp succ ({proj 1}: fin_seq _ _)) def not: prim_rec 1 := is_zero -- cond(x, y, z) = if x != 0 then y else z def cond: prim_rec 3 := prec (proj 1) (proj 2) -- def eq: prim_rec 2 := comp and (fin_seq.push le {ge}) def eq: prim_rec 2 := comp is_zero ({comp add (fin_seq.push sub {sub_rev})}: fin_seq _ _) @[simp] lemma add.is_add: forall x y, eval add (fin_seq.push x {y}) = x + y := begin intro x, induction x with x' ih, { intro y, rw nat.add_comm, rw nat.add_zero, simp [add, eval], reflexivity, }, { intro y, change add.eval (fin_seq.push x' {y}) + 1 = x'.succ + y, rw ih, rw nat.add_comm x'.succ y, rw nat.add_succ y x', rw nat.add_comm y x', }, end @[simp] lemma add.is_add_bulk: forall xy, eval add xy = xy 0 + xy 1 := begin intro xy, rw <- fin_seq.length_2_of_insert_of_singleton xy, apply add.is_add, end lemma add.size: size_of add = 5 := rfl @[simp] lemma sub_rev.is_sub_rev: forall x y, eval sub_rev (fin_seq.push x {y}) = y - x := begin intro x, induction x with x' ih, { intro y, simp [sub_rev, eval], reflexivity, }, { intro y, change pred.eval ({sub_rev.eval (fin_seq.push x' {y})}: fin_seq _ _) = y - x'.succ, simp, rw ih, reflexivity, }, end lemma sub_rev.size: size_of sub_rev = 7 := rfl @[simp] lemma sub_rev.is_sub_rev_bulk: forall xy, eval sub_rev xy = xy 1 - xy 0 := begin intro xy, rw <- fin_seq.length_2_of_insert_of_singleton xy, apply sub_rev.is_sub_rev, end @[simp] lemma sub.is_sub: forall x y, eval sub (fin_seq.push x {y}) = x - y := begin simp only [eval, sub], simp [sub_rev.is_sub_rev_bulk, eval], intros x y, reflexivity, end lemma sub.size: size_of sub = 10 := rfl @[simp] lemma mul.is_mul: forall x y, eval mul (fin_seq.push x {y}) = x * y := begin intro x, induction x with x' ih; intro y, { change 0 = 0 * y, rw nat.zero_mul, }, { simp only [mul, eval], change add.eval (fin_seq.push (mul.eval (fin_seq.push x' {y})) ({y}: fin_seq _ _)) = x'.succ * y, rw ih, rw add.is_add, rw nat.succ_mul, }, end lemma mul.size: size_of sub = 10 := rfl @[simp] lemma le.is_le: forall x y, eval le (fin_seq.push x {y}) = if x <= y then 1 else 0 := begin simp [le, eval], intros x y, apply if_congr, rw @nat.sub_eq_zero_iff_le x y, simp, end lemma le.size: size_of le = 17 := rfl @[simp] lemma ge.is_ge: forall x y, eval ge (fin_seq.push x {y}) = if x >= y then 1 else 0 := begin simp [ge, eval], intros x y, apply if_congr, change y - x = 0 <-> x >= y, rw nat.sub_eq_zero_iff_le, simp, end lemma ge.size: size_of ge = 14 := rfl @[simp] lemma and.is_and: forall x y, eval and (fin_seq.push x {y}) = if x ≠ 0 then y else 0 := begin intros x y, cases x with x'; reflexivity, end lemma and.size: size_of and = 4 := rfl @[simp] lemma or.is_or: forall x y, eval or (fin_seq.push x {y}) = if x ≠ 0 then x else y := begin intros x y, cases x with x'; reflexivity, end lemma or.size: size_of or = 5 := rfl @[simp] lemma not.is_not: forall x, eval not ({x}: fin_seq _ _) = if x ≠ 0 then 0 else 1 := begin intros x, cases x with x'; reflexivity, end lemma not.size: size_of not = 6 := rfl @[simp] lemma cond.is_cond: forall (x y z: nat), eval cond (fin_seq.push x (fin_seq.push y ({z}: fin_seq 1 nat))) = if x ≠ 0 then y else z := begin intros x y z, cases x with x'; reflexivity, end lemma cond.size: size_of cond = 3 := rfl @[simp] lemma eq.is_eq: forall x y, eval eq (fin_seq.push x {y}) = if x = y then 1 else 0 := begin intros x y, simp [eval, eq], apply if_congr, change (x - y) + eval sub_rev (fin_seq.push x {y}) = 0 <-> x = y, rw sub_rev.is_sub_rev, change (x - y) + (y - x) = 0 <-> x = y, split, { intro h, have := nat.eq_zero_of_add_eq_zero h, cases this with h1 h2, apply nat.le_antisymm, apply nat.le_of_sub_eq_zero h1, apply nat.le_of_sub_eq_zero h2, }, { intro h, cases h, rw nat.sub_self, }, simp, end lemma eq.size: size_of eq = 30 := rfl end prim_rec