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
9a9dd0441df676569df85829893fe1c958632507
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/category/Cat.lean
5494837c721a13db23af91263afef6307984be30
[]
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
2,426
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.concrete_category.default import Mathlib.category_theory.discrete_category import Mathlib.category_theory.eq_to_hom import Mathlib.PostPort universes v u u_1 u_2 u_3 u_4 namespace Mathlib /-! # Category of categories This file contains the definition of the category `Cat` of all categories. In this category objects are categories and morphisms are functors between these categories. ## Implementation notes Though `Cat` is not a concrete category, we use `bundled` to define its carrier type. -/ namespace category_theory /-- Category of categories. -/ def Cat := bundled category namespace Cat protected instance inhabited : Inhabited Cat := { default := bundled.mk (Type u) } protected instance has_coe_to_sort : has_coe_to_sort Cat := has_coe_to_sort.mk (Type u) bundled.α protected instance str (C : Cat) : category ↥C := bundled.str C /-- Construct a bundled `Cat` from the underlying type and the typeclass. -/ def of (C : Type u) [category C] : Cat := bundled.of C /-- Category structure on `Cat` -/ protected instance category : large_category Cat := category.mk /-- Functor that gets the set of objects of a category. It is not called `forget`, because it is not a faithful functor. -/ def objects : Cat ⥤ Type u := functor.mk (fun (C : Cat) => ↥C) fun (C D : Cat) (F : C ⟶ D) => functor.obj F /-- Any isomorphism in `Cat` induces an equivalence of the underlying categories. -/ def equiv_of_iso {C : Cat} {D : Cat} (γ : C ≅ D) : ↥C ≌ ↥D := equivalence.mk' (iso.hom γ) (iso.inv γ) (eq_to_iso sorry) (eq_to_iso (iso.inv_hom_id γ)) end Cat /-- Embedding `Type` into `Cat` as discrete categories. This ought to be modelled as a 2-functor! -/ @[simp] theorem Type_to_Cat_obj (X : Type u) : functor.obj Type_to_Cat X = Cat.of (discrete X) := Eq.refl (functor.obj Type_to_Cat X) protected instance Type_to_Cat.faithful : faithful Type_to_Cat := faithful.mk protected instance Type_to_Cat.full : full Type_to_Cat := full.mk fun (X Y : Type (max (max (max u_1 u_2 u_3 u_4) u_1 u_2 u_3) (max u_1 u_2 u_3 u_4) u_1 u_2)) (F : functor.obj Type_to_Cat X ⟶ functor.obj Type_to_Cat Y) => functor.obj F
2035f1936fad780da98c71fbd243c8bf20b9e7f4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/denoms_clearable_auto.lean
d8460df044a24e39f10f3b50bad3be01f1a870ad
[]
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
2,944
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.erase_lead import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Denominators of evaluation of polynomials at ratios Let `i : R → K` be a homomorphism of semirings. Assume that `K` is commutative. If `a` and `b` are elements of `R` such that `i b ∈ K` is invertible, then for any polynomial `f ∈ polynomial R` the "mathematical" expression `b ^ f.nat_degree * f (a / b) ∈ K` is in the image of the homomorphism `i`. -/ -- TODO: use hypothesis (ub : is_unit (i b)) to work with localizations. /-- `denoms_clearable` formalizes the property that `b ^ N * f (a / b)` does not have denominators, if the inequality `f.nat_degree ≤ N` holds. In the implementation, we also use provide an inverse in the existential. -/ def denoms_clearable {R : Type u_1} {K : Type u_2} [semiring R] [comm_semiring K] (a : R) (b : R) (N : ℕ) (f : polynomial R) (i : R →+* K) := ∃ (D : R), ∃ (bi : K), bi * coe_fn i b = 1 ∧ coe_fn i D = coe_fn i b ^ N * polynomial.eval (coe_fn i a * bi) (polynomial.map i f) theorem denoms_clearable_zero {R : Type u_1} {K : Type u_2} [semiring R] [comm_semiring K] {i : R →+* K} {b : R} {bi : K} (N : ℕ) (a : R) (bu : bi * coe_fn i b = 1) : denoms_clearable a b N 0 i := sorry theorem denoms_clearable_C_mul_X_pow {R : Type u_1} {K : Type u_2} [semiring R] [comm_semiring K] {i : R →+* K} {b : R} {bi : K} {N : ℕ} (a : R) (bu : bi * coe_fn i b = 1) {n : ℕ} (r : R) (nN : n ≤ N) : denoms_clearable a b N (coe_fn polynomial.C r * polynomial.X ^ n) i := sorry theorem denoms_clearable.add {R : Type u_1} {K : Type u_2} [semiring R] [comm_semiring K] {i : R →+* K} {a : R} {b : R} {N : ℕ} {f : polynomial R} {g : polynomial R} : denoms_clearable a b N f i → denoms_clearable a b N g i → denoms_clearable a b N (f + g) i := sorry theorem denoms_clearable_of_nat_degree_le {R : Type u_1} {K : Type u_2} [semiring R] [comm_semiring K] {i : R →+* K} {b : R} {bi : K} (N : ℕ) (a : R) (bu : bi * coe_fn i b = 1) (f : polynomial R) : polynomial.nat_degree f ≤ N → denoms_clearable a b N f i := sorry /-- If `i : R → K` is a ring homomorphism, `f` is a polynomial with coefficients in `R`, `a, b` are elements of `R`, with `i b` invertible, then there is a `D ∈ R` such that `b ^ f.nat_degree * f (a / b)` equals `i D`. -/ theorem denoms_clearable_nat_degree {R : Type u_1} {K : Type u_2} [semiring R] [comm_semiring K] {b : R} {bi : K} (i : R →+* K) (f : polynomial R) (a : R) (bu : bi * coe_fn i b = 1) : denoms_clearable a b (polynomial.nat_degree f) f i := denoms_clearable_of_nat_degree_le (polynomial.nat_degree f) a bu f le_rfl end Mathlib
3e6859066920df241c6f3ee2b8ab889b4ec43906
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/one_by_one_matrix.lean
34ae6d8f894b6a19da22efb3c366e54c6effc50c
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
1,253
lean
import .mat -- TODO: move lemma fin.eq_zero_fin1 (i : fin 1) : i = 0 := begin rw fin.eq_iff_veq, apply nat.eq_zero_of_le_zero (nat.le_of_lt_succ i.2) end namespace one_by_one_matrix /- def coe {α : Type*} : (matrix (fin 1) (fin 1) α) → α := λ A, A 0 0 instance coe_instance (α : Type*) : has_coe (matrix (fin 1) (fin 1) α) α := ⟨coe⟩ @[simp] lemma coe_add (α : Type*) [has_add α] (A B : matrix (fin 1) (fin 1) α) : coe (A + B) = coe A + coe B := by simp [coe] @[simp] lemma coe_smul (α : Type*) [has_mul α] (a : α) (A : matrix (fin 1) (fin 1) α) : coe (a • A) = a * coe A := by simp [coe, has_scalar.smul] @[simp] lemma coe_smul' (α : Type*) [has_mul α] (a : α) (A : matrix (fin 1) (fin 1) α) : coe (a • A) = a * coe A := by simp [coe, has_scalar.smul] @[simp] lemma coe_neg (α : Type*) [has_neg α] (A : matrix (fin 1) (fin 1) α) : coe (- A) = - coe A := by simp [coe] @[simp] lemma coe_zero (α : Type*) [has_zero α] : coe (0 : matrix (fin 1) (fin 1) α) = 0 := by simp [coe] -/ @[simp] lemma transpose (α : Type*) [ring α] (A : matrix (fin 1) (fin 1) α) : Aᵀ = A := begin ext i j, unfold matrix.transpose, rw [fin.eq_zero_fin1 i, fin.eq_zero_fin1 j] end end one_by_one_matrix
cc4551fabf09eb04f47e90b5ffc5ecfb5f0cac44
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/algebra/group.lean
790c98b66d8ef8337b2a74b2093b03dda7e6dd27
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,782
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. -/ import tactic.interactive data.option section pending_1857 /- Transport multiplicative to additive -/ section transport open tactic @[user_attribute] meta def to_additive_attr : user_attribute (name_map name) name := { name := `to_additive, descr := "Transport multiplicative to additive", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do val ← to_additive_attr.get_param n, pure $ dict.insert n val) mk_name_map, []⟩, parser := lean.parser.ident, after_set := some $ λ src _ _, do env ← get_env, dict ← to_additive_attr.get_cache, tgt ← to_additive_attr.get_param src, (get_decl tgt >> skip) <|> transport_with_dict dict src tgt } end transport /- map operations -/ attribute [to_additive has_add.add] has_mul.mul attribute [to_additive has_zero.zero] has_one.one attribute [to_additive has_neg.neg] has_inv.inv attribute [to_additive has_add] has_mul attribute [to_additive has_zero] has_one attribute [to_additive has_neg] has_inv /- map constructors -/ attribute [to_additive has_add.mk] has_mul.mk attribute [to_additive has_zero.mk] has_one.mk attribute [to_additive has_neg.mk] has_inv.mk /- map structures -/ attribute [to_additive add_semigroup] semigroup attribute [to_additive add_semigroup.mk] semigroup.mk attribute [to_additive add_semigroup.to_has_add] semigroup.to_has_mul attribute [to_additive add_semigroup.add_assoc] semigroup.mul_assoc attribute [to_additive add_semigroup.add] semigroup.mul attribute [to_additive add_comm_semigroup] comm_semigroup attribute [to_additive add_comm_semigroup.mk] comm_semigroup.mk attribute [to_additive add_comm_semigroup.to_add_semigroup] comm_semigroup.to_semigroup attribute [to_additive add_comm_semigroup.add_comm] comm_semigroup.mul_comm attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup attribute [to_additive add_left_cancel_semigroup.mk] left_cancel_semigroup.mk attribute [to_additive add_left_cancel_semigroup.to_add_semigroup] left_cancel_semigroup.to_semigroup attribute [to_additive add_left_cancel_semigroup.add_left_cancel] left_cancel_semigroup.mul_left_cancel attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup attribute [to_additive add_right_cancel_semigroup.mk] right_cancel_semigroup.mk attribute [to_additive add_right_cancel_semigroup.to_add_semigroup] right_cancel_semigroup.to_semigroup attribute [to_additive add_right_cancel_semigroup.add_right_cancel] right_cancel_semigroup.mul_right_cancel attribute [to_additive add_monoid] monoid attribute [to_additive add_monoid.mk] monoid.mk attribute [to_additive add_monoid.to_has_zero] monoid.to_has_one attribute [to_additive add_monoid.to_add_semigroup] monoid.to_semigroup attribute [to_additive add_monoid.add] monoid.mul attribute [to_additive add_monoid.add_assoc] monoid.mul_assoc attribute [to_additive add_monoid.zero] monoid.one attribute [to_additive add_monoid.zero_add] monoid.one_mul attribute [to_additive add_monoid.add_zero] monoid.mul_one attribute [to_additive add_comm_monoid] comm_monoid attribute [to_additive add_comm_monoid.mk] comm_monoid.mk attribute [to_additive add_comm_monoid.to_add_monoid] comm_monoid.to_monoid attribute [to_additive add_comm_monoid.to_add_comm_semigroup] comm_monoid.to_comm_semigroup attribute [to_additive add_group] group attribute [to_additive add_group.mk] group.mk attribute [to_additive add_group.to_has_neg] group.to_has_inv attribute [to_additive add_group.to_add_monoid] group.to_monoid attribute [to_additive add_group.add_left_neg] group.mul_left_inv attribute [to_additive add_group.add] group.mul attribute [to_additive add_group.add_assoc] group.mul_assoc attribute [to_additive add_group.zero] group.one attribute [to_additive add_group.zero_add] group.one_mul attribute [to_additive add_group.add_zero] group.mul_one attribute [to_additive add_group.neg] group.inv attribute [to_additive add_comm_group] comm_group attribute [to_additive add_comm_group.mk] comm_group.mk attribute [to_additive add_comm_group.to_add_group] comm_group.to_group attribute [to_additive add_comm_group.to_add_comm_monoid] comm_group.to_comm_monoid /- map theorems -/ attribute [to_additive add_assoc] mul_assoc attribute [to_additive add_semigroup_to_is_associative] semigroup_to_is_associative attribute [to_additive add_comm] mul_comm attribute [to_additive add_comm_semigroup_to_is_commutative] comm_semigroup_to_is_commutative attribute [to_additive add_left_comm] mul_left_comm attribute [to_additive add_right_comm] mul_right_comm attribute [to_additive add_left_cancel] mul_left_cancel attribute [to_additive add_right_cancel] mul_right_cancel attribute [to_additive add_left_cancel_iff] mul_left_cancel_iff attribute [to_additive add_right_cancel_iff] mul_right_cancel_iff attribute [to_additive zero_add] one_mul attribute [to_additive add_zero] mul_one attribute [to_additive add_left_neg] mul_left_inv attribute [to_additive neg_add_self] inv_mul_self attribute [to_additive neg_add_cancel_left] inv_mul_cancel_left attribute [to_additive neg_add_cancel_right] inv_mul_cancel_right attribute [to_additive neg_eq_of_add_eq_zero] inv_eq_of_mul_eq_one attribute [to_additive neg_zero] one_inv attribute [to_additive neg_neg] inv_inv attribute [to_additive add_right_neg] mul_right_inv attribute [to_additive add_neg_self] mul_inv_self attribute [to_additive neg_inj] inv_inj attribute [to_additive add_group.add_left_cancel] group.mul_left_cancel attribute [to_additive add_group.add_right_cancel] group.mul_right_cancel attribute [to_additive add_group.to_left_cancel_add_semigroup] group.to_left_cancel_semigroup attribute [to_additive add_group.to_right_cancel_add_semigroup] group.to_right_cancel_semigroup attribute [to_additive add_neg_cancel_left] mul_inv_cancel_left attribute [to_additive add_neg_cancel_right] mul_inv_cancel_right attribute [to_additive neg_add_rev] mul_inv_rev attribute [to_additive eq_neg_of_eq_neg] eq_inv_of_eq_inv attribute [to_additive eq_neg_of_add_eq_zero] eq_inv_of_mul_eq_one attribute [to_additive eq_add_neg_of_add_eq] eq_mul_inv_of_mul_eq attribute [to_additive eq_neg_add_of_add_eq] eq_inv_mul_of_mul_eq attribute [to_additive neg_add_eq_of_eq_add] inv_mul_eq_of_eq_mul attribute [to_additive add_neg_eq_of_eq_add] mul_inv_eq_of_eq_mul attribute [to_additive eq_add_of_add_neg_eq] eq_mul_of_mul_inv_eq attribute [to_additive eq_add_of_neg_add_eq] eq_mul_of_inv_mul_eq attribute [to_additive add_eq_of_eq_neg_add] mul_eq_of_eq_inv_mul attribute [to_additive add_eq_of_eq_add_neg] mul_eq_of_eq_mul_inv attribute [to_additive neg_add] mul_inv end pending_1857 universes u v variables {α : Type u} {β : Type v} def additive (α : Type*) := α def multiplicative (α : Type*) := α instance [semigroup α] : add_semigroup (additive α) := { add := ((*) : α → α → α), add_assoc := @mul_assoc _ _ } instance [add_semigroup α] : semigroup (multiplicative α) := { mul := ((+) : α → α → α), mul_assoc := @add_assoc _ _ } instance [comm_semigroup α] : add_comm_semigroup (additive α) := { add_comm := @mul_comm _ _, ..additive.add_semigroup } instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) := { mul_comm := @add_comm _ _, ..multiplicative.semigroup } instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) := { add_left_cancel := @mul_left_cancel _ _, ..additive.add_semigroup } instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) := { mul_left_cancel := @add_left_cancel _ _, ..multiplicative.semigroup } instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) := { add_right_cancel := @mul_right_cancel _ _, ..additive.add_semigroup } instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) := { mul_right_cancel := @add_right_cancel _ _, ..multiplicative.semigroup } @[simp, to_additive add_left_inj] theorem mul_left_inj [left_cancel_semigroup α] (a : α) {b c : α} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ @[simp, to_additive add_right_inj] theorem mul_right_inj [right_cancel_semigroup α] (a : α) {b c : α} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) namespace units variables [monoid α] {a b c : units α} instance : has_coe (units α) α := ⟨val⟩ @[extensionality] theorem ext : ∀ {a b : units α}, (a : α) = b → a = b | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := ⟨congr_arg _, ext⟩ instance [decidable_eq α] : decidable_eq (units α) | a b := decidable_of_iff' _ ext_iff protected def mul (u₁ u₂ : units α) : units α := ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, have u₁.val * (u₂.val * u₂.inv) * u₁.inv = 1, by rw [u₂.val_inv]; rw [mul_one, u₁.val_inv], by simpa only [mul_assoc], have u₂.inv * (u₁.inv * u₁.val) * u₂.val = 1, by rw [u₁.inv_val]; rw [mul_one, u₂.inv_val], by simpa only [mul_assoc]⟩ protected def inv' (u : units α) : units α := ⟨u.inv, u.val, u.inv_val, u.val_inv⟩ instance : has_mul (units α) := ⟨units.mul⟩ instance : has_one (units α) := ⟨⟨1, 1, mul_one 1, one_mul 1⟩⟩ instance : has_inv (units α) := ⟨units.inv'⟩ variables (a b) @[simp] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp] lemma coe_one : ((1 : units α) : α) = 1 := rfl lemma val_coe : (↑a : α) = a.val := rfl lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl @[simp] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[simp] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] instance : group (units α) := by refine {mul := (*), one := 1, inv := has_inv.inv, ..}; { intros, apply ext, simp only [coe_mul, coe_one, mul_assoc, one_mul, mul_one, inv_mul] } instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp] theorem mul_left_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp] theorem mul_right_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ end units theorem nat.units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[to_additive with_zero] def with_one (α) := option α @[to_additive with_zero.has_coe_t] instance : has_coe_t α (with_one α) := ⟨some⟩ instance [semigroup α] : monoid (with_one α) := { one := none, mul := option.lift_or_get (*), 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 } 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 instance [semigroup α] : mul_zero_class (with_zero α) := { zero := none, mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.add_monoid } 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 := some 1, 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.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } instance [monoid α] : add_monoid (additive α) := { zero := (1 : α), zero_add := @one_mul _ _, add_zero := @mul_one _ _, ..additive.add_semigroup } instance [add_monoid α] : monoid (multiplicative α) := { one := (0 : α), one_mul := @zero_add _ _, mul_one := @add_zero _ _, ..multiplicative.semigroup } section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_right_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_right_inj _ theorem divp_eq_one (a : α) (u : units α) : a /ₚ u = 1 ↔ a = u := (units.mul_right_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid 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 instance [comm_monoid α] : add_comm_monoid (additive α) := { add_comm := @mul_comm α _, ..additive.add_monoid } instance [add_comm_monoid α] : comm_monoid (multiplicative α) := { mul_comm := @add_comm α _, ..multiplicative.monoid } instance [group α] : add_group (additive α) := { neg := @has_inv.inv α _, add_left_neg := @mul_left_inv _ _, ..additive.add_monoid } instance [add_group α] : group (multiplicative α) := { inv := @has_neg.neg α _, mul_left_inv := @add_left_neg _ _, ..multiplicative.monoid } section group variables [group α] {a b c : α} instance : has_lift α (units α) := ⟨λ a, ⟨a, a⁻¹, mul_inv_self _, inv_mul_self _⟩⟩ @[simp, to_additive neg_inj'] theorem inv_inj' : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← inv_inv a, h, inv_inv], congr_arg _⟩ @[to_additive eq_of_neg_eq_neg] theorem eq_of_inv_eq_inv : a⁻¹ = b⁻¹ → a = b := inv_inj'.1 @[simp, to_additive add_self_iff_eq_zero] theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 := by have := @mul_left_inj _ _ a a 1; rwa mul_one at this @[simp, to_additive neg_eq_zero] theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← @inv_inj' _ _ a 1, one_inv] @[simp, to_additive neg_ne_zero] theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 := not_congr inv_eq_one @[to_additive left_inverse_neg] theorem left_inverse_inv (α) [group α] : function.left_inverse (λ a : α, a⁻¹) (λ a, a⁻¹) := assume a, inv_inv a attribute [simp] mul_inv_cancel_left add_neg_cancel_left mul_inv_cancel_right add_neg_cancel_right @[to_additive eq_neg_iff_eq_neg] theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ := ⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩ @[to_additive neg_eq_iff_neg_eq] theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a := by rw [eq_comm, @eq_comm _ _ a, eq_inv_iff_eq_inv] @[to_additive add_eq_zero_iff_eq_neg] theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ := by simpa [mul_left_inv, -mul_right_inj] using @mul_right_inj _ _ b a (b⁻¹) @[to_additive add_eq_zero_iff_neg_eq] theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b := by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm] @[to_additive eq_neg_iff_add_eq_zero] theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 := mul_eq_one_iff_eq_inv.symm @[to_additive neg_eq_iff_add_eq_zero] theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 := mul_eq_one_iff_inv_eq.symm @[to_additive eq_add_neg_iff_add_eq] theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive eq_neg_add_iff_add_eq] theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive neg_add_eq_iff_eq_add] theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive add_neg_eq_iff_eq_add] theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive add_neg_eq_zero] theorem mul_inv_eq_one {a b : α} : a * b⁻¹ = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inv] @[to_additive neg_comm_of_comm] theorem inv_comm_of_comm {a b : α} (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [inv_mul_cancel_left, mul_assoc, mul_inv_cancel_right] at this end end group instance [comm_group α] : add_comm_group (additive α) := { add_comm := @mul_comm α _, ..additive.add_group } instance [add_comm_group α] : comm_group (multiplicative α) := { mul_comm := @add_comm α _, ..multiplicative.group } section add_monoid variables [add_monoid α] {a b c : α} @[simp] lemma bit0_zero : bit0 (0 : α) = 0 := add_zero _ @[simp] lemma bit1_zero [has_one α] : bit1 (0 : α) = 1 := show 0+0+1=(1:α), by rw [zero_add, zero_add] end add_monoid section add_group variables [add_group α] {a b c : α} local attribute [simp] sub_eq_add_neg def sub_sub_cancel := @sub_sub_self @[simp] lemma sub_left_inj : a - b = a - c ↔ b = c := (add_left_inj _).trans neg_inj' @[simp] lemma sub_right_inj : b - a = c - a ↔ b = c := add_right_inj _ lemma sub_add_sub_cancel (a b c : α) : (a - b) + (b - c) = a - c := by rw [← add_sub_assoc, sub_add_cancel] lemma sub_sub_sub_cancel_right (a b c : α) : (a - c) - (b - c) = a - b := by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel] theorem sub_eq_zero : a - b = 0 ↔ a = b := ⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩ theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b := not_congr sub_eq_zero theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b := eq_add_neg_iff_add_eq theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b := add_neg_eq_iff_eq_add theorem eq_iff_eq_of_sub_eq_sub {a b c d : α} (H : a - b = c - d) : a = b ↔ c = d := by rw [← sub_eq_zero, H, sub_eq_zero] theorem left_inverse_sub_add_left (c : α) : function.left_inverse (λ x, x - c) (λ x, x + c) := assume x, add_sub_cancel x c theorem left_inverse_add_left_sub (c : α) : function.left_inverse (λ x, x + c) (λ x, x - c) := assume x, sub_add_cancel x c theorem left_inverse_add_right_neg_add (c : α) : function.left_inverse (λ x, c + x) (λ x, - c + x) := assume x, add_neg_cancel_left c x theorem left_inverse_neg_add_add_right (c : α) : function.left_inverse (λ x, - c + x) (λ x, c + x) := assume x, neg_add_cancel_left c x end add_group section add_comm_group variables [add_comm_group α] {a b c : α} lemma sub_eq_neg_add (a b : α) : a - b = -b + a := add_comm _ _ theorem neg_add' (a b : α) : -(a + b) = -a - b := neg_add a b lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b := by rw [eq_sub_iff_add_eq, add_comm] lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c := by rw [sub_eq_iff_eq_add, add_comm] lemma add_sub_cancel' (a b : α) : a + b - a = b := by rw [sub_eq_neg_add, neg_add_cancel_left] lemma add_sub_cancel'_right (a b : α) : a + (b - a) = b := by rw [← add_sub_assoc, add_sub_cancel'] lemma sub_right_comm (a b c : α) : a - b - c = a - c - b := add_right_comm _ _ _ lemma sub_add_sub_cancel' (a b c : α) : (a - b) + (c - a) = c - b := by rw add_comm; apply sub_add_sub_cancel lemma sub_sub_sub_cancel_left (a b c : α) : (c - a) - (c - b) = b - a := by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel] end add_comm_group section is_conj variables [group α] [group β] def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b @[refl] lemma is_conj_refl (a : α) : is_conj a a := ⟨1, by rw [one_mul, one_inv, mul_one]⟩ @[symm] lemma is_conj_symm (a b : α) : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩ @[trans] lemma is_conj_trans (a b c : α) : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩ @[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩ end is_conj class is_monoid_hom [monoid α] [monoid β] (f : α → β) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y}, f (x * y) = f x * f y) class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) : Prop := (map_zero : f 0 = 0) (map_add : ∀ {x y}, f (x + y) = f x + f y) attribute [to_additive is_add_monoid_hom] is_monoid_hom attribute [to_additive is_add_monoid_hom.map_add] is_monoid_hom.map_mul attribute [to_additive is_add_monoid_hom.mk] is_monoid_hom.mk namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] @[to_additive is_add_monoid_hom.id] instance id : is_monoid_hom (@id α) := by refine {..}; intros; refl @[to_additive is_add_monoid_hom.id] instance comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] : is_monoid_hom (g ∘ f) := { map_mul := λ x y, show g _ = g _ * g _, by rw [map_mul f, map_mul g], map_one := show g _ = 1, by rw [map_one f, map_one g] } end is_monoid_hom -- TODO rename fields of is_group_hom: mul ↝ map_mul? /-- Predicate for group homomorphism. -/ class is_group_hom [group α] [group β] (f : α → β) : Prop := (mul : ∀ a b : α, f (a * b) = f a * f b) class is_add_group_hom [add_group α] [add_group β] (f : α → β) : Prop := (add : ∀ a b, f (a + b) = f a + f b) attribute [to_additive is_add_group_hom] is_group_hom attribute [to_additive is_add_group_hom.add] is_group_hom.mul attribute [to_additive is_add_group_hom.mk] is_group_hom.mk namespace is_group_hom variables [group α] [group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.zero] theorem one : f 1 = 1 := mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul] @[to_additive is_add_group_hom.neg] theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← mul f, inv_mul_self, one f] @[to_additive is_add_group_hom.id] instance id : is_group_hom (@id α) := ⟨λ _ _, rfl⟩ @[to_additive is_add_group_hom.comp] instance comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) := ⟨λ x y, show g _ = g _ * g _, by rw [mul f, mul g]⟩ protected lemma is_conj (f : α → β) [is_group_hom f] {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨f c, by rw [← is_group_hom.mul f, ← is_group_hom.inv f, ← is_group_hom.mul f, hc]⟩ end is_group_hom /-- Predicate for group anti-homomorphism, or a homomorphism into the opposite group. -/ class is_group_anti_hom {β : Type*} [group α] [group β] (f : α → β) : Prop := (mul : ∀ a b : α, f (a * b) = f b * f a) namespace is_group_anti_hom variables [group α] [group β] (f : α → β) [w : is_group_anti_hom f] include w theorem one : f 1 = 1 := mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul] theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← mul f, mul_inv_self, one f] end is_group_anti_hom theorem inv_is_group_anti_hom [group α] : is_group_anti_hom (λ x : α, x⁻¹) := ⟨mul_inv_rev⟩ namespace is_add_group_hom variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] lemma sub (a b) : f (a - b) = f a - f b := calc f (a - b) = f (a + -b) : rfl ... = f a + f (-b) : add f _ _ ... = f a - f b : by simp[neg f] end is_add_group_hom namespace units variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] definition map : units α → units β := λ u, ⟨f u.val, f u.inv, by rw [← is_monoid_hom.map_mul f, u.val_inv, is_monoid_hom.map_one f], by rw [← is_monoid_hom.map_mul f, u.inv_val, is_monoid_hom.map_one f] ⟩ instance : is_group_hom (units.map f) := ⟨λ a b, by ext; exact is_monoid_hom.map_mul f ⟩ end units
6a520a02621fa46eab7b8c22839286c16cff09e7
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/lebesgue_measure.lean
fb0127b90ff55a1721ed912d509ff4cc2c18ab63
[ "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
12,254
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 Lebesgue measure on the real line -/ import measure_theory.measure_space import measure_theory.borel_space noncomputable theory open classical set filter open nnreal (of_real) namespace measure_theory /-- Length of an interval. This is the largest monotonic function which correctly measures all intervals. -/ def lebesgue_length (s : set ℝ) : ennreal := ⨅a b (h : s ⊆ Ico a b), of_real (b - a) @[simp] lemma lebesgue_length_empty : lebesgue_length ∅ = 0 := le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma lebesgue_length_Ico (a b : ℝ) : lebesgue_length (Ico a b) = of_real (b - a) := begin refine le_antisymm (infi_le_of_le a $ infi_le_of_le b $ infi_le _ (by refl)) (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, cases (Ico_subset_Ico_iff ab).1 h with h₁ h₂, exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_mono {s₁ s₂ : set ℝ} (h : s₁ ⊆ s₂) : lebesgue_length s₁ ≤ lebesgue_length s₂ := infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h', ⟨subset.trans h h', le_refl _⟩ lemma lebesgue_length_eq_infi_Ioo (s) : lebesgue_length s = ⨅a b (h : s ⊆ Ioo a b), of_real (b - a) := begin refine le_antisymm (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _, refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le (a - ε) (infi_le_of_le b $ infi_le_of_le (subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 ε0) _), rw [← sub_add, ← ennreal.coe_add, ennreal.coe_le_coe], apply le_trans nnreal.of_real_add_le _, simp, end @[simp] lemma lebesgue_length_Ioo (a b : ℝ) : lebesgue_length (Ioo a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _, rw lebesgue_length_eq_infi_Ioo (Ioo a b), refine (le_infi $ λ a', le_infi $ λ b', le_infi $ λ h, _), cases le_or_lt b a with ab ab, {simp [ab]}, cases (Ioo_subset_Ioo_iff ab).1 h with h₁ h₂, rw [lebesgue_length_Ico, ennreal.coe_le_coe], exact nnreal.of_real_le_of_real (sub_le_sub h₂ h₁) end lemma lebesgue_length_eq_infi_Icc (s) : lebesgue_length s = ⨅a b (h : s ⊆ Icc a b), of_real (b - a) := begin refine le_antisymm _ (infi_le_infi $ λ a, infi_le_infi $ λ b, infi_le_infi2 $ λ h, ⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩), refine le_infi (λ a, le_infi $ λ b, le_infi $ λ h, _), refine ennreal.le_of_forall_epsilon_le (λ ε ε0 _, _), refine infi_le_of_le a (infi_le_of_le (b + ε) $ infi_le_of_le (subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 ε0) _), rw [sub_eq_add_neg, add_right_comm, ←ennreal.coe_add, ennreal.coe_le_coe], apply le_trans nnreal.of_real_add_le, simp [sub_eq_add_neg] end @[simp] lemma lebesgue_length_Icc (a b : ℝ) : lebesgue_length (Icc a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self), rw lebesgue_length_eq_infi_Icc (Icc a b), exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp)) end /-- The Lebesgue outer measure, as an outer measure of ℝ. -/ def lebesgue_outer : outer_measure ℝ := outer_measure.of_function lebesgue_length lebesgue_length_empty lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≤ lebesgue_length s := outer_measure.of_function_le _ _ _ lemma lebesgue_length_subadditive {a b : ℝ} {c d : ℕ → ℝ} (ss : Icc a b ⊆ ⋃i, Ioo (c i) (d i)) : (of_real (b - a) : ennreal) ≤ ∑' i, of_real (d i - c i) := begin suffices : ∀ (s:finset ℕ) b (cv : Icc a b ⊆ ⋃ i ∈ (↑s:set ℕ), Ioo (c i) (d i)), (of_real (b - a) : ennreal) ≤ s.sum (λ i, of_real (d i - c i)), { rcases compact_Icc.elim_finite_subcover_image (λ (i : ℕ) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set ℕ), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]}, rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa [e]) }, clear ss b, refine λ s, finset.strong_induction_on s (λ s IH b cv, _), cases le_total b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), simp }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊢, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left' (IH _ (finset.erase_ssubset is) (c i) _)), { rw [← ennreal.coe_add, ennreal.coe_le_coe], refine le_trans (nnreal.of_real_le_of_real _) nnreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (le_of_lt bd) _ }, { rintro x ⟨h₁, h₂⟩, refine (cv ⟨h₁, le_trans h₂ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le h₂)) } end @[simp] lemma lebesgue_outer_Icc (a b : ℝ) : lebesgue_outer (Icc a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length) (le_infi $ λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ p:ℝ×ℝ, f i ⊆ Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ennreal) < lebesgue_length (f i) + ε' i, { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo}, simpa [infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hg i).2), exact lebesgue_length_subadditive (subset.trans hf $ Union_subset_Union $ λ i, (hg i).1) end @[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 := by simpa using lebesgue_outer_Icc a a @[simp] lemma lebesgue_outer_Ico (a b : ℝ) : lebesgue_outer (Ico a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ico; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @nnreal.of_real_add_le (b - a - ε) ε, rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_right_comm, ← lebesgue_outer_Icc a (b-ε), nnreal.of_real_coe] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Icc_subset_Ico_right $ (sub_lt_self_iff _).2 ε0) end @[simp] lemma lebesgue_outer_Ioo (a b : ℝ) : lebesgue_outer (Ioo a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Ioo; apply lebesgue_outer_le_length) (ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), have := @nnreal.of_real_add_le (b - a - ε) ε, rw [← ennreal.coe_le_coe, ennreal.coe_add, sub_add_cancel, sub_sub, ← lebesgue_outer_Ico (a+ε) b, nnreal.of_real_coe] at this, exact le_trans this (add_le_add_right' $ lebesgue_outer.mono $ Ico_subset_Ioo_left $ (lt_add_iff_pos_right _).2 ε0) end lemma is_lebesgue_measurable_Iio {c : ℝ} : lebesgue_outer.caratheodory.is_measurable (Iio c) := outer_measure.caratheodory_is_measurable $ λ t, le_infi $ λ a, le_infi $ λ b, le_infi $ λ h, begin refine le_trans (add_le_add' (lebesgue_length_mono $ inter_subset_inter_left _ h) (lebesgue_length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hca; cases le_total b c with hbc hcb; simp [*, -sub_eq_add_neg, sub_add_sub_cancel']; rw [← ennreal.coe_add, ennreal.coe_le_coe], { simp [*, -nnreal.of_real_add, nnreal.of_real_add_of_real, -sub_eq_add_neg, sub_add_sub_cancel'] }, { rw nnreal.of_real_of_nonpos, { simp }, exact sub_nonpos.2 (le_trans hbc hca) } end theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer := begin refine le_antisymm (λ s, _) (outer_measure.trim_ge _), rw outer_measure.trim_eq_infi, refine le_infi (λ f, le_infi $ λ hf, ennreal.le_of_forall_epsilon_le $ λ ε ε0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 ε0) ℕ with ⟨ε', ε'0, hε⟩, refine le_trans _ (add_le_add_left' (le_of_lt hε)), rw ← ennreal.tsum_add, choose g hg using show ∀ i, ∃ s, f i ⊆ s ∧ is_measurable s ∧ lebesgue_outer s ≤ lebesgue_length (f i) + of_real (ε' i), { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (ε'0 i))), conv at this {to_lhs, rw lebesgue_length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, h₂⟩, rw ← lebesgue_outer_Ico at h₂, exact ⟨_, h₁, is_measurable_Ico, le_of_lt $ by simpa using h₂⟩ }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (subset.trans hf $ Union_subset_Union (λ i, (hg i).1)) _, apply infi_le_of_le (is_measurable.Union (λ i, (hg i).2.1)) _, exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ λ i, (hg i).2.2) end /-- Lebesgue measure on the Borel sets The outer Lebesgue measure is the completion of this measure. (TODO: proof this) -/ instance : measure_space ℝ := ⟨{to_outer_measure := lebesgue_outer, m_Union := have borel ℝ ≤ lebesgue_outer.caratheodory, by rw real.borel_eq_generate_from_Iio_rat; refine measurable_space.generate_from_le _; simp [is_lebesgue_measurable_Iio] {contextual := tt}, λ f hf, lebesgue_outer.Union_eq_of_caratheodory (λ i, this _ (hf i)), trimmed := lebesgue_outer_trim }⟩ @[simp] theorem lebesgue_to_outer_measure : (measure_space.μ : measure ℝ).to_outer_measure = lebesgue_outer := rfl end measure_theory open measure_theory section volume open_locale interval theorem real.volume_val (s) : volume s = lebesgue_outer s := rfl local attribute [simp] real.volume_val @[simp] lemma real.volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp @[simp] lemma real.volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp @[simp] lemma real.volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp @[simp] lemma real.volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp @[simp] lemma real.volume_interval {a b : ℝ} : volume [a, b] = of_real (abs (b - a)) := begin rw [interval, real.volume_Icc], congr, exact max_sub_min_eq_abs _ _ end open metric lemma real.volume_lt_top_of_bounded {s : set ℝ} (h : bounded s) : volume s < ⊤ := begin rw [real.bounded_iff_bdd_below_bdd_above, bdd_below_bdd_above_iff_subset_interval] at h, rcases h with ⟨a, b, h⟩, calc volume s ≤ volume [a, b] : volume_mono h ... < ⊤ : by { rw real.volume_interval, exact ennreal.coe_lt_top } end lemma real.volume_lt_top_of_compact {s : set ℝ} (h : compact s) : volume s < ⊤ := real.volume_lt_top_of_bounded (bounded_of_compact h) end volume /- section vitali def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ∃ y ∈ Icc (0:ℝ) 1, ∃ q:ℚ, ↑q = x - y := ⟨x, h, 0, by simp⟩ def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ := classical.some (vitali_aux_h x h) theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 := Exists.fst (classical.some_spec (vitali_aux_h x h):_) theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ∃ q:ℚ, ↑q = x - vitali_aux x h := Exists.snd (classical.some_spec (vitali_aux_h x h):_) def vitali : set ℝ := {x | ∃ h, x = vitali_aux x h} theorem vitali_nonmeasurable : ¬ is_null_measurable measure_space.μ vitali := sorry end vitali -/
300078b1151c24158292be16ddf8157343b88fe4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/archimedean_auto.lean
0c64810b96d8c137d7bcf43ee39ba774b7d36e88
[]
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
2,098
lean
/- Copyright (c) 2020 Heather Macbeth, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.subgroup import Mathlib.algebra.archimedean import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Archimedean groups This file proves a few facts about ordered groups which satisfy the `archimedean` property, that is: `class archimedean (α) [ordered_add_comm_monoid α] : Prop :=` `(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n •ℕ y)` They are placed here in a separate file (rather than incorporated as a continuation of `algebra.archimedean`) because they rely on some imports from `group_theory` -- bundled subgroups in particular. The main result is `add_subgroup.cyclic_of_min`: a subgroup of a decidable archimedean abelian group is cyclic, if its set of positive elements has a minimal element. This result is used in this file to deduce `int.subgroup_cyclic`, proving that every subgroup of `ℤ` is cyclic. (There are several other methods one could use to prove this fact, including more purely algebraic methods, but none seem to exist in mathlib as of writing. The closest is `subgroup.is_cyclic`, but that has not been transferred to `add_subgroup`.) The result is also used in `topology.instances.real` as an ingredient in the classification of subgroups of `ℝ`. -/ /-- Given a subgroup `H` of a decidable linearly ordered archimedean abelian group `G`, if there exists a minimal element `a` of `H ∩ G_{>0}` then `H` is generated by `a`. -/ theorem add_subgroup.cyclic_of_min {G : Type u_1} [linear_ordered_add_comm_group G] [archimedean G] {H : add_subgroup G} {a : G} (ha : is_least (set_of fun (g : G) => g ∈ H ∧ 0 < g) a) : H = add_subgroup.closure (singleton a) := sorry /-- Every subgroup of `ℤ` is cyclic. -/ theorem int.subgroup_cyclic (H : add_subgroup ℤ) : ∃ (a : ℤ), H = add_subgroup.closure (singleton a) := sorry end Mathlib
38941336f499c32530147c715242198446a82858
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/ring_exp.lean
6d076b526409034a9ede963fe2b4409411e574cb
[ "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
56,181
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Tim Baanen. Solve equations in commutative (semi)rings with exponents. -/ import tactic.norm_num import control.traversable.basic /-! # `ring_exp` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`, something that the `ring` tactic cannot do, but `ring_exp` can. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ex` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The normalised version and normalisation proofs are also stored in the `ex` type. The outline of the file: - Define an inductive family of types `ex`, parametrised over `ex_type`, which can represent expressions with `+`, `*`, `^` and rational numerals. The parametrisation over `ex_type` ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ex` type, thus allowing us to map expressions to `ex` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `ex_type`) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - In the tactic, a normalized expression `ps : ex` lives in the meta-world, but the normalization proofs live in the real world. Thus, we cannot directly say `ps.orig = ps.pretty` anywhere, but we have to carefully construct the proof when we compute `ps`. This was a major source of bugs in development! - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. This is accomplished by the `in_exponent` function and is relatively painless since we work in a `reader` monad. - The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`. ## Caveats and future work Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring_exp` solves the goal, but `a / a := 1 by ring_exp` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ -- The base ring `α` will have a universe level `u`. -- We do not introduce `α` as a variable yet, -- in order to make it explicit or implicit as required. universes u namespace tactic.ring_exp open nat /-- The `atom` structure is used to represent atomic expressions: those which `ring_exp` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring_exp_eq` tactic does not normalize the subexpressions in atoms, but `ring_exp` does if `ring_exp_eq` was not sufficient. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ meta structure atom : Type := (value : expr) (index : ℕ) namespace atom /-- The `eq` operation on `atom`s works modulo definitional equality, ignoring their `value`s. The invariants on `atom` ensure indices are unique per value. Thus, `eq` indicates equality as long as the `atom`s come from the same context. -/ meta def eq (a b : atom) : bool := a.index = b.index /-- We order `atom`s on the order of appearance in the main expression. -/ meta def lt (a b : atom) : bool := a.index < b.index meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩ end atom section expression /-! ### `expression` section In this section, we define the `ex` type and its basic operations. First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`. For understanding the code, it's easier to check out `ex` itself first, then refer back to the supporting types. The arithmetic operations on `ex` need additional definitions, so they are defined in a later section. -/ /-- Coefficients in the expression are stored in a wrapper structure, allowing for easier modification of the data structures. The modifications might be caching of the result of `expr.of_rat`, or using a different meta representation of numerals. -/ @[derive decidable_eq, derive inhabited] structure coeff : Type := (value : ℚ) /-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/ @[derive decidable_eq, derive inhabited] inductive ex_type : Type | base : ex_type | sum : ex_type | prod : ex_type | exp : ex_type open ex_type /-- Each `ex` stores information for its normalization proof. The `orig` expression is the expression that was passed to `eval`. The `pretty` expression is the normalised form that the `ex` represents. (I didn't call this something like `norm`, because there are already too many things called `norm` in mathematics!) The field `proof` contains an optional proof term of type `%%orig = %%pretty`. The value `none` for the proof indicates that everything reduces to reflexivity. (Which saves space in quite a lot of cases.) -/ meta structure ex_info : Type := (orig : expr) (pretty : expr) (proof : option expr) /-- The `ex` type is an abstract representation of an expression with `+`, `*` and `^`. Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively. The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented by (something along the lines of) `sum 1 (sum 2 zero)`. The `coeff` constructor is the base case for `ex prod`, and is used for numerals. The code maintains the invariant that the coefficient is never `0`. The `var` constructor is the base case for `ex exp`, and is used for atoms. The `sum_b` constructor allows for addition in the base of an exponentiation; it serves a similar purpose as the parentheses in `(a + b)^c`. The code maintains the invariant that the argument to `sum_b` is not `zero` or `sum _ zero`. All of the constructors contain an `ex_info` field, used to carry around (arguments to) proof terms. While the `ex_type` parameter enforces some simplification invariants, the following ones must be manually maintained at the risk of insufficient power: - the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`) - the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`) - normalisation proofs of subexpressions must be `refl ps.pretty` - if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted according to the `lt` relation defined further down; similarly for `prod` and `coeff` (to ensure `a + b = b + a`). The first two invariants could be encoded in a subtype of `ex`, but aren't (yet) to spare some implementation burden. The other invariants cannot be encoded because we need the `tactic` monad to check them. (For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.) -/ meta inductive ex : ex_type → Type | zero (info : ex_info) : ex sum | sum (info : ex_info) : ex prod → ex sum → ex sum | coeff (info : ex_info) : coeff → ex prod | prod (info : ex_info) : ex exp → ex prod → ex prod | var (info : ex_info) : atom → ex base | sum_b (info : ex_info) : ex sum → ex base | exp (info : ex_info) : ex base → ex prod → ex exp /-- Return the proof information associated to the `ex`. -/ meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info | sum (ex.zero i) := i | sum (ex.sum i _ _) := i | prod (ex.coeff i _) := i | prod (ex.prod i _ _) := i | base (ex.var i _) := i | base (ex.sum_b i _) := i | exp (ex.exp i _ _) := i /-- Return the original, non-normalized version of this `ex`. Note that arguments to another `ex` are always "pre-normalized": their `orig` and `pretty` are equal, and their `proof` is reflexivity. -/ meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig /-- Return the normalized version of this `ex`. -/ meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty /-- Return the normalisation proof of the given expression. If the proof is `refl`, we give `none` instead, which helps to control the size of proof terms. To get an actual term, use `ex.proof_term`, or use `mk_proof` with the correct set of arguments. -/ meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof /-- Update the `orig` and `proof` fields of the `ex_info`. Intended for use in `ex.set_info`. -/ meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info := {orig := o.get_or_else i.pretty, proof := pf, .. i} /-- Update the `ex_info` of the given expression. We use this to combine intermediate normalisation proofs. Since `pretty` only depends on the subexpressions, which do not change, we do not set `pretty`. -/ meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et | sum (ex.zero i) o pf := ex.zero (i.set o pf) | sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps | prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x | prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps | base (ex.var i x) o pf := ex.var (i.set o pf) x | base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps | exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩ /-- Convert an `ex` to a `string`. -/ meta def ex.repr : Π {et : ex_type}, ex et → string | sum (ex.zero _) := "0" | sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps | prod (ex.coeff _ x) := repr x | prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps | base (ex.var _ x) := repr x | base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")" | exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩ /-- Equality test for expressions. Since equivalence of `atom`s is not the same as equality, we cannot make a true `(=)` operator for `ex` either. -/ meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool | sum (ex.zero _) (ex.zero _) := tt | sum (ex.zero _) (ex.sum _ _ _) := ff | sum (ex.sum _ _ _) (ex.zero _) := ff | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs | prod (ex.coeff _ x) (ex.coeff _ y) := x = y | prod (ex.coeff _ _) (ex.prod _ _ _) := ff | prod (ex.prod _ _ _) (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs | base (ex.var _ x) (ex.var _ y) := x.eq y | base (ex.var _ _) (ex.sum_b _ _) := ff | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs /-- The ordering on expressions. As for `ex.eq`, this is a linear order only in one context. -/ meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool | sum _ (ex.zero _) := ff | sum (ex.zero _) _ := tt | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs) | prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1 | prod (ex.coeff _ _) _ := tt | prod _ (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs) | base (ex.var _ x) (ex.var _ y) := x.lt y | base (ex.var _ _) (ex.sum_b _ _) := tt | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs) end expression section operations /-! ### `operations` section This section defines the operations (on `ex`) that use tactics. They live in the `ring_exp_m` monad, which adds a cache and a list of encountered atoms to the `tactic` monad. Throughout this section, we will be constructing proof terms. The lemmas used in the construction are all defined over a commutative semiring α. -/ variables {α : Type u} [comm_semiring α] open tactic open ex_type /-- Stores the information needed in the `eval` function and its dependencies, so they can (re)construct expressions. The `eval_info` structure stores this information for one type, and the `context` combines the two types, one for bases and one for exponents. -/ meta structure eval_info := (α : expr) (univ : level) -- Cache the instances for optimization and consistency (csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr) -- Optional instances (only required for (-) and (/) respectively) (ring_instance : option expr) (dr_instance : option expr) -- Cache common constants. (zero : expr) (one : expr) /-- The `context` contains the full set of information needed for the `eval` function. This structure has two copies of `eval_info`: one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`). When evaluating an exponent, we put `info_e` in `info_b`. -/ meta structure context := (info_b : eval_info) (info_e : eval_info) (transp : transparency) /-- The `ring_exp_m` monad is used instead of `tactic` to store the context. -/ @[derive [monad, alternative]] meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α /-- Access the instance cache. -/ meta def get_context : ring_exp_m context := reader_t.read /-- Lift an operation in the `tactic` monad to the `ring_exp_m` monad. This operation will not access the cache. -/ meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m) /-- Change the context of the given computation, so that expressions are evaluated in the exponent ring, instead of the base ring. -/ meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do ctx ← get_context, reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩ /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class f (ctx.info_b.csr_instance) args /-- Specialized version of `mk_app ``has_add.add`. Should be faster because it can use the cached instances. -/ meta def mk_add (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_add.add ctx.info_b.ha_instance args /-- Specialized version of `mk_app ``has_mul.mul`. Should be faster because it can use the cached instances. -/ meta def mk_mul (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_mul.mul ctx.info_b.hm_instance args /-- Specialized version of `mk_app ``has_pow.pow`. Should be faster because it can use the cached instances. -/ meta def mk_pow (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt ``has_pow.pow [ctx.info_b.univ, ctx.info_e.univ] ctx.info_b.α ctx.info_e.α ctx.info_b.hp_instance).mk_app args /-- Construct a normalization proof term or return the cached one. -/ meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr := match ps.proof with | none := lift $ tactic.mk_eq_refl ps.pretty | (some p) := pure p end /-- Construct a normalization proof term or return the cached one. -/ meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term /-- If all `ex_info` have trivial proofs, return a trivial proof. Otherwise, construct all proof terms. Useful in applications where trivial proofs combine to another trivial proof, most importantly to pass to `mk_proof_or_refl`. -/ meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr)) | [] := pure none | (x :: xs) := do xs_pfs ← none_or_proof_term xs, match (x.proof, xs_pfs) with | (none, none) := pure none | (some x_pf, none) := do xs_pfs ← traverse ex_info.proof_term xs, pure (some (x_pf :: xs_pfs)) | (_, some xs_pfs) := do x_pf ← x.proof_term, pure (some (x_pf :: xs_pfs)) end /-- Use the proof terms as arguments to the given lemma. If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.` -/ meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs' ← traverse ex_info.proof_term hs, mk_app_csr lem (args ++ hs') /-- Use the proof terms as arguments to the given lemma. Often, we construct a proof term using congruence where reflexivity suffices. To solve this, the following function tries to get away with reflexivity. -/ meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs_full ← none_or_proof_term hs, match hs_full with | none := lift $ mk_eq_refl term | (some hs') := mk_app_csr lem (args ++ hs') end /-- A shortcut for adding the original terms of two expressions. -/ meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_add [ps.orig, qs.orig] /-- A shortcut for multiplying the original terms of two expressions. -/ meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_mul [ps.orig, qs.orig] /-- A shortcut for exponentiating the original terms of two expressions. -/ meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_pow [ps.orig, qs.orig] /-- Congruence lemma for constructing `ex.sum`. -/ lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc /-- Congruence lemma for constructing `ex.prod`. -/ lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc /-- Congruence lemma for constructing `ex.exp`. -/ lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc /-- Constructs `ex.zero` with the correct arguments. -/ meta def ex_zero : ring_exp_m (ex sum) := do ctx ← get_context, pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩ /-- Constructs `ex.sum` with the correct arguments. -/ meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do pps_o ← add_orig p ps, pps_p ← mk_add [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``sum_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.coeff` with the correct arguments. There are more efficient constructors for specific numerals: if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`. -/ meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do ctx ← get_context, x_p ← lift $ expr.of_rat ctx.info_b.α x, pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩) /-- Constructs `ex.coeff 1` with the correct arguments. This is a special case for optimization purposes. -/ meta def ex_one : ring_exp_m (ex prod) := do ctx ← get_context, pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩ /-- Constructs `ex.prod` with the correct arguments. -/ meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do pps_o ← mul_orig p ps, pps_p ← mk_mul [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``prod_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.var` with the correct arguments. -/ meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p) /-- Constructs `ex.sum_b` with the correct arguments. -/ meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) := pure (ex.sum_b ps.info (ps.set_info none none)) /-- Constructs `ex.exp` with the correct arguments. -/ meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do ctx ← get_context, pps_o ← pow_orig p ps, pps_p ← mk_pow [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``exp_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp /-- Conversion from `ex base` to `ex exp`. -/ meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do o ← in_exponent $ ex_one, ps ← ex_exp p o, pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp /-- Conversion from `ex exp` to `ex prod`. -/ meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do o ← ex_one, ps ← ex_prod p o, pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp /-- Conversion from `ex prod` to `ex sum`. -/ meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do z ← ex_zero, ps ← ex_sum p z, pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp /-- A more efficient conversion from `atom` to `ex sum`. The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`, except we need to calculate less intermediate steps. -/ meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do p' ← ex_var p, o ← in_exponent $ ex_one, p' ← ex_exp p' o, o ← ex_one, p' ← ex_prod p' o, z ← ex_zero, p' ← ex_sum p' z, pf ← mk_proof ``atom_to_sum_pf [p.1] [], pure $ p'.set_info p.1 pf /-- Compute the sum of two coefficients. Note that the result might not be a valid expression: if `p = -q`, then the result should be `ex.zero : ex sum` instead. The caller must detect when this happens! The returned value is of the form `ex.coeff _ (p + q)`, with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`. -/ meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq_o ← mk_add [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o, pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩ lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p /-- Compute the product of two coefficients. The returned value is of the form `ex.coeff _ (p * q)`, with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`. -/ meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := match p.1, q.1 with -- Special case to speed up multiplication with 1. | ⟨1, 1, _, _⟩, _ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p], pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩ | _, ⟨1, 1, _, _⟩ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p], pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩ | _, _ := do ctx ← get_context, pq' ← mk_mul [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.eval_field pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ end /-- Represents the way in which two products are equal except coefficient. This type is used in the function `add_overlap`. In order to deal with equations of the form `a * 2 + a = 3 * a`, the `add` function will add up overlapping products, turning `a * 2 + a` into `a * 3`. We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this, and the `overlap` type carries the information on how it overlaps. The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`; the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a` (the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`); the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`. We distinguish those two cases because in the second, the whole product reduces to `0`. A potential extension to the tactic would also do this for the base of exponents, e.g. to show `2^n * 2^n = 4^n`. -/ meta inductive overlap : Type | none : overlap | nonzero : ex prod → overlap | zero : ex sum → overlap lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * pq : by rw pq_pf lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * 0 : by rw pq_pf ... = 0 : mul_zero _ /-- Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients). For other arguments, return `overlap.none`. -/ meta def add_overlap : ex prod → ex prod → ring_exp_m overlap | (ex.coeff x_i x) (ex.coeff y_i y) := do xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y | lift $ fail "internal error: add_coeff should return ex.coeff", if xy_c.1 = 0 then do z ← ex_zero, pure $ overlap.zero (z.set_info xy.orig xy.proof) else pure $ overlap.nonzero xy | (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none | (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none | pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q then do pq_ol ← add_overlap ps qs, pqs_o ← add_orig pps qqs, match pq_ol with | overlap.none := pure overlap.none | (overlap.nonzero pq) := do pqs ← ex_prod p pq, pf ← mk_proof ``add_overlap_pf [ps.pretty, qs.pretty, pq.pretty, p.pretty] [pq.info], pure $ overlap.nonzero (pqs.set_info pqs_o pf) | (overlap.zero pq) := do z ← ex_zero, pf ← mk_proof ``add_overlap_pf_zero [ps.pretty, qs.pretty, p.pretty] [pq.info], pure $ overlap.zero (z.set_info pqs_o pf) end else pure overlap.none section addition lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc ps + qs = 0 + qs' : by rw [ps_pf, qs_pf] ... = qs' : zero_add _ lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc ps + qs = ps' + 0 : by rw [ps_pf, qs_pf] ... = ps' : add_zero _ lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} : pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} : pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs := λ pps_pf qqs_pf pq_pf pqs_pf, calc pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf] ... = (p + q) + (ps + qs) : by cc ... = 0 + pqs : by rw [pq_pf, pqs_pf] ... = pqs : zero_add _ lemma add_pf_sum_lt {pps p ps qqs pqs : α} : pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc lemma add_pf_sum_gt {pps qqs q qs pqs : α} : qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc /-- Add two expressions. * `0 + qs = 0` * `ps + 0 = 0` * `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`) * `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`) * `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`) -/ meta def add : ex sum → ex sum → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ qs.set_info pqs_o pf | ps qs@(ex.zero qs_i) := do pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ ps.set_info pqs_o pf | pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do ol ← add_overlap p q, ppqqs_o ← add_orig pps qqs, match ol with | (overlap.nonzero pq) := do pqs ← add ps qs, pqqs ← ex_sum pq pqs, qqs_pf ← qqs.proof_term, pf ← mk_proof ``add_pf_sum_overlap [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf | (overlap.zero pq) := do pqs ← add ps qs, pf ← mk_proof ``add_pf_sum_overlap_zero [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqs.set_info ppqqs_o pf | overlap.none := if p.lt q then do pqs ← add ps qqs, ppqs ← ex_sum p pqs, pf ← mk_proof ``add_pf_sum_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← add pps qs, pqqs ← ex_sum q pqs, pf ← mk_proof ``add_pf_sum_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end end addition section multiplication lemma mul_pf_c_c {ps ps' qs qs' pq : α} : ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc lemma mul_pf_c_prod {ps qqs q qs pqs : α} : qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc lemma mul_pf_prod_c {pps p ps qs pqs : α} : pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} : pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs → p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs := λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} : pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} : qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc /-- Multiply two expressions. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (q * qs) = q * (qs * x)` (for `x` coefficient) * `(p * ps) * y = p * (ps * y)` (for `y` coefficient) * `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)` (if `p_e` and `q_e` are identical except coefficient) * `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`) * `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`) -/ meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do pq ← mul_coeff ps.pretty qs.pretty x y, pq_o ← mul_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c [ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do pqs ← mul_pp ps qs, pqqs ← ex_prod q pqs, pqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_c_prod [ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info pqqs_o pf | pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do pqs ← mul_pp ps qs, ppqs ← ex_prod p pqs, ppqs_o ← mul_orig pps qs, pf ← mk_proof ``mul_pf_prod_c [pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqs_o pf | pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do ppqqs_o ← mul_orig pps qqs, pq_ol ← in_exponent $ add_overlap p_e q_e, match pq_ol, p_b.eq q_b with | (overlap.nonzero pq_e), tt := do psqs ← mul_pp ps qs, pq ← ex_exp p_b pq_e, ppsqqs ← ex_prod pq psqs, pf ← mk_proof ``mul_pp_pf_overlap [pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty] [pps.info, qqs.info, ppsqqs.info], pure $ ppsqqs.set_info ppqqs_o pf | _, _ := if p.lt q then do pqs ← mul_pp ps qqs, ppqs ← ex_prod p pqs, pf ← mk_proof ``mul_pp_pf_prod_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← mul_pp pps qs, pqqs ← ex_prod q pqs, pf ← mk_proof ``mul_pp_pf_prod_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 := λ ps_pf, by rw [ps_pf, zero_mul] lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps → p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc pps * qs = (p + ps) * qs : by rw [pps_pf] ... = p * qs + ps * qs : add_mul _ _ _ ... = ppsqs : ppsqs_pf /-- Multiply two expressions. * `0 * qs = 0` * `(p + ps) * qs = (p * qs) + (ps * qs)` -/ meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info], pure $ z.set_info z_o pf | pps@(ex.sum pps_i p ps) qs := do pqs ← mul_pp p qs >>= prod_to_sum, psqs ← mul_p ps qs, ppsqs ← add pqs psqs, pps_pf ← pps.proof_term, ppsqs_o ← mul_orig pps qs, ppsqs_pf ← ppsqs.proof_term, pf ← mk_proof ``mul_p_pf_sum [pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty] [pps.info, ppsqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 := λ qs_pf, by rw [qs_pf, mul_zero] lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs → ps * qqs = psqqs := λ qs_pf psqqs_pf, calc ps * qqs = ps * (q + qs) : by rw [qs_pf] ... = ps * q + ps * qs : mul_add _ _ _ ... = psqqs : psqqs_pf /-- Multiply two expressions. * `ps * 0 = 0` * `ps * (q + qs) = (ps * q) + (ps * qs)` -/ meta def mul : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info], pure $ z.set_info z_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← mul_p ps q, psqs ← mul ps qs, psqqs ← add psq psqs, psqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_sum [ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end multiplication section exponentiation lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} : pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs := λ pps_pf psqs_pf, calc pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf] ... = p ^ (ps * qs) : symm (pow_mul _ _ _) ... = p ^ psqs : by rw [psqs_pf] /-- Compute the exponentiation of two coefficients. The returned value is of the form `ex.coeff _ (p ^ q)`, with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`. -/ meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq' ← mk_pow [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.eval_pow pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ /-- Exponentiate two expressions. * `(p ^ ps) ^ qs = p ^ (ps * qs)` -/ meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp) | pps@(ex.exp pps_i p ps) qs := do psqs ← in_exponent $ mul_pp ps qs, ppsqs ← ex_exp p psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_e_pf_exp [pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty] [pps.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 := λ ps_pf, by rw [ps_pf, one_pow] lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 := by simp; cc lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps → p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs := λ pps_pf pqs_pf psqs_pf, calc pps ^ qs = (p * ps) ^ qs : by rw [pps_pf] ... = p ^ qs * ps ^ qs : mul_pow _ _ _ ... = pqs * psqs : by rw [pqs_pf, psqs_pf] /-- Exponentiate two expressions. * `1 ^ qs = 1` * `x ^ qs = x ^ qs` (for `x` coefficient) * `(p * ps) ^ qs = p ^ qs + ps ^ qs` -/ meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info], pure $ o.set_info o_o pf | ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do pq ← pow_coeff ps.pretty qs.pretty x y, pq_o ← pow_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c [ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff ps_i x) qs := do ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b, pqs ← ex_exp ps'' qs, pqs_o ← pow_orig ps qs, pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c [ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pqs.info], pqs' ← exp_to_prod pqs, pure $ pqs'.set_info pqs_o pf | pps@(ex.prod pps_i p ps) qs := do pqs ← pow_e p qs, psqs ← pow_pp ps qs, ppsqs ← ex_prod pqs psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_pp_pf_prod [pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig] [pps.info, pqs.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' := λ ps_pf qs_pf, calc ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf] ... = ps' : pow_one _ lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 := λ ps_pf qs_pf, calc ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf] ... = 0 : zero_pow (succ_pos qs') lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} : qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs := λ qs_pf pqqs_pf, calc ps ^ qs = ps ^ succ qs' : by rw [qs_pf] ... = ps * ps ^ qs' : pow_succ _ _ ... = pqqs : by rw [pqqs_pf] lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} : pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs := λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf] lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc /-- Exponentiate two expressions. * `ps ^ 1 = ps` * `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`) * `(p + 0) ^ qs = p ^ qs` * `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`) * `ps ^ qs = ps ^ qs` (otherwise) -/ meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum) | ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do ps_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pure $ ps.set_info ps_o pf | ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do ctx ← get_context, z ← ex_zero, qs_pred ← lift $ expr.of_nat ctx.info_e.α y, pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info], z_o ← pow_orig ps qs, pure $ z.set_info z_o pf | pps@(ex.sum pps_i p (ex.zero _)) qqs := do pqs ← pow_pp p qqs, pqs_o ← pow_orig pps qqs, pf ← mk_proof ``pow_p_pf_singleton [pps.orig, p.pretty, pqs.pretty, qqs.orig] [pps.info, pqs.info], prod_to_sum $ pqs.set_info pqs_o pf | ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩, pqs ← pow_p ps qs', pqqs ← mul ps pqs, pqqs_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_succ [ps.orig, pqqs.pretty, qs.orig, qs'.pretty] [qs.info, pqqs.info], pure $ pqqs.set_info pqqs_o pf | pps qqs := do -- fallback: treat them as atoms pps' ← ex_sum_b pps, psqs ← ex_exp pps' qqs, psqs_o ← pow_orig pps qqs, pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons [pps.orig, pps.pretty, qqs.orig, qqs.pretty] [pps.info, qqs.info], exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc ps ^ qs = ps ^ 0 : by rw [qs_pf] ... = 1 : pow_zero _ lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs → ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf] ... = ps ^ q * ps ^ qs : pow_add _ _ _ ... = psqqs : psqqs_pf /-- Exponentiate two expressions. * `ps ^ 0 = 1` * `ps ^ (q + qs) = ps ^ q * ps ^ qs` -/ meta def pow : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info], prod_to_sum $ o.set_info o_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← pow_p ps q, psqs ← pow ps qs, psqqs ← mul psq psqs, psqqs_o ← pow_orig ps qqs, pf ← mk_proof ``pow_pf_sum [ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end exponentiation lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp /-- Give a simpler, more human-readable representation of the normalized expression. Normalized expressions might have the form `a^1 * 1 + 0`, since the dummy operations reduce special cases in pattern-matching. Humans prefer to read `a` instead. This tactic gets rid of the dummy additions, multiplications and exponentiations. -/ meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr) | sum pps@(ex.sum pps_i p (ex.zero _)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf] | sum (ex.sum pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_add [p_p, ps_p] <*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf] | prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := prod.mk pps.pretty <$> pps.proof_term | (some ringi) := do (p_p, p_pf) ← p.simple, prod.mk <$> lift (mk_app ``has_neg.neg [p_p]) <*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf] end | prod (ex.prod pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_mul [p_p, ps_p] <*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | base (ex.sum_b pps_i ps) := ps.simple | exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf] | exp (ex.exp pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← in_exponent $ ps.simple, prod.mk <$> mk_pow [p_p, ps_p] <*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | et ps := prod.mk ps.pretty <$> ps.proof_term /-- Performs a lookup of the atom `a` in the list of known atoms, or allocates a new one. If `a` is not definitionally equal to any of the list's entries, a new atom is appended to the list and returned. The index of this atom is kept track of in the second inductive argument. This function is mostly useful in `resolve_atom`, which updates the state with the new list of atoms. -/ meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom) | [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm]) | bas@(b :: as) n := do ctx ← get_context, (lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do (atm, as') ← resolve_atom_aux as (succ n), pure (atm, b :: as') /-- Convert the expression to an atom: either look up a definitionally equal atom, or allocate it as a new atom. You probably want to use `eval_base` if `eval` doesn't work instead of directly calling `resolve_atom`, since `eval_base` can also handle numerals. -/ meta def resolve_atom (a : expr) : ring_exp_m atom := do atoms ← reader_t.lift $ state_t.get, (atm, atoms') ← resolve_atom_aux a atoms 0, reader_t.lift $ state_t.put atoms', pure atm /-- Treat the expression atomically: as a coefficient or atom. Handles cases where `eval` cannot treat the expression as a known operation because it is just a number or single variable. -/ meta def eval_base (ps : expr) : ring_exp_m (ex sum) := match ps.to_rat with | some ⟨0, 1, _, _⟩ := ex_zero | some x := ex_coeff x >>= prod_to_sum | none := do a ← resolve_atom ps, atom_to_sum a end lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp /-- Negate an expression by multiplying with `-1`. Only works if there is a `ring` instance; otherwise it will `fail`. -/ meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := lift $ fail "internal error: negate called in semiring" | (some ring_instance) := do minus_one ← ex_coeff (-1) >>= prod_to_sum, ps' ← mul minus_one ps, ps_pf ← ps'.proof_term, pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf], ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig], pure $ ps'.set_info ps'_o pf end lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} : ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' := by cc /-- Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom. Only works if there is a `division_ring` instance; otherwise it will `fail`. -/ meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only supported in a division ring" | (some dri) := pure dri end, (ps_simple, ps_simple_pf) ← ps.simple, e ← lift $ mk_app ``has_inv.inv [ps_simple], (e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)), e'' ← eval_base e', ps_pf ← ps.proof_term, e''_pf ← e''.proof_term, pf ← mk_app_class ``inverse_pf dri [ ps.orig, ps.pretty, ps_simple, e', e''.pretty, ps_pf, ps_simple_pf, e_pf, e''_pf], e''_o ← lift $ mk_app ``has_inv.inv [ps.orig], pure $ e''.set_info e''_o pf lemma sub_pf {α} [ring α] {ps qs psqs : α} : ps + -qs = psqs → ps - qs = psqs := id lemma div_pf {α} [division_ring α] {ps qs psqs : α} : ps * qs⁻¹ = psqs → ps / qs = psqs := id end operations section wiring /-! ### `wiring` section This section deals with going from `expr` to `ex` and back. The main attraction is `eval`, which uses `add`, `mul`, etc. to calculate an `ex` from a given `expr`. Other functions use `ex`es to produce `expr`s together with a proof, or produce the context to run `ring_exp_m` from an `expr`. -/ open tactic open ex_type /-- Compute a normalized form (of type `ex`) from an expression (of type `expr`). This is the main driver of the `ring_exp` tactic, calling out to `add`, `mul`, `pow`, etc. to parse the `expr`. -/ meta def eval : expr → ring_exp_m (ex sum) | e@`(%%ps + %%qs) := do ps' ← eval ps, qs' ← eval qs, add ps' qs' | e@`(%%ps - %%qs) := (do ctx ← get_context, ri ← match ctx.info_b.ring_instance with | none := lift $ fail "subtraction is not directly supported in a semiring" | (some ri) := pure ri end, ps' ← eval ps, qs' ← eval qs >>= negate, psqs ← add ps' qs', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(- %%ps) := do ps' ← eval ps, negate ps' <|> eval_base e | e@`(%%ps * %%qs) := do ps' ← eval ps, qs' ← eval qs, mul ps' qs' | e@`(has_inv.inv %%ps) := do ps' ← eval ps, inverse ps' <|> eval_base e | e@`(%%ps / %%qs) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only directly supported in a division ring" | (some dri) := pure dri end, ps' ← eval ps, qs' ← eval qs, (do qs'' ← inverse qs', psqs ← mul ps' qs'', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do ps' ← eval ps, qs' ← in_exponent $ eval qs, psqs ← pow ps' qs', psqs_pf ← psqs.proof_term, (do has_pow_pf ← match hp_instance with | `(monoid.has_pow) := lift $ mk_eq_refl e | _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow" end, pf ← lift $ mk_eq_trans has_pow_pf psqs_pf, pure $ psqs.set_info e pf) <|> eval_base e | ps := eval_base ps /-- Run `eval` on the expression and return the result together with normalization proof. See also `eval_simple` if you want something that behaves like `norm_num`. -/ meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do e' ← eval e, prod.mk e' <$> e'.proof_term /-- Run `eval` on the expression and simplify the result. Returns a simplified normalized expression, together with an equality proof. See also `eval_with_proof` if you just want to check the equality of two expressions. -/ meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do (complicated, complicated_pf) ← eval_with_proof e, (simple, simple_pf) ← complicated.simple, prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf) /-- Compute the `eval_info` for a given type `α`. -/ meta def make_eval_info (α : expr) : tactic eval_info := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance, ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none), dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none), ha_instance ← mk_app ``has_add [α] >>= mk_instance, hm_instance ← mk_app ``has_mul [α] >>= mk_instance, hp_instance ← mk_mapp ``monoid.has_pow [some α, none], z ← mk_mapp ``has_zero.zero [α, none], o ← mk_mapp ``has_one.one [α, none], pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩ /-- Use `e` to build the context for running `mx`. -/ meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do info_b ← infer_type e >>= make_eval_info, info_e ← mk_const ``nat >>= make_eval_info, (λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) []) /-- Repeatedly apply `eval_simple` on (sub)expressions. -/ meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do (_, e', pf') ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (e'', pf) ← run_ring_exp transp e $ eval_simple e, guard (¬ e'' =ₐ e), return ((), e'', some pf, ff)) (λ _ _ _ _ _, failed) `eq e, pure (e', pf') end wiring end tactic.ring_exp namespace tactic.interactive open interactive interactive.types lean.parser tactic tactic.ring_exp local postfix `?`:9001 := optional /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. This version of `ring_exp` fails if the target is not an equality. The variant `ring_exp_eq!` will use a more aggressive reducibility setting to determine equality of atoms. -/ meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do `(eq %%ps %%qs) ← target >>= whnf, let transp := if red.is_some then semireducible else reducible, ((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $ prod.mk <$> eval_with_proof ps <*> eval_with_proof qs, if ps'.eq qs' then do qs_pf_inv ← mk_eq_symm qs_pf, pf ← mk_eq_trans ps_pf qs_pf_inv, tactic.interactive.exact ``(%%pf) else fail "ring_exp failed to prove equality" /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. This tactic extends `ring`: it should solve every goal that `ring` can solve. Additionally, it knows how to evaluate expressions with complicated exponents (where `ring` only understands constant exponents). The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine equality of atoms. For example: ```lean example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp example (x y : ℕ) : x + id y = y + id x := by ring_exp! ``` -/ meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := ring_exp_eq red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp) ns loc.include_goal | fail "ring_exp failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "ring_exp", category := doc_category.tactic, decl_names := [`tactic.interactive.ring_exp], tags := ["arithmetic", "simplification", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive open tactic tactic.interactive (ring_exp_eq) open tactic.ring_exp (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring_exp`. -/ meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring_exp_eq red) <|> replace_lhs (normalize transp) <|> fail "ring_exp failed to simplify" end conv.interactive
03ef9474925d9336263060eecd077530c7b176e1
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/lie/universal_enveloping.lean
5e393221611aa6b8c7bf1bdeebae4c59901f7628
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,709
lean
/- Copyright (c) 2020 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 algebra.ring_quot import linear_algebra.tensor_algebra /-! # Universal enveloping algebra Given a commutative ring `R` and a Lie algebra `L` over `R`, we construct the universal enveloping algebra of `L`, together with its universal property. ## Main definitions * `universal_enveloping_algebra`: the universal enveloping algebra, endowed with an `R`-algebra structure. * `universal_enveloping_algebra.ι`: the Lie algebra morphism from `L` to its universal enveloping algebra. * `universal_enveloping_algebra.lift`: given an associative algebra `A`, together with a Lie algebra morphism `f : L →ₗ⁅R⁆ A`, `lift R L f : universal_enveloping_algebra R L →ₐ[R] A` is the unique morphism of algebras through which `f` factors. * `universal_enveloping_algebra.ι_comp_lift`: states that the lift of a morphism is indeed part of a factorisation. * `universal_enveloping_algebra.lift_unique`: states that lifts of morphisms are indeed unique. * `universal_enveloping_algebra.hom_ext`: a restatement of `lift_unique` as an extensionality lemma. ## Tags lie algebra, universal enveloping algebra, tensor algebra -/ universes u₁ u₂ u₃ variables (R : Type u₁) (L : Type u₂) variables [comm_ring R] [lie_ring L] [lie_algebra R L] local notation `ιₜ` := tensor_algebra.ι R namespace universal_enveloping_algebra /-- The quotient by the ideal generated by this relation is the universal enveloping algebra. Note that we have avoided using the more natural expression: | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆) ⁅ιₜ x, ιₜ y⁆ so that our construction needs only the semiring structure of the tensor algebra. -/ inductive rel : tensor_algebra R L → tensor_algebra R L → Prop | lie_compat (x y : L) : rel (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) ((ιₜ x) * (ιₜ y)) end universal_enveloping_algebra /-- The universal enveloping algebra of a Lie algebra. -/ @[derive [inhabited, semiring, algebra R]] def universal_enveloping_algebra := ring_quot (universal_enveloping_algebra.rel R L) namespace universal_enveloping_algebra instance : ring (universal_enveloping_algebra R L) := algebra.semiring_to_ring R /-- The quotient map from the tensor algebra to the universal enveloping algebra as a morphism of associative algebras. -/ def mk_alg_hom : tensor_algebra R L →ₐ[R] universal_enveloping_algebra R L := ring_quot.mk_alg_hom R (rel R L) variables {L} /-- The natural Lie algebra morphism from a Lie algebra to its universal enveloping algebra. -/ def ι : L →ₗ⁅R⁆ universal_enveloping_algebra R L := { map_lie := λ x y, by { suffices : mk_alg_hom R L (ιₜ ⁅x, y⁆ + (ιₜ y) * (ιₜ x)) = mk_alg_hom R L ((ιₜ x) * (ιₜ y)), { rw alg_hom.map_mul at this, simp [lie_ring.of_associative_ring_bracket, ← this], }, exact ring_quot.mk_alg_hom_rel _ (rel.lie_compat x y), }, ..(mk_alg_hom R L).to_linear_map.comp ιₜ } variables {A : Type u₃} [ring A] [algebra R A] (f : L →ₗ⁅R⁆ A) /-- The universal property of the universal enveloping algebra: Lie algebra morphisms into associative algebras lift to associative algebra morphisms from the universal enveloping algebra. -/ def lift : universal_enveloping_algebra R L →ₐ[R] A := ring_quot.lift_alg_hom R (tensor_algebra.lift R (f : L →ₗ[R] A)) begin intros a b h, induction h with x y, simp [lie_ring.of_associative_ring_bracket], end @[simp] lemma lift_ι_apply (x : L) : lift R f (ι R x) = f x := begin have : ι R x = ring_quot.mk_alg_hom R (rel R L) (ιₜ x), by refl, simp [this, lift], end lemma ι_comp_lift : (lift R f) ∘ (ι R) = f := by { ext, simp, } lemma lift_unique (g : universal_enveloping_algebra R L →ₐ[R] A) : g ∘ (ι R) = f ↔ g = lift R f := begin split; intros h, { apply ring_quot.lift_alg_hom_unique, rw ← tensor_algebra.lift_unique, ext x, change _ = f x, rw ← congr h rfl, refl, }, { subst h, apply ι_comp_lift, }, end @[ext] lemma hom_ext {g₁ g₂ : universal_enveloping_algebra R L →ₐ[R] A} (h : g₁ ∘ (ι R) = g₂ ∘ (ι R)) : g₁ = g₂ := begin let f₁ := (lie_algebra.of_associative_algebra_hom g₁).comp (ι R), let f₂ := (lie_algebra.of_associative_algebra_hom g₂).comp (ι R), have h' : f₁ = f₂, { ext, exact congr h rfl, }, have h₁ : g₁ = lift R f₁, { rw ← lift_unique, refl, }, have h₂ : g₂ = lift R f₂, { rw ← lift_unique, refl, }, rw [h₁, h₂, h'], end end universal_enveloping_algebra
7374c68f8fe9738cdc809201bc24a433b733825a
618003631150032a5676f229d13a079ac875ff77
/src/data/list/basic.lean
727e564db2e978876e1ac2ef6f09ca323c8a20e5
[ "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
154,468
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import algebra.group import deprecated.group import data.nat.basic /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma injective_length_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma injective_length [subsingleton α] : injective (length : list α → ℕ) := injective_length_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := left_inverse.injective reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-! ### is_nil -/ lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] := list.cases_on l (by simp [is_nil]) (by simp [is_nil]) /-! ### last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl /-! ### sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /-! ### nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem injective_map_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } end monoid @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_add_right (le_refl _) }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] /-! ### join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /-! ### all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /-! ### count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /-! ### prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix theorem tail_subset (l : list α) : tail l ⊆ l := (sublist_of_suffix (tail_suffix l)).subset theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /-! ### sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /-! ### sublists_len -/ /-- Auxiliary function to construct the list of all sublists of a given length. Given an integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) /-- The list of all sublists of a list `l` that are of length `n`. For instance, for `l = [0, 1, 2, 3]` and `n = 2`, one gets `[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/ def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact (sublists_len_sublist_sublists' _ _).append ((sublists_len_sublist_sublists' _ _).map _) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact IH.append ((IHn s).map _) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 ((sublists_len_sublist_sublists' _ _).subset h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /-! ### permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /-! ### insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /-! ### sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /-! ### union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /-! ### inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter section choose variables (p : α → Prop) [decidable_pred p] (l : list α) 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 -- A jumble of lost lemmas: theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r end list
836f04a2832c15ac94557382f5b2e2b374333735
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/colimit_limit.lean
b1d32734fa1c3797a9d83a0c8de4f0693df5f306
[ "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
3,377
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.types import category_theory.currying /-! # The morphism comparing a colimit of limits with the corresponding limit of colimits. For `F : J × K ⥤ C` there is always a morphism $\colim_k \lim_j F(j,k) → \lim_j \colim_k F(j, k)$. While it is not usually an isomorphism, with additional hypotheses on `J` and `K` it may be, in which case we say that "colimits commute with limits". The prototypical example, proved in `category_theory.limits.filtered_colimit_commutes_finite_limit`, is that when `C = Type`, filtered colimits commute with finite limits. ## References * Borceux, Handbook of categorical algebra 1, Section 2.13 * [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W) -/ universes v u open category_theory namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables (F : J × K ⥤ C) open category_theory.prod lemma map_id_left_eq_curry_map {j : J} {k k' : K} {f : k ⟶ k'} : F.map ((𝟙 j, f) : (j, k) ⟶ (j, k')) = ((curry.obj F).obj j).map f := rfl lemma map_id_right_eq_curry_swap_map {j j' : J} {f : j ⟶ j'} {k : K} : F.map ((f, 𝟙 k) : (j, k) ⟶ (j', k)) = ((curry.obj (swap K J ⋙ F)).obj k).map f := rfl variables [has_limits_of_shape J C] variables [has_colimits_of_shape K C] /-- The universal morphism $\colim_k \lim_j F(j,k) → \lim_j \colim_k F(j, k)$. -/ noncomputable def colimit_limit_to_limit_colimit : colimit ((curry.obj (swap K J ⋙ F)) ⋙ lim) ⟶ limit ((curry.obj F) ⋙ colim) := limit.lift ((curry.obj F) ⋙ colim) { X := _, π := { app := λ j, colimit.desc ((curry.obj (swap K J ⋙ F)) ⋙ lim) { X := _, ι := { app := λ k, limit.π ((curry.obj (swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k, naturality' := begin dsimp, intros k k' f, simp only [functor.comp_map, curry.obj_map_app, limits.limit.map_π_assoc, swap_map, category.comp_id, map_id_left_eq_curry_map, colimit.w], end }, }, naturality' := begin dsimp, intros j j' f, ext k, simp only [limits.colimit.ι_map, curry.obj_map_app, limits.colimit.ι_desc_assoc, limits.colimit.ι_desc, category.id_comp, category.assoc, map_id_right_eq_curry_swap_map, limit.w_assoc], end } } /-- Since `colimit_limit_to_limit_colimit` is a morphism from a colimit to a limit, this lemma characterises it. -/ @[simp] lemma ι_colimit_limit_to_limit_colimit_π (j) (k) : colimit.ι _ k ≫ colimit_limit_to_limit_colimit F ≫ limit.π _ j = limit.π ((curry.obj (swap K J ⋙ F)).obj k) j ≫ colimit.ι ((curry.obj F).obj j) k := by { dsimp [colimit_limit_to_limit_colimit], simp, } @[simp] lemma ι_colimit_limit_to_limit_colimit_π_apply (F : J × K ⥤ Type v) (j) (k) (f) : limit.π ((curry.obj F) ⋙ colim) j (colimit_limit_to_limit_colimit F (colimit.ι ((curry.obj (swap K J ⋙ F)) ⋙ lim) k f)) = colimit.ι ((curry.obj F).obj j) k (limit.π ((curry.obj (swap K J ⋙ F)).obj k) j f) := by { dsimp [colimit_limit_to_limit_colimit], simp, } end category_theory.limits
9f6a731e7813147f42ea007fa27a3df8dc89cf9e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/cone/basic.lean
3feb656d347f0211c3cb34e03ee3320aef3a4aeb
[ "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
29,613
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Frédéric Dupuis -/ import analysis.convex.hull import data.real.basic import linear_algebra.linear_pmap /-! # Convex cones > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In a `𝕜`-module `E`, we define a convex cone as a set `s` such that `a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form a `complete_lattice`, and define their images (`convex_cone.map`) and preimages (`convex_cone.comap`) under linear maps. We define pointed, blunt, flat and salient cones, and prove the correspondence between convex cones and ordered modules. We define `convex.to_cone` to be the minimal cone that includes a given convex set. ## Main statements We prove two extension theorems: * `riesz_extension`: [M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E` such that `p + s = E`, and `f` is a linear function `p → ℝ` which is nonnegative on `p ∩ s`, then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. * `exists_extension_of_le_sublinear`: Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x` We prove the following theorems: * `convex_cone.hyperplane_separation_of_nonempty_of_is_closed_of_nmem`: This variant of the [hyperplane separation theorem](https://en.wikipedia.org/wiki/Hyperplane_separation_theorem) states that given a nonempty, closed, convex cone `K` in a complete, real inner product space `H` and a point `b` disjoint from it, there is a vector `y` which separates `b` from `K` in the sense that for all points `x` in `K`, `0 ≤ ⟪x, y⟫_ℝ` and `⟪y, b⟫_ℝ < 0`. This is also a geometric interpretation of the [Farkas lemma](https://en.wikipedia.org/wiki/Farkas%27_lemma#Geometric_interpretation). * `convex_cone.inner_dual_cone_of_inner_dual_cone_eq_self`: ## Implementation notes While `convex 𝕜` is a predicate on sets, `convex_cone 𝕜 E` is a bundled convex cone. ## References * https://en.wikipedia.org/wiki/Convex_cone * [Stephen P. Boyd and Lieven Vandenberghe, *Convex Optimization*][boydVandenberghe2004] * [Emo Welzl and Bernd Gärtner, *Cone Programming*][welzl_garter] -/ assert_not_exists normed_space open set linear_map open_locale classical pointwise variables {𝕜 E F G : Type*} /-! ### Definition of `convex_cone` and basic properties -/ section definitions variables (𝕜 E) [ordered_semiring 𝕜] /-- A convex cone is a subset `s` of a `𝕜`-module such that `a • x + b • y ∈ s` whenever `a, b > 0` and `x, y ∈ s`. -/ structure convex_cone [add_comm_monoid E] [has_smul 𝕜 E] := (carrier : set E) (smul_mem' : ∀ ⦃c : 𝕜⦄, 0 < c → ∀ ⦃x : E⦄, x ∈ carrier → c • x ∈ carrier) (add_mem' : ∀ ⦃x⦄ (hx : x ∈ carrier) ⦃y⦄ (hy : y ∈ carrier), x + y ∈ carrier) end definitions variables {𝕜 E} namespace convex_cone section ordered_semiring variables [ordered_semiring 𝕜] [add_comm_monoid E] section has_smul variables [has_smul 𝕜 E] (S T : convex_cone 𝕜 E) instance : set_like (convex_cone 𝕜 E) E := { coe := carrier, coe_injective' := λ S T h, by cases S; cases T; congr' } @[simp] lemma coe_mk {s : set E} {h₁ h₂} : ↑(@mk 𝕜 _ _ _ _ s h₁ h₂) = s := rfl @[simp] lemma mem_mk {s : set E} {h₁ h₂ x} : x ∈ @mk 𝕜 _ _ _ _ s h₁ h₂ ↔ x ∈ s := iff.rfl /-- Two `convex_cone`s are equal if they have the same elements. -/ @[ext] theorem ext {S T : convex_cone 𝕜 E} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h lemma smul_mem {c : 𝕜} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S := S.smul_mem' hc hx lemma add_mem ⦃x⦄ (hx : x ∈ S) ⦃y⦄ (hy : y ∈ S) : x + y ∈ S := S.add_mem' hx hy instance : add_mem_class (convex_cone 𝕜 E) E := { add_mem := λ c a b ha hb, add_mem c ha hb } instance : has_inf (convex_cone 𝕜 E) := ⟨λ S T, ⟨S ∩ T, λ c hc x hx, ⟨S.smul_mem hc hx.1, T.smul_mem hc hx.2⟩, λ x hx y hy, ⟨S.add_mem hx.1 hy.1, T.add_mem hx.2 hy.2⟩⟩⟩ @[simp] lemma coe_inf : ((S ⊓ T : convex_cone 𝕜 E) : set E) = ↑S ∩ ↑T := rfl lemma mem_inf {x} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl instance : has_Inf (convex_cone 𝕜 E) := ⟨λ S, ⟨⋂ s ∈ S, ↑s, λ c hc x hx, mem_bInter $ λ s hs, s.smul_mem hc $ mem_Inter₂.1 hx s hs, λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (mem_Inter₂.1 hx s hs) (mem_Inter₂.1 hy s hs)⟩⟩ @[simp] lemma coe_Inf (S : set (convex_cone 𝕜 E)) : ↑(Inf S) = ⋂ s ∈ S, (s : set E) := rfl lemma mem_Inf {x : E} {S : set (convex_cone 𝕜 E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_Inter₂ @[simp] lemma coe_infi {ι : Sort*} (f : ι → convex_cone 𝕜 E) : ↑(infi f) = ⋂ i, (f i : set E) := by simp [infi] lemma mem_infi {ι : Sort*} {x : E} {f : ι → convex_cone 𝕜 E} : x ∈ infi f ↔ ∀ i, x ∈ f i := mem_Inter₂.trans $ by simp variables (𝕜) instance : has_bot (convex_cone 𝕜 E) := ⟨⟨∅, λ c hc x, false.elim, λ x, false.elim⟩⟩ lemma mem_bot (x : E) : x ∈ (⊥ : convex_cone 𝕜 E) = false := rfl @[simp] lemma coe_bot : ↑(⊥ : convex_cone 𝕜 E) = (∅ : set E) := rfl instance : has_top (convex_cone 𝕜 E) := ⟨⟨univ, λ c hc x hx, mem_univ _, λ x hx y hy, mem_univ _⟩⟩ lemma mem_top (x : E) : x ∈ (⊤ : convex_cone 𝕜 E) := mem_univ x @[simp] lemma coe_top : ↑(⊤ : convex_cone 𝕜 E) = (univ : set E) := rfl instance : complete_lattice (convex_cone 𝕜 E) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x, false.elim, top := (⊤), le_top := λ S x hx, mem_top 𝕜 x, inf := (⊓), Inf := has_Inf.Inf, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T}, le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx, le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx, sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx, Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs, le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx, Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha, .. set_like.partial_order } instance : inhabited (convex_cone 𝕜 E) := ⟨⊥⟩ end has_smul section module variables [module 𝕜 E] (S : convex_cone 𝕜 E) protected lemma convex : convex 𝕜 (S : set E) := convex_iff_forall_pos.2 $ λ x hx y hy a b ha hb _, S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy) end module end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] [add_comm_monoid G] section mul_action variables [mul_action 𝕜 E] (S : convex_cone 𝕜 E) lemma smul_mem_iff {c : 𝕜} (hc : 0 < c) {x : E} : c • x ∈ S ↔ x ∈ S := ⟨λ h, inv_smul_smul₀ hc.ne' x ▸ S.smul_mem (inv_pos.2 hc) h, S.smul_mem hc⟩ end mul_action section module variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G] /-- The image of a convex cone under a `𝕜`-linear map is a convex cone. -/ def map (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 E) : convex_cone 𝕜 F := { carrier := f '' S, smul_mem' := λ c hc y ⟨x, hx, hy⟩, hy ▸ f.map_smul c x ▸ mem_image_of_mem f (S.smul_mem hc hx), add_mem' := λ y₁ ⟨x₁, hx₁, hy₁⟩ y₂ ⟨x₂, hx₂, hy₂⟩, hy₁ ▸ hy₂ ▸ f.map_add x₁ x₂ ▸ mem_image_of_mem f (S.add_mem hx₁ hx₂) } @[simp] lemma mem_map {f : E →ₗ[𝕜] F} {S : convex_cone 𝕜 E} {y : F} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex lemma map_map (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 E) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image g f S @[simp] lemma map_id (S : convex_cone 𝕜 E) : S.map linear_map.id = S := set_like.coe_injective $ image_id _ /-- The preimage of a convex cone under a `𝕜`-linear map is a convex cone. -/ def comap (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 F) : convex_cone 𝕜 E := { carrier := f ⁻¹' S, smul_mem' := λ c hc x hx, by { rw [mem_preimage, f.map_smul c], exact S.smul_mem hc hx }, add_mem' := λ x hx y hy, by { rw [mem_preimage, f.map_add], exact S.add_mem hx hy } } @[simp] lemma coe_comap (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 F) : (S.comap f : set E) = f ⁻¹' S := rfl @[simp] lemma comap_id (S : convex_cone 𝕜 E) : S.comap linear_map.id = S := set_like.coe_injective preimage_id lemma comap_comap (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 G) : (S.comap g).comap f = S.comap (g.comp f) := set_like.coe_injective $ preimage_comp.symm @[simp] lemma mem_comap {f : E →ₗ[𝕜] F} {S : convex_cone 𝕜 F} {x : E} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl end module end add_comm_monoid section ordered_add_comm_group variables [ordered_add_comm_group E] [module 𝕜 E] /-- Constructs an ordered module given an `ordered_add_comm_group`, a cone, and a proof that the order relation is the one defined by the cone. -/ lemma to_ordered_smul (S : convex_cone 𝕜 E) (h : ∀ x y : E, x ≤ y ↔ y - x ∈ S) : ordered_smul 𝕜 E := ordered_smul.mk' begin intros x y z xy hz, rw [h (z • x) (z • y), ←smul_sub z y x], exact smul_mem S hz ((h x y).mp xy.le), end end ordered_add_comm_group end linear_ordered_field /-! ### Convex cones with extra properties -/ section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [has_smul 𝕜 E] (S : convex_cone 𝕜 E) /-- A convex cone is pointed if it includes `0`. -/ def pointed (S : convex_cone 𝕜 E) : Prop := (0 : E) ∈ S /-- A convex cone is blunt if it doesn't include `0`. -/ def blunt (S : convex_cone 𝕜 E) : Prop := (0 : E) ∉ S lemma pointed_iff_not_blunt (S : convex_cone 𝕜 E) : S.pointed ↔ ¬S.blunt := ⟨λ h₁ h₂, h₂ h₁, not_not.mp⟩ lemma blunt_iff_not_pointed (S : convex_cone 𝕜 E) : S.blunt ↔ ¬S.pointed := by rw [pointed_iff_not_blunt, not_not] lemma pointed.mono {S T : convex_cone 𝕜 E} (h : S ≤ T) : S.pointed → T.pointed := @h _ lemma blunt.anti {S T : convex_cone 𝕜 E} (h : T ≤ S) : S.blunt → T.blunt := (∘ @@h) end add_comm_monoid section add_comm_group variables [add_comm_group E] [has_smul 𝕜 E] (S : convex_cone 𝕜 E) /-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/ def flat : Prop := ∃ x ∈ S, x ≠ (0 : E) ∧ -x ∈ S /-- A convex cone is salient if it doesn't include `x` and `-x` for any nonzero `x`. -/ def salient : Prop := ∀ x ∈ S, x ≠ (0 : E) → -x ∉ S lemma salient_iff_not_flat (S : convex_cone 𝕜 E) : S.salient ↔ ¬S.flat := begin split, { rintros h₁ ⟨x, xs, H₁, H₂⟩, exact h₁ x xs H₁ H₂ }, { intro h, unfold flat at h, push_neg at h, exact h } end lemma flat.mono {S T : convex_cone 𝕜 E} (h : S ≤ T) : S.flat → T.flat | ⟨x, hxS, hx, hnxS⟩ := ⟨x, h hxS, hx, h hnxS⟩ lemma salient.anti {S T : convex_cone 𝕜 E} (h : T ≤ S) : S.salient → T.salient := λ hS x hxT hx hnT, hS x (h hxT) hx (h hnT) /-- A flat cone is always pointed (contains `0`). -/ lemma flat.pointed {S : convex_cone 𝕜 E} (hS : S.flat) : S.pointed := begin obtain ⟨x, hx, _, hxneg⟩ := hS, rw [pointed, ←add_neg_self x], exact add_mem S hx hxneg, end /-- A blunt cone (one not containing `0`) is always salient. -/ lemma blunt.salient {S : convex_cone 𝕜 E} : S.blunt → S.salient := begin rw [salient_iff_not_flat, blunt_iff_not_pointed], exact mt flat.pointed, end /-- A pointed convex cone defines a preorder. -/ def to_preorder (h₁ : S.pointed) : preorder E := { le := λ x y, y - x ∈ S, le_refl := λ x, by change x - x ∈ S; rw [sub_self x]; exact h₁, le_trans := λ x y z xy zy, by simpa using add_mem S zy xy } /-- A pointed and salient cone defines a partial order. -/ def to_partial_order (h₁ : S.pointed) (h₂ : S.salient) : partial_order E := { le_antisymm := begin intros a b ab ba, by_contradiction h, have h' : b - a ≠ 0 := λ h'', h (eq_of_sub_eq_zero h'').symm, have H := h₂ (b-a) ab h', rw neg_sub b a at H, exact H ba, end, ..to_preorder S h₁ } /-- A pointed and salient cone defines an `ordered_add_comm_group`. -/ def to_ordered_add_comm_group (h₁ : S.pointed) (h₂ : S.salient) : ordered_add_comm_group E := { add_le_add_left := begin intros a b hab c, change c + b - (c + a) ∈ S, rw add_sub_add_left_eq_sub, exact hab, end, ..to_partial_order S h₁ h₂, ..show add_comm_group E, by apply_instance } end add_comm_group section module variables [add_comm_monoid E] [module 𝕜 E] instance : has_zero (convex_cone 𝕜 E) := ⟨⟨0, λ _ _, by simp, λ _, by simp⟩⟩ @[simp] lemma mem_zero (x : E) : x ∈ (0 : convex_cone 𝕜 E) ↔ x = 0 := iff.rfl @[simp] lemma coe_zero : ((0 : convex_cone 𝕜 E) : set E) = 0 := rfl lemma pointed_zero : (0 : convex_cone 𝕜 E).pointed := by rw [pointed, mem_zero] instance : has_add (convex_cone 𝕜 E) := ⟨ λ K₁ K₂, { carrier := {z | ∃ (x y : E), x ∈ K₁ ∧ y ∈ K₂ ∧ x + y = z}, smul_mem' := begin rintro c hc _ ⟨x, y, hx, hy, rfl⟩, rw smul_add, use [c • x, c • y, K₁.smul_mem hc hx, K₂.smul_mem hc hy], end, add_mem' := begin rintro _ ⟨x₁, x₂, hx₁, hx₂, rfl⟩ y ⟨y₁, y₂, hy₁, hy₂, rfl⟩, use [x₁ + y₁, x₂ + y₂, K₁.add_mem hx₁ hy₁, K₂.add_mem hx₂ hy₂], abel, end } ⟩ @[simp] lemma mem_add {K₁ K₂ : convex_cone 𝕜 E} {a : E} : a ∈ K₁ + K₂ ↔ ∃ (x y : E), x ∈ K₁ ∧ y ∈ K₂ ∧ x + y = a := iff.rfl instance : add_zero_class (convex_cone 𝕜 E) := ⟨0, has_add.add, λ _, by {ext, simp}, λ _, by {ext, simp}⟩ instance : add_comm_semigroup (convex_cone 𝕜 E) := { add := has_add.add, add_assoc := λ _ _ _, set_like.coe_injective $ set.add_comm_semigroup.add_assoc _ _ _, add_comm := λ _ _, set_like.coe_injective $ set.add_comm_semigroup.add_comm _ _ } end module end ordered_semiring end convex_cone namespace submodule /-! ### Submodules are cones -/ section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [module 𝕜 E] /-- Every submodule is trivially a convex cone. -/ def to_convex_cone (S : submodule 𝕜 E) : convex_cone 𝕜 E := { carrier := S, smul_mem' := λ c hc x hx, S.smul_mem c hx, add_mem' := λ x hx y hy, S.add_mem hx hy } @[simp] lemma coe_to_convex_cone (S : submodule 𝕜 E) : ↑S.to_convex_cone = (S : set E) := rfl @[simp] lemma mem_to_convex_cone {x : E} {S : submodule 𝕜 E} : x ∈ S.to_convex_cone ↔ x ∈ S := iff.rfl @[simp] lemma to_convex_cone_le_iff {S T : submodule 𝕜 E} : S.to_convex_cone ≤ T.to_convex_cone ↔ S ≤ T := iff.rfl @[simp] lemma to_convex_cone_bot : (⊥ : submodule 𝕜 E).to_convex_cone = 0 := rfl @[simp] lemma to_convex_cone_top : (⊤ : submodule 𝕜 E).to_convex_cone = ⊤ := rfl @[simp] lemma to_convex_cone_inf (S T : submodule 𝕜 E) : (S ⊓ T).to_convex_cone = S.to_convex_cone ⊓ T.to_convex_cone := rfl @[simp] lemma pointed_to_convex_cone (S : submodule 𝕜 E) : S.to_convex_cone.pointed := S.zero_mem end add_comm_monoid end ordered_semiring end submodule namespace convex_cone /-! ### Positive cone of an ordered module -/ section positive_cone variables (𝕜 E) [ordered_semiring 𝕜] [ordered_add_comm_group E] [module 𝕜 E] [ordered_smul 𝕜 E] /-- The positive cone is the convex cone formed by the set of nonnegative elements in an ordered module. -/ def positive : convex_cone 𝕜 E := { carrier := set.Ici 0, smul_mem' := λ c hc x (hx : _ ≤ _), smul_nonneg hc.le hx, add_mem' := λ x (hx : _ ≤ _) y (hy : _ ≤ _), add_nonneg hx hy } @[simp] lemma mem_positive {x : E} : x ∈ positive 𝕜 E ↔ 0 ≤ x := iff.rfl @[simp] lemma coe_positive : ↑(positive 𝕜 E) = set.Ici (0 : E) := rfl /-- The positive cone of an ordered module is always salient. -/ lemma salient_positive : salient (positive 𝕜 E) := λ x xs hx hx', lt_irrefl (0 : E) (calc 0 < x : lt_of_le_of_ne xs hx.symm ... ≤ x + (-x) : le_add_of_nonneg_right hx' ... = 0 : add_neg_self x) /-- The positive cone of an ordered module is always pointed. -/ lemma pointed_positive : pointed (positive 𝕜 E) := le_refl 0 /-- The cone of strictly positive elements. Note that this naming diverges from the mathlib convention of `pos` and `nonneg` due to "positive cone" (`convex_cone.positive`) being established terminology for the non-negative elements. -/ def strictly_positive : convex_cone 𝕜 E := { carrier := set.Ioi 0, smul_mem' := λ c hc x (hx : _ < _), smul_pos hc hx, add_mem' := λ x hx y hy, add_pos hx hy } @[simp] lemma mem_strictly_positive {x : E} : x ∈ strictly_positive 𝕜 E ↔ 0 < x := iff.rfl @[simp] lemma coe_strictly_positive : ↑(strictly_positive 𝕜 E) = set.Ioi (0 : E) := rfl lemma positive_le_strictly_positive : strictly_positive 𝕜 E ≤ positive 𝕜 E := λ x, le_of_lt /-- The strictly positive cone of an ordered module is always salient. -/ lemma salient_strictly_positive : salient (strictly_positive 𝕜 E) := (salient_positive 𝕜 E).anti $ positive_le_strictly_positive 𝕜 E /-- The strictly positive cone of an ordered module is always blunt. -/ lemma blunt_strictly_positive : blunt (strictly_positive 𝕜 E) := lt_irrefl 0 end positive_cone end convex_cone /-! ### Cone over a convex set -/ section cone_from_convex variables [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] namespace convex /-- The set of vectors proportional to those in a convex set forms a convex cone. -/ def to_cone (s : set E) (hs : convex 𝕜 s) : convex_cone 𝕜 E := begin apply convex_cone.mk (⋃ (c : 𝕜) (H : 0 < c), c • s); simp only [mem_Union, mem_smul_set], { rintros c c_pos _ ⟨c', c'_pos, x, hx, rfl⟩, exact ⟨c * c', mul_pos c_pos c'_pos, x, hx, (smul_smul _ _ _).symm⟩ }, { rintros _ ⟨cx, cx_pos, x, hx, rfl⟩ _ ⟨cy, cy_pos, y, hy, rfl⟩, have : 0 < cx + cy, from add_pos cx_pos cy_pos, refine ⟨_, this, _, convex_iff_div.1 hs hx hy cx_pos.le cy_pos.le this, _⟩, simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ this.ne'] } end variables {s : set E} (hs : convex 𝕜 s) {x : E} lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c : 𝕜), 0 < c ∧ ∃ y ∈ s, c • y = x := by simp only [to_cone, convex_cone.mem_mk, mem_Union, mem_smul_set, eq_comm, exists_prop] lemma mem_to_cone' : x ∈ hs.to_cone s ↔ ∃ (c : 𝕜), 0 < c ∧ c • x ∈ s := begin refine hs.mem_to_cone.trans ⟨_, _⟩, { rintros ⟨c, hc, y, hy, rfl⟩, exact ⟨c⁻¹, inv_pos.2 hc, by rwa [smul_smul, inv_mul_cancel hc.ne', one_smul]⟩ }, { rintros ⟨c, hc, hcx⟩, exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel hc.ne', one_smul]⟩ } end lemma subset_to_cone : s ⊆ hs.to_cone s := λ x hx, hs.mem_to_cone'.2 ⟨1, zero_lt_one, by rwa one_smul⟩ /-- `hs.to_cone s` is the least cone that includes `s`. -/ lemma to_cone_is_least : is_least { t : convex_cone 𝕜 E | s ⊆ t } (hs.to_cone s) := begin refine ⟨hs.subset_to_cone, λ t ht x hx, _⟩, rcases hs.mem_to_cone.1 hx with ⟨c, hc, y, hy, rfl⟩, exact t.smul_mem hc (ht hy) end lemma to_cone_eq_Inf : hs.to_cone s = Inf { t : convex_cone 𝕜 E | s ⊆ t } := hs.to_cone_is_least.is_glb.Inf_eq.symm end convex lemma convex_hull_to_cone_is_least (s : set E) : is_least {t : convex_cone 𝕜 E | s ⊆ t} ((convex_convex_hull 𝕜 s).to_cone _) := begin convert (convex_convex_hull 𝕜 s).to_cone_is_least, ext t, exact ⟨λ h, convex_hull_min h t.convex, (subset_convex_hull 𝕜 s).trans⟩, end lemma convex_hull_to_cone_eq_Inf (s : set E) : (convex_convex_hull 𝕜 s).to_cone _ = Inf {t : convex_cone 𝕜 E | s ⊆ t} := eq.symm $ is_glb.Inf_eq $ is_least.is_glb $ convex_hull_to_cone_is_least s end cone_from_convex /-! ### M. Riesz extension theorem Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof. It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition. In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f` to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E` but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension` we use this isomorphism to prove the theorem. -/ variables [add_comm_group E] [module ℝ E] namespace riesz_extension open submodule variables (s : convex_cone ℝ E) (f : E →ₗ.[ℝ] ℝ) /-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`, a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p` and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger submodule without breaking the non-negativity condition. -/ lemma step (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) : ∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x := begin obtain ⟨y, -, hy⟩ : ∃ (y : E) (h : y ∈ ⊤), y ∉ f.domain, { exact @set_like.exists_of_lt (submodule ℝ E) _ _ _ _ (lt_top_iff_ne_top.2 hdom) }, obtain ⟨c, le_c, c_le⟩ : ∃ c, (∀ x : f.domain, -(x:E) - y ∈ s → f x ≤ c) ∧ (∀ x : f.domain, (x:E) + y ∈ s → c ≤ f x), { set Sp := f '' {x : f.domain | (x:E) + y ∈ s}, set Sn := f '' {x : f.domain | -(x:E) - y ∈ s}, suffices : (upper_bounds Sn ∩ lower_bounds Sp).nonempty, by simpa only [set.nonempty, upper_bounds, lower_bounds, ball_image_iff] using this, refine exists_between_of_forall_le (nonempty.image f _) (nonempty.image f (dense y)) _, { rcases (dense (-y)) with ⟨x, hx⟩, rw [← neg_neg x, add_subgroup_class.coe_neg, ← sub_eq_add_neg] at hx, exact ⟨_, hx⟩ }, rintros a ⟨xn, hxn, rfl⟩ b ⟨xp, hxp, rfl⟩, have := s.add_mem hxp hxn, rw [add_assoc, add_sub_cancel'_right, ← sub_eq_add_neg, ← add_subgroup_class.coe_sub] at this, replace := nonneg _ this, rwa [f.map_sub, sub_nonneg] at this }, have hy' : y ≠ 0, from λ hy₀, hy (hy₀.symm ▸ zero_mem _), refine ⟨f.sup_span_singleton y (-c) hy, _, _⟩, { refine lt_iff_le_not_le.2 ⟨f.left_le_sup _ _, λ H, _⟩, replace H := linear_pmap.domain_mono.monotone H, rw [linear_pmap.domain_sup_span_singleton, sup_le_iff, span_le, singleton_subset_iff] at H, exact hy H.2 }, { rintros ⟨z, hz⟩ hzs, rcases mem_sup.1 hz with ⟨x, hx, y', hy', rfl⟩, rcases mem_span_singleton.1 hy' with ⟨r, rfl⟩, simp only [subtype.coe_mk] at hzs, erw [linear_pmap.sup_span_singleton_apply_mk _ _ _ _ _ hx, smul_neg, ← sub_eq_add_neg, sub_nonneg], rcases lt_trichotomy r 0 with hr|hr|hr, { have : -(r⁻¹ • x) - y ∈ s, by rwa [← s.smul_mem_iff (neg_pos.2 hr), smul_sub, smul_neg, neg_smul, neg_neg, smul_smul, mul_inv_cancel hr.ne, one_smul, sub_eq_add_neg, neg_smul, neg_neg], replace := le_c (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left (neg_pos.2 hr), neg_mul, neg_mul, neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel hr.ne, one_mul] at this }, { subst r, simp only [zero_smul, add_zero] at hzs ⊢, apply nonneg, exact hzs }, { have : r⁻¹ • x + y ∈ s, by rwa [← s.smul_mem_iff hr, smul_add, smul_smul, mul_inv_cancel hr.ne', one_smul], replace := c_le (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left hr, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel hr.ne', one_mul] at this } } end theorem exists_top (p : E →ₗ.[ℝ] ℝ) (hp_nonneg : ∀ x : p.domain, (x : E) ∈ s → 0 ≤ p x) (hp_dense : ∀ y, ∃ x : p.domain, (x : E) + y ∈ s) : ∃ q ≥ p, q.domain = ⊤ ∧ ∀ x : q.domain, (x : E) ∈ s → 0 ≤ q x := begin replace hp_nonneg : p ∈ { p | _ }, by { rw mem_set_of_eq, exact hp_nonneg }, obtain ⟨q, hqs, hpq, hq⟩ := zorn_nonempty_partial_order₀ _ _ _ hp_nonneg, { refine ⟨q, hpq, _, hqs⟩, contrapose! hq, rcases step s q hqs _ hq with ⟨r, hqr, hr⟩, { exact ⟨r, hr, hqr.le, hqr.ne'⟩ }, { exact λ y, let ⟨x, hx⟩ := hp_dense y in ⟨of_le hpq.left x, hx⟩ } }, { intros c hcs c_chain y hy, clear hp_nonneg hp_dense p, have cne : c.nonempty := ⟨y, hy⟩, refine ⟨linear_pmap.Sup c c_chain.directed_on, _, λ _, linear_pmap.le_Sup c_chain.directed_on⟩, rintros ⟨x, hx⟩ hxs, have hdir : directed_on (≤) (linear_pmap.domain '' c), from directed_on_image.2 (c_chain.directed_on.mono linear_pmap.domain_mono.monotone), rcases (mem_Sup_of_directed (cne.image _) hdir).1 hx with ⟨_, ⟨f, hfc, rfl⟩, hfx⟩, have : f ≤ linear_pmap.Sup c c_chain.directed_on, from linear_pmap.le_Sup _ hfc, convert ← hcs hfc ⟨x, hfx⟩ hxs, apply this.2, refl } end end riesz_extension /-- M. **Riesz extension theorem**: given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. -/ theorem riesz_extension (s : convex_cone ℝ E) (f : E →ₗ.[ℝ] ℝ) (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x ∈ s, 0 ≤ g x) := begin rcases riesz_extension.exists_top s f nonneg dense with ⟨⟨g_dom, g⟩, ⟨hpg, hfg⟩, htop, hgs⟩, clear hpg, refine ⟨g ∘ₗ ↑(linear_equiv.of_top _ htop).symm, _, _⟩; simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.of_top_symm_apply], { exact λ x, (hfg (submodule.coe_mk _ _).symm).symm }, { exact λ x hx, hgs ⟨x, _⟩ hx } end /-- **Hahn-Banach theorem**: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x`. -/ theorem exists_extension_of_le_sublinear (f : E →ₗ.[ℝ] ℝ) (N : E → ℝ) (N_hom : ∀ (c : ℝ), 0 < c → ∀ x, N (c • x) = c * N x) (N_add : ∀ x y, N (x + y) ≤ N x + N y) (hf : ∀ x : f.domain, f x ≤ N x) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x, g x ≤ N x) := begin let s : convex_cone ℝ (E × ℝ) := { carrier := {p : E × ℝ | N p.1 ≤ p.2 }, smul_mem' := λ c hc p hp, calc N (c • p.1) = c * N p.1 : N_hom c hc p.1 ... ≤ c * p.2 : mul_le_mul_of_nonneg_left hp hc.le, add_mem' := λ x hx y hy, (N_add _ _).trans (add_le_add hx hy) }, obtain ⟨g, g_eq, g_nonneg⟩ := riesz_extension s ((-f).coprod (linear_map.id.to_pmap ⊤)) _ _; try { simp only [linear_pmap.coprod_apply, to_pmap_apply, id_apply, linear_pmap.neg_apply, ← sub_eq_neg_add, sub_nonneg, subtype.coe_mk] at * }, replace g_eq : ∀ (x : f.domain) (y : ℝ), g (x, y) = y - f x, { intros x y, simpa only [subtype.coe_mk, subtype.coe_eta] using g_eq ⟨(x, y), ⟨x.2, trivial⟩⟩ }, { refine ⟨-g.comp (inl ℝ E ℝ), _, _⟩; simp only [neg_apply, inl_apply, comp_apply], { intro x, simp [g_eq x 0] }, { intro x, have A : (x, N x) = (x, 0) + (0, N x), by simp, have B := g_nonneg ⟨x, N x⟩ (le_refl (N x)), rw [A, map_add, ← neg_le_iff_add_nonneg'] at B, have C := g_eq 0 (N x), simp only [submodule.coe_zero, f.map_zero, sub_zero] at C, rwa ← C } }, { exact λ x hx, le_trans (hf _) hx }, { rintros ⟨x, y⟩, refine ⟨⟨(0, N x - y), ⟨f.domain.zero_mem, trivial⟩⟩, _⟩, simp only [convex_cone.mem_mk, mem_set_of_eq, subtype.coe_mk, prod.fst_add, prod.snd_add, zero_add, sub_add_cancel] } end
77d36d98c5692461611eabb1fe60e2f375a740fe
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/matrix/basic.lean
dbaa30f51bcb1b27044036fee9ae4ebf143c61e2
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
42,559
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import algebra.big_operators.pi import algebra.module.pi import algebra.module.linear_map import algebra.big_operators.ring import algebra.star.basic import data.equiv.ring import data.fintype.card /-! # Matrices -/ universes u u' v w open_locale big_operators /-- `matrix m n` is the type of matrices whose rows are indexed by the fintype `m` and whose columns are indexed by the fintype `n`. -/ @[nolint unused_arguments] def matrix (m : Type u) (n : Type u') [fintype m] [fintype n] (α : Type v) : Type (max u u' v) := m → n → α variables {l m n o : Type*} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} namespace matrix section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext /-- `M.map f` is the matrix obtained by applying `f` to each entry of the matrix `M`. -/ def map (M : matrix m n α) {β : Type w} (f : α → β) : matrix m n β := λ i j, f (M i j) @[simp] lemma map_apply {M : matrix m n α} {β : Type w} {f : α → β} {i : m} {j : n} : M.map f i j = f (M i j) := rfl @[simp] lemma map_map {M : matrix m n α} {β γ : Type*} {f : α → β} {g : β → γ} : (M.map f).map g = M.map (g ∘ f) := by { ext, simp, } /-- The transpose of a matrix. -/ def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix /-- `matrix.col u` is the column matrix whose entries are given by `u`. -/ def col (w : m → α) : matrix m unit α | x y := w x /-- `matrix.row u` is the row matrix whose entries are given by `u`. -/ def row (v : n → α) : matrix unit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [has_sub α] : has_sub (matrix m n α) := pi.has_sub instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group instance [unique α] : unique (matrix m n α) := pi.unique instance [subsingleton α] : subsingleton (matrix m n α) := pi.subsingleton instance [nonempty m] [nonempty n] [nontrivial α] : nontrivial (matrix m n α) := function.nontrivial @[simp] theorem zero_apply [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_apply [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_apply [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl @[simp] theorem sub_apply [has_sub α] (M N : matrix m n α) (i j) : (M - N) i j = M i j - N i j := rfl @[simp] lemma map_zero [has_zero α] {β : Type w} [has_zero β] {f : α → β} (h : f 0 = 0) : (0 : matrix m n α).map f = 0 := by { ext, simp [h], } lemma map_add [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M N : matrix m n α) : (M + N).map f = M.map f + N.map f := by { ext, simp, } lemma map_sub [add_group α] {β : Type w} [add_group β] (f : α →+ β) (M N : matrix m n α) : (M - N).map f = M.map f - N.map f := by { ext, simp } lemma subsingleton_of_empty_left (hm : ¬ nonempty m) : subsingleton (matrix m n α) := ⟨λ M N, by { ext, contrapose! hm, use i }⟩ lemma subsingleton_of_empty_right (hn : ¬ nonempty n) : subsingleton (matrix m n α) := ⟨λ M N, by { ext, contrapose! hn, use j }⟩ end matrix /-- The `add_monoid_hom` between spaces of matrices induced by an `add_monoid_hom` between their coefficients. -/ def add_monoid_hom.map_matrix [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) : matrix m n α →+ matrix m n β := { to_fun := λ M, M.map f, map_zero' := by simp, map_add' := matrix.map_add f, } @[simp] lemma add_monoid_hom.map_matrix_apply [add_monoid α] {β : Type w} [add_monoid β] (f : α →+ β) (M : matrix m n α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section diagonal variables [decidable_eq n] /-- `diagonal d` is the square matrix such that `(diagonal d) i i = d i` and `(diagonal d) i j = 0` if `i ≠ j`. -/ def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_apply_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_apply_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_apply_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_apply_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_apply_ne' h] } end @[simp] theorem diagonal_add [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases h : i = j; simp [h] @[simp] lemma diagonal_map {β : Type w} [has_zero α] [has_zero β] {f : α → β} (h : f 0 = 0) {d : n → α} : (diagonal d).map f = diagonal (λ m, f (d m)) := by { ext, simp only [diagonal, map_apply], split_ifs; simp [h], } section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_apply {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_apply_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_apply_eq i @[simp] theorem one_apply_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_apply_ne theorem one_apply_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_apply_ne' @[simp] lemma one_map {β : Type w} [has_zero β] [has_one β] {f : α → β} (h₀ : f 0 = 0) (h₁ : f 1 = 1) : (1 : matrix n n α).map f = (1 : matrix n n β) := by { ext, simp only [one_apply, map_apply], split_ifs; simp [h₀, h₁], } end one section numeral @[simp] lemma bit0_apply [has_add α] (M : matrix m m α) (i : m) (j : m) : (bit0 M) i j = bit0 (M i j) := rfl variables [add_monoid α] [has_one α] lemma bit1_apply (M : matrix n n α) (i : n) (j : n) : (bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) := by dsimp [bit1]; by_cases h : i = j; simp [h] @[simp] lemma bit1_apply_eq (M : matrix n n α) (i : n) : (bit1 M) i i = bit1 (M i i) := by simp [bit1_apply] @[simp] lemma bit1_apply_ne (M : matrix n n α) {i j : n} (h : i ≠ j) : (bit1 M) i j = bit0 (M i j) := by simp [bit1_apply, h] end numeral end diagonal section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_apply_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_apply_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _ using 1; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) : dot_product (x • v) w = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc] @[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) : dot_product v (x • w) = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm] end dot_product /-- `M ⬝ N` is the usual product of matrices `M` and `N`, i.e. we have that `(M ⬝ N) i k` is the dot product of the `i`-th row of `M` by the `k`-th column of `Ǹ`. -/ protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_apply [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_apply' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ @[simp] lemma map_mul {L : matrix m n α} {M : matrix n o α} {β : Type w} [semiring β] {f : α →+* β} : (L ⬝ M).map f = L.map f ⬝ M.map f := by { ext, simp [mul_apply, ring_hom.map_sum], } -- TODO: there should be a way to avoid restating these for each `foo_hom`. /-- A version of `one_map` where `f` is a ring hom. -/ @[simp] lemma ring_hom_map_one [decidable_eq n] {β : Type w} [semiring β] (f : α →+* β) : (1 : matrix n n α).map f = 1 := one_map f.map_zero f.map_one /-- A version of `one_map` where `f` is a `ring_equiv`. -/ @[simp] lemma ring_equiv_map_one [decidable_eq n] {β : Type w} [semiring β] (f : α ≃+* β) : (1 : matrix n n α).map f = 1 := one_map f.map_zero f.map_one /-- A version of `map_zero` where `f` is a `zero_hom`. -/ @[simp] lemma zero_hom_map_zero {β : Type w} [has_zero β] (f : zero_hom α β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `add_monoid_hom`. -/ @[simp] lemma add_monoid_hom_map_zero {β : Type w} [add_monoid β] (f : α →+ β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `add_equiv`. -/ @[simp] lemma add_equiv_map_zero {β : Type w} [add_monoid β] (f : α ≃+ β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `linear_map`. -/ @[simp] lemma linear_map_map_zero {R : Type*} [semiring R] {β : Type w} [add_comm_monoid β] [semimodule R α] [semimodule R β] (f : α →ₗ[R] β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `linear_equiv`. -/ @[simp] lemma linear_equiv_map_zero {R : Type*} [semiring R] {β : Type w} [add_comm_monoid β] [semimodule R α] [semimodule R β] (f : α ≃ₗ[R] β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `ring_hom`. -/ @[simp] lemma ring_hom_map_zero {β : Type w} [semiring β] (f : α →+* β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero /-- A version of `map_zero` where `f` is a `ring_equiv`. -/ @[simp] lemma ring_equiv_map_zero {β : Type w} [semiring β] (f : α ≃+* β) : (0 : matrix n n α).map f = 0 := map_zero f.map_zero lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : (∑ a in s, f a) ⬝ M = ∑ a in s, f a ⬝ M := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ ∑ a in s, f a = ∑ a in s, M ⬝ f a := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm @[simp] lemma row_mul_col_apply (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring end matrix /-- The `ring_hom` between spaces of square matrices induced by a `ring_hom` between their coefficients. -/ def ring_hom.map_matrix [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) : matrix m m α →+* matrix m m β := { to_fun := λ M, M.map f, map_one' := by simp, map_mul' := λ L M, matrix.map_mul, ..(f.to_add_monoid_hom).map_matrix } @[simp] lemma ring_hom.map_matrix_apply [decidable_eq m] [semiring α] {β : Type w} [semiring β] (f : α →+* β) (M : matrix m m α) : f.map_matrix M = M.map f := rfl open_locale matrix namespace matrix section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } protected theorem sub_mul (M M' : matrix m n α) (N : matrix n o α) : (M - M') ⬝ N = M ⬝ N - M' ⬝ N := by rw [sub_eq_add_neg, matrix.add_mul, neg_mul, sub_eq_add_neg] protected theorem mul_sub (M : matrix m n α) (N N' : matrix n o α) : M ⬝ (N - N') = M ⬝ N - M ⬝ N' := by rw [sub_eq_add_neg, matrix.mul_add, mul_neg, sub_eq_add_neg] end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule _ _ _ @[simp] lemma smul_apply [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section semiring variables [semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } @[simp] lemma mul_mul_left (M : matrix m n α) (N : matrix n o α) (a : α) : (λ i j, a * M i j) ⬝ N = a • (M ⬝ N) := begin simp only [←smul_apply], simp, end /-- The ring homomorphism `α →+* matrix n n α` sending `a` to the diagonal matrix with `a` on the diagonal. -/ def scalar (n : Type u) [decidable_eq n] [fintype n] : α →+* matrix n n α := { to_fun := λ a, a • 1, map_zero' := by simp, map_add' := by { intros, ext, simp [add_mul], }, map_one' := by simp, map_mul' := by { intros, ext, simp [mul_assoc], }, } section scalar variable [decidable_eq n] @[simp] lemma coe_scalar : (scalar n : α → matrix n n α) = λ a, a • 1 := rfl lemma scalar_apply_eq (a : α) (i : n) : scalar n a i i = a := by simp only [coe_scalar, mul_one, one_apply_eq, smul_apply] lemma scalar_apply_ne (a : α) (i j : n) (h : i ≠ j) : scalar n a i j = 0 := by simp only [h, coe_scalar, one_apply_ne, ne.def, not_false_iff, smul_apply, mul_zero] lemma scalar_inj [nonempty n] {r s : α} : scalar n r = scalar n s ↔ r = s := begin split, { intro h, inhabit n, rw [← scalar_apply_eq r (arbitrary n), ← scalar_apply_eq s (arbitrary n), h] }, { rintro rfl, refl } end end scalar end semiring section comm_semiring variables [comm_semiring α] lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } @[simp] lemma mul_mul_right (M : matrix m n α) (N : matrix n o α) (a : α) : M ⬝ (λ i j, a * N i j) = a • (M ⬝ N) := begin simp only [←smul_apply], simp, end lemma scalar.commute [decidable_eq n] (r : α) (M : matrix n n α) : commute (scalar n r) M := by simp [commute, semiconj_by] end comm_semiring section semiring variables [semiring α] /-- For two vectors `w` and `v`, `vec_mul_vec w v i j` is defined to be `w i * v j`. Put another way, `vec_mul_vec w v` is exactly `col w ⬝ row v`. -/ def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y /-- `mul_vec M v` is the matrix-vector product of `M` and `v`, where `v` is seen as a column matrix. Put another way, `mul_vec M v` is the vector whose entries are those of `M ⬝ col v` (see `col_mul_vec`). -/ def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v /-- `vec_mul v M` is the vector-matrix product of `v` and `M`, where `v` is seen as a row matrix. Put another way, `vec_mul v M` is the vector whose entries are those of `row v ⬝ M` (see `row_vec_mul`). -/ def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_apply], refl } variables [decidable_eq m] [decidable_eq n] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i' = i ∧ j' = j then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis (x : matrix n m α) : x = ∑ (i : n) (j : m), std_basis_matrix i j (x i j) := begin ext, symmetry, iterate 2 { rw finset.sum_apply }, convert fintype.sum_eq_single i _, { simp [std_basis_matrix] }, { intros j hj, simp [std_basis_matrix, hj.symm] } end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], split_ifs; tauto, end @[elab_as_eliminator] protected lemma induction_on' {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_zero : M 0) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := begin rw [matrix_eq_sum_std_basis m, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [nonempty n] {X : Type*} [semiring X] {M : matrix n n X → Prop} (m : matrix n n X) (h_add : ∀p q, M p → M q → M (p + q)) (h_std_basis : ∀ i j x, M (std_basis_matrix i j x)) : M m := matrix.induction_on' m begin have i : n := classical.choice (by assumption), simpa using h_std_basis i i 0, end h_add h_std_basis end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } lemma smul_mul_vec_assoc (A : matrix n n α) (b : n → α) (a : α) : (a • A).mul_vec b = a • (A.mul_vec b) := begin ext i, change dot_product ((a • A) i) b = _, simp only [mul_vec, smul_eq_mul, pi.smul_apply, smul_dot_product], end end ring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_apply`, `diagonal_apply_eq`, etc. -/ @[simp] lemma transpose_apply (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_apply_eq] }, { simp only [diagonal_apply_ne h, diagonal_apply_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_sub [add_group α] (M : matrix m n α) (N : matrix m n α) : (M - N)ᵀ = Mᵀ - Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_semiring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [semiring α] (c : α) (M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [has_neg α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl lemma transpose_map {β : Type w} {f : α → β} {M : matrix m n α} : Mᵀ.map f = (M.map f)ᵀ := by { ext, refl } end transpose section star_ring variables [decidable_eq n] {R : Type*} [semiring R] [star_ring R] /-- When `R` is a `*`-(semi)ring, `matrix n n R` becomes a `*`-(semi)ring with the star operation given by taking the conjugate, and the star of each entry. -/ instance : star_ring (matrix n n R) := { star := λ M, M.transpose.map star, star_involutive := λ M, by { ext, simp, }, star_add := λ M N, by { ext, simp, }, star_mul := λ M N, by { ext, simp [mul_apply], }, } @[simp] lemma star_apply (M : matrix n n R) (i j) : star M i j = star (M j i) := rfl lemma star_mul (M N : matrix n n R) : star (M ⬝ N) = star N ⬝ star M := star_mul _ _ end star_ring /-- `M.minor row col` is the matrix obtained by reindexing the rows and the lines of `M`, such that `M.minor row col i j = M (row i) (col j)`. Note that the total number of row/colums doesn't have to be preserved. -/ def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) /-- The left `n × l` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) /-- The right `n × r` part of a `n × (l+r)` matrix. -/ @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) /-- The top `u × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id /-- The bottom `d × n` part of a `(u+d) × n` matrix. -/ @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id /-- The top-right `u × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) /-- The bottom-right `d × r` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) /-- The top-left `u × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) /-- The bottom-left `d × l` part of a `(u+d) × (l+r)` matrix. -/ @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_apply (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_apply (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col section update /-- Update, i.e. replace the `i`th row of matrix `A` with the values in `b`. -/ def update_row [decidable_eq n] (M : matrix n m α) (i : n) (b : m → α) : matrix n m α := function.update M i b /-- Update, i.e. replace the `j`th column of matrix `A` with the values in `b`. -/ def update_column [decidable_eq m] (M : matrix n m α) (j : m) (b : n → α) : matrix n m α := λ i, function.update (M i) j (b i) variables {M : matrix n m α} {i : n} {j : m} {b : m → α} {c : n → α} @[simp] lemma update_row_self [decidable_eq n] : update_row M i b i = b := function.update_same i b M @[simp] lemma update_column_self [decidable_eq m] : update_column M j c i j = c i := function.update_same j (c i) (M i) @[simp] lemma update_row_ne [decidable_eq n] {i' : n} (i_ne : i' ≠ i) : update_row M i b i' = M i' := function.update_noteq i_ne b M @[simp] lemma update_column_ne [decidable_eq m] {j' : m} (j_ne : j' ≠ j) : update_column M j c i j' = M i j' := function.update_noteq j_ne (c i) (M i) lemma update_row_apply [decidable_eq n] {i' : n} : update_row M i b i' j = if i' = i then b j else M i' j := begin by_cases i' = i, { rw [h, update_row_self, if_pos rfl] }, { rwa [update_row_ne h, if_neg h] } end lemma update_column_apply [decidable_eq m] {j' : m} : update_column M j c i j' = if j' = j then c i else M i j' := begin by_cases j' = j, { rw [h, update_column_self, if_pos rfl] }, { rwa [update_column_ne h, if_neg h] } end lemma update_row_transpose [decidable_eq m] : update_row Mᵀ j c = (update_column M j c)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end lemma update_column_transpose [decidable_eq n] : update_column Mᵀ i b = (update_row M i b)ᵀ := begin ext i' j, rw [transpose_apply, update_row_apply, update_column_apply], refl end end update section block_matrices /-- We can form a single large matrix by flattening smaller 'block' matrices of compatible dimensions. -/ def from_blocks (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : matrix (n ⊕ o) (l ⊕ m) α := sum.elim (λ i, sum.elim (A i) (B i)) (λ i, sum.elim (C i) (D i)) @[simp] lemma from_blocks_apply₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : l) : from_blocks A B C D (sum.inl i) (sum.inl j) = A i j := rfl @[simp] lemma from_blocks_apply₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : n) (j : m) : from_blocks A B C D (sum.inl i) (sum.inr j) = B i j := rfl @[simp] lemma from_blocks_apply₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : l) : from_blocks A B C D (sum.inr i) (sum.inl j) = C i j := rfl @[simp] lemma from_blocks_apply₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (i : o) (j : m) : from_blocks A B C D (sum.inr i) (sum.inr j) = D i j := rfl /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "top left" submatrix. -/ def to_blocks₁₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n l α := λ i j, M (sum.inl i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "top right" submatrix. -/ def to_blocks₁₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix n m α := λ i j, M (sum.inl i) (sum.inr j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "bottom left" submatrix. -/ def to_blocks₂₁ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o l α := λ i j, M (sum.inr i) (sum.inl j) /-- Given a matrix whose row and column indexes are sum types, we can extract the correspnding "bottom right" submatrix. -/ def to_blocks₂₂ (M : matrix (n ⊕ o) (l ⊕ m) α) : matrix o m α := λ i j, M (sum.inr i) (sum.inr j) lemma from_blocks_to_blocks (M : matrix (n ⊕ o) (l ⊕ m) α) : from_blocks M.to_blocks₁₁ M.to_blocks₁₂ M.to_blocks₂₁ M.to_blocks₂₂ = M := begin ext i j, rcases i; rcases j; refl, end @[simp] lemma to_blocks_from_blocks₁₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₁ = A := rfl @[simp] lemma to_blocks_from_blocks₁₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₁₂ = B := rfl @[simp] lemma to_blocks_from_blocks₂₁ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₁ = C := rfl @[simp] lemma to_blocks_from_blocks₂₂ (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D).to_blocks₂₂ = D := rfl lemma from_blocks_transpose (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : (from_blocks A B C D)ᵀ = from_blocks Aᵀ Cᵀ Bᵀ Dᵀ := begin ext i j, rcases i; rcases j; simp [from_blocks], end variables [semiring α] lemma from_blocks_smul (x : α) (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) : x • (from_blocks A B C D) = from_blocks (x • A) (x • B) (x • C) (x • D) := begin ext i j, rcases i; rcases j; simp [from_blocks], end lemma from_blocks_add (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix n l α) (B' : matrix n m α) (C' : matrix o l α) (D' : matrix o m α) : (from_blocks A B C D) + (from_blocks A' B' C' D') = from_blocks (A + A') (B + B') (C + C') (D + D') := begin ext i j, rcases i; rcases j; refl, end lemma from_blocks_multiply {p q : Type*} [fintype p] [fintype q] (A : matrix n l α) (B : matrix n m α) (C : matrix o l α) (D : matrix o m α) (A' : matrix l p α) (B' : matrix l q α) (C' : matrix m p α) (D' : matrix m q α) : (from_blocks A B C D) ⬝ (from_blocks A' B' C' D') = from_blocks (A ⬝ A' + B ⬝ C') (A ⬝ B' + B ⬝ D') (C ⬝ A' + D ⬝ C') (C ⬝ B' + D ⬝ D') := begin ext i j, rcases i; rcases j; simp only [from_blocks, mul_apply, fintype.sum_sum_type, sum.elim_inl, sum.elim_inr, pi.add_apply], end variables [decidable_eq l] [decidable_eq m] @[simp] lemma from_blocks_diagonal (d₁ : l → α) (d₂ : m → α) : from_blocks (diagonal d₁) 0 0 (diagonal d₂) = diagonal (sum.elim d₁ d₂) := begin ext i j, rcases i; rcases j; simp [diagonal], end @[simp] lemma from_blocks_one : from_blocks (1 : matrix l l α) 0 0 (1 : matrix m m α) = 1 := by { ext i j, rcases i; rcases j; simp [one_apply] } end block_matrices section block_diagonal variables (M N : o → matrix m n α) [decidable_eq o] section has_zero variables [has_zero α] /-- `matrix.block_diagonal M` turns `M : o → matrix m n α'` into a `m × o`-by`n × o` block matrix which has the entries of `M` along the diagonal and zero elsewhere. -/ def block_diagonal : matrix (m × o) (n × o) α | ⟨i, k⟩ ⟨j, k'⟩ := if k = k' then M k i j else 0 lemma block_diagonal_apply (ik jk) : block_diagonal M ik jk = if ik.2 = jk.2 then M ik.2 ik.1 jk.1 else 0 := by { cases ik, cases jk, refl } @[simp] lemma block_diagonal_apply_eq (i j k) : block_diagonal M (i, k) (j, k) = M k i j := if_pos rfl lemma block_diagonal_apply_ne (i j) {k k'} (h : k ≠ k') : block_diagonal M (i, k) (j, k') = 0 := if_neg h @[simp] lemma block_diagonal_transpose : (block_diagonal M)ᵀ = (block_diagonal (λ k, (M k)ᵀ)) := begin ext, simp only [transpose_apply, block_diagonal_apply, eq_comm], split_ifs with h, { rw h }, { refl } end @[simp] lemma block_diagonal_zero : block_diagonal (0 : o → matrix m n α) = 0 := by { ext, simp [block_diagonal_apply] } @[simp] lemma block_diagonal_diagonal [decidable_eq m] (d : o → m → α) : (block_diagonal (λ k, diagonal (d k))) = diagonal (λ ik, d ik.2 ik.1) := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, diagonal], split_ifs; finish end @[simp] lemma block_diagonal_one [decidable_eq m] [has_one α] : (block_diagonal (1 : o → matrix m m α)) = 1 := show (block_diagonal (λ (_ : o), diagonal (λ (_ : m), (1 : α)))) = diagonal (λ _, 1), by rw [block_diagonal_diagonal] end has_zero @[simp] lemma block_diagonal_add [add_monoid α] : block_diagonal (M + N) = block_diagonal M + block_diagonal N := begin ext, simp only [block_diagonal_apply, add_apply], split_ifs; simp end @[simp] lemma block_diagonal_neg [add_group α] : block_diagonal (-M) = - block_diagonal M := begin ext, simp only [block_diagonal_apply, neg_apply], split_ifs; simp end @[simp] lemma block_diagonal_sub [add_group α] : block_diagonal (M - N) = block_diagonal M - block_diagonal N := by simp [sub_eq_add_neg] @[simp] lemma block_diagonal_mul {p : Type*} [fintype p] [semiring α] (N : o → matrix n p α) : block_diagonal (λ k, M k ⬝ N k) = block_diagonal M ⬝ block_diagonal N := begin ext ⟨i, k⟩ ⟨j, k'⟩, simp only [block_diagonal_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product], split_ifs with h; simp [h] end @[simp] lemma block_diagonal_smul {R : Type*} [semiring R] [add_comm_monoid α] [semimodule R α] (x : R) : block_diagonal (x • M) = x • block_diagonal M := by { ext, simp only [block_diagonal_apply, pi.smul_apply, smul_apply], split_ifs; simp } end block_diagonal end matrix namespace ring_hom variables {β : Type*} [semiring α] [semiring β] lemma map_matrix_mul (M : matrix m n α) (N : matrix n o α) (i : m) (j : o) (f : α →+* β) : f (matrix.mul M N i j) = matrix.mul (λ i j, f (M i j)) (λ i j, f (N i j)) i j := by simp [matrix.mul_apply, ring_hom.map_sum] end ring_hom
5804c3b4a66b1ec06d45dc58ad5f859edd4e25aa
f57749ca63d6416f807b770f67559503fdb21001
/library/init/relation.lean
672e4d0f088cac6a60afcdbba721f0cd845e6f2b
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,659
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module init.relation Authors: Leonardo de Moura -/ prelude import init.logic -- TODO(Leo): remove duplication between this file and algebra/relation.lean -- We need some of the following definitions asap when "initializing" Lean. variables {A B : Type} (R : B → B → Prop) local infix `≺`:50 := R definition reflexive := ∀x, x ≺ x definition symmetric := ∀⦃x y⦄, x ≺ y → y ≺ x definition transitive := ∀⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z definition equivalence := reflexive R ∧ symmetric R ∧ transitive R definition mk_equivalence (r : reflexive R) (s : symmetric R) (t : transitive R) : equivalence R := and.intro r (and.intro s t) definition irreflexive := ∀x, ¬ x ≺ x definition anti_symmetric := ∀⦃x y⦄, x ≺ y → y ≺ x → x = y definition empty_relation := λa₁ a₂ : A, false definition subrelation (Q R : B → B → Prop) := ∀⦃x y⦄, Q x y → R x y definition inv_image (f : A → B) : A → A → Prop := λa₁ a₂, f a₁ ≺ f a₂ theorem inv_image.trans (f : A → B) (H : transitive R) : transitive (inv_image R f) := λ (a₁ a₂ a₃ : A) (H₁ : inv_image R f a₁ a₂) (H₂ : inv_image R f a₂ a₃), H H₁ H₂ theorem inv_image.irreflexive (f : A → B) (H : irreflexive R) : irreflexive (inv_image R f) := λ (a : A) (H₁ : inv_image R f a a), H (f a) H₁ inductive tc {A : Type} (R : A → A → Prop) : A → A → Prop := | base : ∀a b, R a b → tc R a b | trans : ∀a b c, tc R a b → tc R b c → tc R a c
17cfa2d4541110a71efad8f6394ca71b439f3559
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/localization/num_denom.lean
1b1ff85f10758528578432c160c2c74d415ab07a
[ "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,080
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.localization.fraction_ring import ring_theory.localization.integer import ring_theory.unique_factorization_domain /-! # Numerator and denominator in a localization > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) {S : Type*} [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] namespace is_fraction_ring open is_localization section num_denom variables (A : Type*) [comm_ring A] [is_domain A] [unique_factorization_monoid A] variables {K : Type*} [field K] [algebra A K] [is_fraction_ring A K] lemma exists_reduced_fraction (x : K) : ∃ (a : A) (b : non_zero_divisors A), (∀ {d}, d ∣ a → d ∣ b → is_unit d) ∧ mk' K a b = x := begin obtain ⟨⟨b, b_nonzero⟩, a, hab⟩ := exists_integer_multiple (non_zero_divisors A) x, obtain ⟨a', b', c', no_factor, rfl, rfl⟩ := unique_factorization_monoid.exists_reduced_factors' a b (mem_non_zero_divisors_iff_ne_zero.mp b_nonzero), obtain ⟨c'_nonzero, b'_nonzero⟩ := mul_mem_non_zero_divisors.mp b_nonzero, refine ⟨a', ⟨b', b'_nonzero⟩, @no_factor, _⟩, refine mul_left_cancel₀ (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors b_nonzero) _, simp only [subtype.coe_mk, ring_hom.map_mul, algebra.smul_def] at *, erw [←hab, mul_assoc, mk'_spec' _ a' ⟨b', b'_nonzero⟩], end /-- `f.num x` is the numerator of `x : f.codomain` as a reduced fraction. -/ noncomputable def num (x : K) : A := classical.some (exists_reduced_fraction A x) /-- `f.num x` is the denominator of `x : f.codomain` as a reduced fraction. -/ noncomputable def denom (x : K) : non_zero_divisors A := classical.some (classical.some_spec (exists_reduced_fraction A x)) lemma num_denom_reduced (x : K) {d} : d ∣ num A x → d ∣ denom A x → is_unit d := (classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).1 @[simp] lemma mk'_num_denom (x : K) : mk' K (num A x) (denom A x) = x := (classical.some_spec (classical.some_spec (exists_reduced_fraction A x))).2 variables {A} lemma num_mul_denom_eq_num_iff_eq {x y : K} : x * algebra_map A K (denom A y) = algebra_map A K (num A y) ↔ x = y := ⟨λ h, by simpa only [mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h, λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩ lemma num_mul_denom_eq_num_iff_eq' {x y : K} : y * algebra_map A K (denom A x) = algebra_map A K (num A x) ↔ x = y := ⟨λ h, by simpa only [eq_comm, mk'_num_denom] using eq_mk'_iff_mul_eq.mpr h, λ h, eq_mk'_iff_mul_eq.mp (by rw [h, mk'_num_denom])⟩ lemma num_mul_denom_eq_num_mul_denom_iff_eq {x y : K} : num A y * denom A x = num A x * denom A y ↔ x = y := ⟨λ h, by simpa only [mk'_num_denom] using mk'_eq_of_eq' h, λ h, by rw h⟩ lemma eq_zero_of_num_eq_zero {x : K} (h : num A x = 0) : x = 0 := num_mul_denom_eq_num_iff_eq'.mp (by rw [zero_mul, h, ring_hom.map_zero]) lemma is_integer_of_is_unit_denom {x : K} (h : is_unit (denom A x : A)) : is_integer A x := begin cases h with d hd, have d_ne_zero : algebra_map A K (denom A x) ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors (denom A x).2, use ↑d⁻¹ * num A x, refine trans _ (mk'_num_denom A x), rw [map_mul, map_units_inv, hd], apply mul_left_cancel₀ d_ne_zero, rw [←mul_assoc, mul_inv_cancel d_ne_zero, one_mul, mk'_spec'] end lemma is_unit_denom_of_num_eq_zero {x : K} (h : num A x = 0) : is_unit (denom A x : A) := num_denom_reduced A x (h.symm ▸ dvd_zero _) dvd_rfl end num_denom variables (S) end is_fraction_ring
97d91fe5776437a2ca15e08e4e324bc9a1f0f5b0
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/Mbar/basic.lean
e54bc8bb2612b3e0a425be9917036ef809b1854d
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,736
lean
import data.real.basic import algebra.big_operators.basic import topology.algebra.infinite_sum import data.finset.basic import data.equiv.basic import analysis.normed_space.basic import analysis.specific_limits import data.equiv.basic import Mbar.bounded import pseudo_normed_group.basic import for_mathlib.tsum /-! ## $\overline{\mathcal{M}}_{r'}(S)$ This file contains a definition of `ℳ-bar_{r'}(S) as defined at the very beginning of section 9 of `Analytic.pdf` (p57), and its action of `T⁻¹`. ## Implementation issues We model Tℤ[[T]] as functions ℕ → ℤ which vanish at 0. -/ universe u noncomputable theory open_locale big_operators nnreal section defs set_option old_structure_cmd true /-- `Mbar r' S` is the set of power series `F_s = ∑ a_{s,n}T^n ∈ Tℤ[[T]]` such that `∑_{s,n} |a_{s,n}|r'^n` converges -/ structure Mbar (r' : ℝ≥0) (S : Type u) [fintype S] := (to_fun : S → ℕ → ℤ) (coeff_zero' : ∀ s, to_fun s 0 = 0) (summable' : ∀ s, summable (λ n, (↑(to_fun s n).nat_abs * r' ^ n))) end defs variables {r' : ℝ≥0} {S : Type u} [fintype S] namespace Mbar instance has_coe_to_fun : has_coe_to_fun (Mbar r' S) := ⟨_, Mbar.to_fun⟩ @[simp] lemma coe_mk (x h₁ h₂) : ((⟨x, h₁, h₂⟩ : Mbar r' S) : S → ℕ → ℤ) = x := rfl @[simp] protected lemma coeff_zero (x : Mbar r' S) (s : S) : x s 0 = 0 := x.coeff_zero' s protected lemma summable (x : Mbar r' S) (s : S) : summable (λ n, (↑(x s n).nat_abs * r' ^ n)) := x.summable' s lemma summable_coe_real (x : Mbar r' S) (s : S) : summable (λ n, ∥x s n∥ * r' ^ n) := by simpa only [← nnreal.summable_coe, nnreal.coe_nat_cast, nnreal.coe_nat_abs, nnreal.coe_mul, nnreal.coe_pow] using x.summable s @[ext] lemma ext (x y : Mbar r' S) (h : ⇑x = y) : x = y := by { cases x, cases y, congr, exact h } lemma ext_iff (x y : Mbar r' S) : x = y ↔ (x : S → ℕ → ℤ) = y := ⟨congr_arg _, ext x y⟩ /-- The zero element of `Mbar r' S`, defined as the constant 0-function. -/ def zero : Mbar r' S := { to_fun := 0, coeff_zero' := λ s, rfl, summable' := λ s, by simpa using summable_zero } /-- Addition in `Mbar r' S`, defined as pointwise addition. -/ def add (F : Mbar r' S) (G : Mbar r' S) : Mbar r' S := { to_fun := F + G, coeff_zero' := λ s, by simp [F.coeff_zero s, G.coeff_zero s], summable' := begin intro s, apply nnreal.summable_of_le _ ((F.summable s).add (G.summable s)), intro n, rw [← add_mul, ← nat.cast_add], apply mul_le_mul_right', rw nat.cast_le, exact int.nat_abs_add_le _ _ end } /-- Subtraction in `Mbar r' S`, defined as pointwise subtraction. -/ def sub (F : Mbar r' S) (G : Mbar r' S) : Mbar r' S := { to_fun := F - G, coeff_zero' := λ s, by simp [F.coeff_zero s, G.coeff_zero s], summable' := begin intro s, apply nnreal.summable_of_le _ ((F.summable s).add (G.summable s)), intro n, rw [← add_mul, ← nat.cast_add], apply mul_le_mul_right', rw nat.cast_le, exact int.nat_abs_sub_le _ _ end } /-- Negation in `Mbar r' S`, defined as pointwise negation. -/ def neg (F : Mbar r' S) : Mbar r' S := { to_fun := -F, coeff_zero' := λ s, by simp [F.coeff_zero s], summable' := begin intro s, convert F.summable s using 1, ext n, simp only [pi.neg_apply, int.nat_abs_neg] end } instance : has_zero (Mbar r' S) := ⟨zero⟩ instance : has_add (Mbar r' S) := ⟨add⟩ instance : has_sub (Mbar r' S) := ⟨sub⟩ instance : has_neg (Mbar r' S) := ⟨neg⟩ instance : inhabited (Mbar r' S) := ⟨0⟩ @[simp] lemma coe_zero : ⇑(0 : Mbar r' S) = 0 := rfl @[simp] lemma coe_add (F G : Mbar r' S) : ⇑(F + G : Mbar r' S) = F + G := rfl @[simp] lemma coe_sub (F G : Mbar r' S) : ⇑(F - G : Mbar r' S) = F - G := rfl @[simp] lemma coe_neg (F : Mbar r' S) : ⇑(-F : Mbar r' S) = -F := rfl /-- Tailored scalar multiplication by natural numbers. -/ protected def nsmul (N : ℕ) (F : Mbar r' S) : Mbar r' S := { to_fun := λ s n, N • F s n, coeff_zero' := λ s, by simp only [F.coeff_zero, smul_zero], summable' := λ s, begin simp only [nsmul_eq_mul, int.nat_abs_mul, nat.cast_mul, mul_assoc, int.nat_abs_of_nat, int.nat_cast_eq_coe_nat, nnreal.coe_nat_abs], by_cases hN : N = 0, { simpa only [hN, nat.cast_zero, zero_mul] using summable_zero }, simp only [← nnreal.summable_coe, nnreal.coe_mul], rw [← summable_mul_left_iff], { simp only [coe_nnnorm, nnreal.coe_nat_abs, nnreal.coe_pow], exact F.summable_coe_real s }, { exact_mod_cast hN } end } /-- Tailored scalar multiplication by integers. -/ protected def gsmul (N : ℤ) (F : Mbar r' S) : Mbar r' S := { to_fun := λ s n, N • F s n, coeff_zero' := λ s, by simp only [F.coeff_zero, smul_zero], summable' := λ s, begin simp only [gsmul_eq_mul, int.nat_abs_mul, int.cast_id, nat.cast_mul, mul_assoc], by_cases hN : N.nat_abs = 0, { simpa only [hN, nat.cast_zero, zero_mul] using summable_zero }, simp only [← nnreal.summable_coe, nnreal.coe_mul], rw [← summable_mul_left_iff], { simp only [coe_nnnorm, nnreal.coe_nat_abs, nnreal.coe_pow], exact F.summable_coe_real s }, { exact_mod_cast hN } end } . instance : add_comm_group (Mbar r' S) := { zero := 0, add := (+), sub := has_sub.sub, neg := has_neg.neg, zero_add := by { intros, ext, simp only [coe_zero, zero_add, coe_add] }, add_zero := by { intros, ext, simp only [coe_zero, add_zero, coe_add] }, add_assoc := by { intros, ext, simp only [add_assoc, coe_add] }, add_left_neg := by { intros, ext, simp only [coe_add, coe_neg, coe_zero, pi.add_apply, pi.zero_apply, pi.neg_apply, add_left_neg] }, add_comm := by { intros, ext, simp only [coe_add, add_comm] }, sub_eq_add_neg := by { intros, ext, simp only [coe_sub, coe_add, coe_neg, sub_eq_add_neg] }, nsmul := λ n F, F.nsmul n, nsmul_zero' := λ F, by { ext, simp only [Mbar.nsmul, zero_smul], refl }, nsmul_succ' := λ n F, begin ext, simp only [Mbar.nsmul, nat.succ_eq_add_one, add_smul, one_smul, add_comm, coe_mk, coe_add, pi.add_apply], end, gsmul := λ n F, F.gsmul n, gsmul_zero' := λ F, by { ext, simp only [Mbar.gsmul, zero_smul], refl }, gsmul_succ' := λ n F, begin ext, simp only [Mbar.gsmul, nat.succ_eq_add_one, algebra.id.smul_eq_mul, coe_mk, pi.add_apply, int.coe_nat_succ, int.of_nat_eq_coe, coe_add, add_mul, one_mul, add_comm], end, gsmul_neg' := λ n F, begin ext, simp only [Mbar.gsmul, algebra.id.smul_eq_mul, coe_mk, pi.neg_apply, int.coe_nat_succ, coe_neg, add_mul, one_mul, neg_add_rev, int.neg_succ_of_nat_coe, neg_mul_eq_neg_mul_symm, one_mul], end } /-- The `coeff s n` is the additive homomorphism that sends `x : Mbar r' S` to the coefficient `x_{s,n}`. -/ @[simps] def coeff (s : S) (n : ℕ) : Mbar r' S →+ ℤ := { to_fun := λ x, x s n, map_zero' := rfl, map_add' := λ x y, rfl } /-- The norm of `F : Mbar r' S` as nonnegative real number. It is defined as `∑ s, ∑' n, (↑(F s n).nat_abs * r' ^ n)`. -/ protected def nnnorm (F : Mbar r' S) : ℝ≥0 := ∑ s, ∑' n, (↑(F s n).nat_abs * r' ^ n) instance : has_nnnorm (Mbar r' S) := ⟨Mbar.nnnorm⟩ lemma nnnorm_def (F : Mbar r' S) : ∥F∥₊ = ∑ s, ∑' n, (↑(F s n).nat_abs * r' ^ n) := rfl @[simp] lemma nnnorm_zero : ∥(0 : Mbar r' S)∥₊ = 0 := by simp only [nnnorm_def, Mbar.coe_zero, tsum_zero, nat.cast_zero, zero_mul, pi.zero_apply, zero_le', finset.sum_const_zero, int.nat_abs_zero] @[simp] lemma nnnorm_neg (F : Mbar r' S) : ∥-F∥₊ = ∥F∥₊ := by simp only [nnnorm_def, Mbar.coe_neg, pi.neg_apply, int.nat_abs_neg, int.nat_abs, coe_neg, set.mem_set_of_eq] lemma nnnorm_add_le (F₁ F₂ : Mbar r' S) : ∥F₁ + F₂∥₊ ≤ ∥F₁∥₊ + ∥F₂∥₊ := begin simp only [nnnorm_def, ← finset.sum_add_distrib], refine finset.sum_le_sum _, rintro s -, rw ← tsum_add (F₁.summable s) (F₂.summable s), refine tsum_le_tsum _ ((F₁ + F₂).summable _) ((F₁.summable s).add (F₂.summable s)), intro n, dsimp, rw [← add_mul, ← nat.cast_add], apply mul_le_mul_right', rw nat.cast_le, exact int.nat_abs_add_le _ _ end lemma nnnorm_sum_le {ι : Type*} (s : finset ι) (F : ι → Mbar r' S) : ∥∑ i in s, F i∥₊ ≤ ∑ i in s, ∥F i∥₊ := begin classical, apply finset.induction_on s; clear s, { simp only [finset.sum_empty, nnnorm_zero] }, intros i s his IH, simp only [finset.sum_insert his], exact (nnnorm_add_le _ _).trans (add_le_add le_rfl IH) end instance pseudo_normed_group : pseudo_normed_group (Mbar r' S) := { filtration := λ c, {F | ∥F∥₊ ≤ c}, filtration_mono := λ c₁ c₂ h F hF, le_trans (by exact hF) h, -- `by exact`, why?? zero_mem_filtration := λ c, by { dsimp, rw nnnorm_zero, apply zero_le' }, neg_mem_filtration := λ c F hF, by { dsimp, rwa nnnorm_neg }, add_mem_filtration := λ c₁ c₂ F₁ F₂ hF₁ hF₂, by exact le_trans (nnnorm_add_le _ _) (add_le_add hF₁ hF₂) } lemma mem_filtration_iff (x : Mbar r' S) (c : ℝ≥0) : x ∈ pseudo_normed_group.filtration (Mbar r' S) c ↔ ∥x∥₊ ≤ c := iff.rfl /-- The coercion from `Mbar r' S` to functions `S → ℕ → ℤ`. This is an additive group homomorphism. -/ def coe_hom : Mbar r' S →+ (S → ℕ → ℤ) := add_monoid_hom.mk' coe_fn $ coe_add @[simp] lemma coe_sum {ι : Type*} (s : finset ι) (F : ι → Mbar r' S) : ⇑(∑ i in s, F i) = ∑ i in s, (F i) := show coe_hom (∑ i in s, F i) = ∑ i in s, coe_hom (F i), from add_monoid_hom.map_sum _ _ _ @[simp] lemma coe_gsmul (n : ℤ) (F : Mbar r' S) : ⇑(n • F) = n • F := rfl @[simp] lemma coe_nsmul (n : ℕ) (F : Mbar r' S) : ⇑(n • F) = n • F := rfl @[simp] lemma nnnorm_gsmul (N : ℤ) (F : Mbar r' S) : ∥N • F∥₊ = ∥N∥₊ * ∥F∥₊ := begin simp only [nnnorm_def, finset.mul_sum], apply fintype.sum_congr, intro s, apply nnreal.eq, simp only [nnreal.coe_mul, nnreal.coe_tsum, ← tsum_mul_left, ← mul_assoc, nnreal.coe_nat_abs, coe_nnnorm, coe_gsmul, pi.smul_apply, int.norm_eq_abs, ← abs_mul, ← int.cast_mul, smul_eq_mul], end lemma nnnorm_nsmul (x : Mbar r' S) (N : ℕ) : ∥N • x∥₊ = N • ∥x∥₊ := by { rw [← gsmul_coe_nat, nnnorm_gsmul, nsmul_eq_mul, ← nnreal.coe_nat_abs], refl, } section Tinv /-- The action of T⁻¹. -/ def Tinv_aux {R : Type*} [has_zero R] : (ℕ → R) → ℕ → R := λ F n, if n = 0 then 0 else F (n + 1) @[simp] lemma Tinv_aux_zero {R : Type*} [has_zero R] (f : ℕ → R) : Tinv_aux f 0 = 0 := rfl @[simp] lemma Tinv_aux_ne_zero {R : Type*} [has_zero R] (f : ℕ → R) (i : ℕ) (hi : i ≠ 0) : Tinv_aux f i = f (i + 1) := if_neg hi @[simp] lemma Tinv_aux_succ {R : Type*} [has_zero R] (f : ℕ → R) (i : ℕ) : Tinv_aux f (i + 1) = f (i + 2) := if_neg (nat.succ_ne_zero i) lemma Tinv_aux_summable [h0r : fact (0 < r')] (F : Mbar r' S) (s : S) : summable (λ n, (↑(Tinv_aux (F s) n).nat_abs * r' ^ n)) := begin have : ∀ n:ℕ, r' ^ n = r' ^ n * r' * r'⁻¹, { intro, rw [mul_inv_cancel_right' h0r.out.ne'] }, conv { congr, funext, rw [this, ← mul_assoc] }, apply summable.mul_right, refine nnreal.summable_of_le _ (nnreal.summable_nat_add _ (F.summable s) 1), rintro ⟨i⟩, { simp only [nat.cast_zero, zero_mul, Tinv_aux_zero, zero_le', int.nat_abs_zero] }, { simp only [Tinv_aux_succ, pow_add, mul_assoc, pow_one] } end /-- The `T⁻¹` action on `Mbar r' S`. This is defined, essentially, as a shift in `ℕ` (accounting for the restriction at 0). This is an additive group homomorphism. -/ def Tinv {r : ℝ≥0} {S : Type u} [fintype S] [h0r : fact (0 < r)] : Mbar r S →+ Mbar r S := add_monoid_hom.mk' (λ F, { to_fun := λ s, Tinv_aux (F s), coeff_zero' := λ s, rfl, summable' := Tinv_aux_summable F }) begin intros F G, ext s (_|n), { simp only [add_zero, pi.add_apply, Mbar.coeff_zero] }, { simp only [coe_mk, pi.add_apply, Tinv_aux_succ, coe_add] } end @[simp] lemma Tinv_zero [fact (0 < r')] (F : Mbar r' S) (s : S) : Tinv F s 0 = 0 := rfl @[simp] lemma Tinv_ne_zero [fact (0 < r')] (F : Mbar r' S) (s : S) (i : ℕ) (hi : i ≠ 0) : Tinv F s i = F s (i + 1) := if_neg hi @[simp] lemma Tinv_succ [fact (0 < r')] (F : Mbar r' S) (s : S) (i : ℕ) : Tinv F s (i + 1) = F s (i + 2) := Tinv_aux_succ (F s) i open pseudo_normed_group lemma Tinv_mem_filtration [h0r : fact (0 < r')] : Tinv ∈ filtration (Mbar r' S →+ Mbar r' S) (r'⁻¹) := begin intros c F hF, simp only [Tinv, add_monoid_hom.mk'_apply], change _ ≤ _ at hF, rw mul_comm, apply le_mul_inv_of_mul_le h0r.out.ne', rw [nnnorm_def, finset.sum_mul], apply le_trans _ hF, apply finset.sum_le_sum, rintro s -, rw ← nnreal.tsum_mul_right, conv_rhs { rw [← sum_add_tsum_nat_add' 1 (F.summable s)] }, refine le_add_of_nonneg_of_le zero_le' _, apply tsum_le_tsum, { rintro (_|i), { simp only [nat.cast_zero, zero_mul, Mbar.coeff_zero, int.nat_abs_zero], exact zero_le' }, { simp only [Tinv_aux_succ, mul_assoc, coe_mk, pow_succ'] } }, { exact (Tinv_aux_summable F s).mul_right _ }, { exact (nnreal.summable_nat_add_iff 1).mpr (F.summable s) } end end Tinv /-- `of_mask x mask : Mbar r' S` is `∑ a_{s,n}T^n ∈ Tℤ[[T]]`, where `a_{s,n}` is `x_{s,n}` if `mask n s` is true and `0` otherwise. -/ @[simps] def of_mask (x : Mbar r' S) (mask : S → ℕ → Prop) [∀ s n, decidable (mask s n)] : Mbar r' S := { to_fun := λ s n, if mask s n then x s n else 0, coeff_zero' := λ s, by { split_ifs, { exact x.coeff_zero s }, { refl } }, summable' := λ s, begin apply nnreal.summable_of_le _ (x.summable s), intro n, refine mul_le_mul' _ le_rfl, norm_cast, split_ifs, { refl }, { rw int.nat_abs_zero, exact zero_le' } end } variables (r' S) /-- `geom r' S` is `∑ T^n ∈ Tℤ[[T]]`. In other words, all non-constant coefficients are `1`. -/ @[simps] def geom [hr' : fact (r' < 1)] : Mbar r' S := { to_fun := λ s n, if n = 0 then 0 else 1, coeff_zero' := λ s, if_pos rfl, summable' := λ s, begin have := (normed_ring.summable_geometric_of_norm_lt_1 (r' : ℝ) _), swap, { rw nnreal.norm_eq, exact hr'.out }, simp only [← nnreal.coe_pow, nnreal.summable_coe] at this, apply nnreal.summable_of_le _ this, intro n, refine (mul_le_mul' _ le_rfl).trans (one_mul _).le, split_ifs; simp end } section map variables {r' S} {T : Type u} [fintype T] (f : S → T) open_locale classical lemma has_sum_aux (F : Mbar r' S) : has_sum (λ n : ℕ, (∑ s, ↑(F s n).nat_abs) * r' ^ n) (∑ s, ∑' n, (F s n).nat_abs * r' ^ n) := begin have : (λ (n : ℕ), (∑ (s : S), ↑(F s n).nat_abs) * r' ^ n) = (λ (n : ℕ), ∑ (s : S), (↑(F s n).nat_abs) * r' ^ n), { funext n, rw finset.sum_mul }, rw this, clear this, exact has_sum_sum (λ s _, (F.summable s).has_sum) end /-- Given an element of `Mbar r' S` and a function `f : S → T`, this constructs an associated element of `Mbar r' T`. -/ @[simps] def map : Mbar r' S → Mbar r' T := λ F, { to_fun := λ t n, ∑ s in finset.univ.filter (λ s', f s' = t), F s n, coeff_zero' := λ s, by simp, summable' := λ t, begin have : ∀ (n : ℕ), ↑((∑ (s : S) in finset.univ.filter (λ (s' : S), f s' = t), F s n).nat_abs) * r' ^ n ≤ (∑ s : S, (F s n).nat_abs) * r' ^ n, { intro n, refine mul_le_mul _ (le_refl _) zero_le' zero_le', simp_rw ← nat.cast_sum, apply nat.cast_le.mpr, have : (∑ (s : S) in finset.univ.filter (λ (s' : S), f s' = t), F s n).nat_abs ≤ ∑ (s : S) in finset.univ.filter (λ s', f s' = t), (F s n).nat_abs, { apply nat_abs_sum_le }, refine le_trans this _, apply finset.sum_le_sum_of_subset, { intros t ht, simp }, { apply_instance } }, exact nnreal.summable_of_le this (has_sum.summable (has_sum_aux _)), end } lemma map_id (F : Mbar r' S) : F.map id = F := begin ext s n, simp [finset.sum_filter], end lemma map_comp (F : Mbar r' S) {U : Type*} [fintype U] (g : T → U) : F.map (g ∘ f) = (F.map f).map g := begin ext u n, dsimp, rw ← finset.sum_bUnion, { apply finset.sum_congr, ext s, split, { intro hs, simpa using hs }, { intro hs, simpa using hs }, { tauto } }, { rintros t1 ht1 t2 ht2 h s hs, simp at ht1 ht2 hs ⊢, refine h _, rw [← hs.1, ← hs.2] } end lemma nnnorm_map_le_of_nnnorm_le {c : ℝ≥0} (F : Mbar r' S) (hF : ∥ F ∥₊ ≤ c) : ∥ F.map f ∥₊ ≤ c := begin simp [ Mbar.nnnorm_def ] at *, rw ← tsum_sum at hF ⊢, { refine le_trans (tsum_le_tsum _ _ _) hF, { intros n, simp_rw ← finset.sum_mul, refine mul_le_mul _ (le_refl _) zero_le' zero_le', simp_rw ← nat.cast_sum, rw nat.cast_le, have : ∑ (x : T), (∑ (s : S) in finset.univ.filter (λ (s' : S), f s' = x), F s n).nat_abs ≤ ∑ (x : T), (∑ (s : S) in finset.univ.filter (λ s', f s' = x), (F s n).nat_abs), { apply finset.sum_le_sum, intros t ht, apply nat_abs_sum_le }, refine le_trans this _, rw ← finset.sum_bUnion, apply finset.sum_le_sum_of_subset, { intros t ht, simp }, { intros t1 ht1 t2 ht2 h s hs, simp at ht1 ht2 hs ⊢, apply h, rw [← hs.1, ← hs.2] } }, { apply summable_sum, intros t ht, apply (F.map f).summable }, { apply summable_sum, intros s hs, apply F.summable } }, { intros t ht, apply (F.map f).summable }, { intros s hs, apply F.summable } end end map end Mbar #lint-
53c5f53adcce7701e041c3b64c4a5ad34b3cd333
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/unexpander.lean
02f385f95244066748952b79ad8ef691753dd325
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
326
lean
open Lean PrettyPrinter namespace ns inductive Foo | mk: Foo @[appUnexpander Foo.mk] def unexpadFoo : Lean.PrettyPrinter.Unexpander | `($x) => `(unexpand) def foo := Foo.mk #print foo @[appUnexpander ns.Foo.mk] def unexpadFoo' : Lean.PrettyPrinter.Unexpander | `($x) => `(unexpand) def bar := ns.Foo.mk #print bar end ns
64a21a8db2897c2db426135069b45baadf36b363
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/rat/meta_defs.lean
fbd4c5ce8cb09c1ff06455a06723bfa503a5e148
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,586
lean
/- Copyright (c) 2019 Robert Y. Lewis . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.rat.defs import tactic.core /-! # Meta operations on ℚ This file defines functions for dealing with rational numbers as expressions. They are not defined earlier in the hierarchy, in the `tactic` or `meta` folders, since we do not want to import `data.rat.basic` there. ## Main definitions * `rat.mk_numeral` embeds a rational `q` as a numeral expression into a type supporting the needed operations. It does not need a tactic state. * `rat.reflect` specializes `rat.mk_numeral` to `ℚ`. * `expr.of_rat` behaves like `rat.mk_numeral`, but uses the tactic state to infer the needed structure on the target type. * `expr.to_rat` evaluates a normal numeral expression as a rat. * `expr.eval_rat` evaluates a numeral expression with arithmetic operations as a rat. -/ /-- `rat.mk_numeral q` embeds `q` 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. This function is similar to `expr.of_rat` but takes more hypotheses and is not tactic valued. -/ meta def rat.mk_numeral (type has_zero has_one has_add has_neg has_div : expr) : ℚ → expr | ⟨num, denom, _, _⟩ := let nume := num.mk_numeral type has_zero has_one has_add has_neg in if denom = 1 then nume else let dene := denom.mk_numeral type has_zero has_one has_add in `(@has_div.div.{0} %%type %%has_div %%nume %%dene) section -- Note that here we are disabling the "safety" of reflected, to allow us to reuse `rat.mk_numeral`. -- The usual way to provide the required `reflected` instance would be via rewriting to prove that -- the expression we use here is equivalent. local attribute [semireducible] reflected /-- `rat.reflect q` represents the rational number `q` as a numeral expression of type `ℚ`. -/ meta instance rat.reflect : has_reflect ℚ := rat.mk_numeral `(ℚ) `(by apply_instance : has_zero ℚ) `(by apply_instance : has_one ℚ) `(by apply_instance : has_add ℚ) `(by apply_instance : has_neg ℚ) `(by apply_instance : has_div ℚ) end /-- `rat.to_pexpr q` creates a `pexpr` that will evaluate to `q`. The `pexpr` does not hold any typing information: `to_expr ``((%%(rat.to_pexpr (3/4)) : K))` will create a native `K` numeral `(3/4 : K)`. -/ meta def rat.to_pexpr (q : ℚ) : pexpr := let n := q.num, d := q.denom in if d = 1 then n.to_pexpr else ``(%%n.to_pexpr / %%d.to_pexpr) /-- Evaluates an expression as a rational number, if that expression represents a numeral or the quotient of two numerals. -/ protected meta def expr.to_nonneg_rat : expr → option ℚ | `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, if c : m.coprime n then if h : 1 < n then return ⟨m, n, lt_trans zero_lt_one h, c⟩ else none else none | e := do n ← e.to_nat, return n /-- Evaluates an expression as a rational number, if that expression represents a numeral, the quotient of two numerals, the negation of a numeral, or the negation of the quotient of two numerals. -/ protected meta def expr.to_rat : expr → option ℚ | `(has_neg.neg %%e) := do q ← e.to_nonneg_rat, some (-q) | e := e.to_nonneg_rat /-- Evaluates an expression into a rational number, if that expression is built up from numerals, +, -, *, /, ⁻¹ -/ protected meta def expr.eval_rat : expr → option ℚ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%q) := (*) 2 <$> q.eval_rat | `(bit1 %%q) := (+) 1 <$> (*) 2 <$> q.eval_rat | `(%%a + %%b) := (+) <$> a.eval_rat <*> b.eval_rat | `(%%a - %%b) := has_sub.sub <$> a.eval_rat <*> b.eval_rat | `(%%a * %%b) := (*) <$> a.eval_rat <*> b.eval_rat | `(%%a / %%b) := (/) <$> a.eval_rat <*> b.eval_rat | `(-(%%a)) := has_neg.neg <$> a.eval_rat | `((%%a)⁻¹) := has_inv.inv <$> a.eval_rat | _ := none /-- `expr.of_rat α q` embeds `q` as a numeral expression inside the type `α`. Lean will try to infer the correct type classes on `α`, and the tactic will fail if it cannot. This function is similar to `rat.mk_numeral` but it takes fewer hypotheses and is tactic valued. -/ protected meta def expr.of_rat (α : expr) : ℚ → tactic expr | ⟨(n:ℕ), d, h, c⟩ := do e₁ ← expr.of_nat α n, if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, h, c⟩ := do e₁ ← expr.of_nat α (n+1), e ← (if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂]), tactic.mk_app ``has_neg.neg [e] namespace tactic namespace instance_cache /-- `c.of_rat q` embeds `q` as a numeral expression inside the type `α`. Lean will try to infer the correct type classes on `c.α`, and the tactic will fail if it cannot. This function is similar to `rat.mk_numeral` but it takes fewer hypotheses and is tactic valued. -/ protected meta def of_rat (c : instance_cache) : ℚ → tactic (instance_cache × expr) | ⟨(n:ℕ), d, _, _⟩ := if d = 1 then c.of_nat n else do (c, e₁) ← c.of_nat n, (c, e₂) ← c.of_nat d, c.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, _, _⟩ := do (c, e) ← (if d = 1 then c.of_nat (n+1) else do (c, e₁) ← c.of_nat (n+1), (c, e₂) ← c.of_nat d, c.mk_app ``has_div.div [e₁, e₂]), c.mk_app ``has_neg.neg [e] end instance_cache end tactic
33646bda4173292bde90b29ae87207776de74a3c
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/regular/smul.lean
b45087acf3d3afca7a7798c7f80be605f8a089ed
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,840
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.smul_with_zero import algebra.regular.basic /-! # Action of regular elements on a module We introduce `M`-regular elements, in the context of an `R`-module `M`. The corresponding predicate is called `is_smul_regular`. There are very limited typeclass assumptions on `R` and `M`, but the "mathematical" case of interest is a commutative ring `R` acting an a module `M`. Since the properties are "multiplicative", there is no actual requirement of having an addition, but there is a zero in both `R` and `M`. Smultiplications involving `0` are, of course, all trivial. The defining property is that an element `a ∈ R` is `M`-regular if the smultiplication map `M → M`, defined by `m ↦ a • m`, is injective. This property is the direct generalization to modules of the property `is_left_regular` defined in `algebra/regular`. Lemma `is_smul_regular.is_left_regular_iff` shows that indeed the two notions coincide. -/ variables {R S : Type*} (M : Type*) {a b : R} {s : S} /-- An `M`-regular element is an element `c` such that multiplication on the left by `c` is an injective map `M → M`. -/ def is_smul_regular [has_scalar R M] (c : R) := function.injective ((•) c : M → M) lemma is_left_regular.is_smul_regular [has_mul R] {c : R} (h : is_left_regular c) : is_smul_regular R c := h /-- Left-regular multiplication on `R` is equivalent to `R`-regularity of `R` itself. -/ lemma is_left_regular_iff [has_mul R] {a : R} : is_left_regular a ↔ is_smul_regular R a := iff.rfl lemma is_right_regular.is_smul_regular [has_mul R] {c : R} (h : is_right_regular c) : is_smul_regular R (mul_opposite.op c) := h /-- Right-regular multiplication on `R` is equivalent to `Rᵐᵒᵖ`-regularity of `R` itself. -/ lemma is_right_regular_iff [has_mul R] {a : R} : is_right_regular a ↔ is_smul_regular R (mul_opposite.op a) := iff.rfl namespace is_smul_regular variables {M} section has_scalar variables [has_scalar R M] [has_scalar R S] [has_scalar S M] [is_scalar_tower R S M] /-- The product of `M`-regular elements is `M`-regular. -/ lemma smul (ra : is_smul_regular M a) (rs : is_smul_regular M s) : is_smul_regular M (a • s) := λ a b ab, rs (ra ((smul_assoc _ _ _).symm.trans (ab.trans (smul_assoc _ _ _)))) /-- If an element `b` becomes `M`-regular after multiplying it on the left by an `M`-regular element, then `b` is `M`-regular. -/ lemma of_smul (a : R) (ab : is_smul_regular M (a • s)) : is_smul_regular M s := @function.injective.of_comp _ _ _ (λ m : M, a • m) _ (λ c d cd, ab (by rwa [smul_assoc, smul_assoc])) /-- An element is `M`-regular if and only if multiplying it on the left by an `M`-regular element is `M`-regular. -/ @[simp] lemma smul_iff (b : S) (ha : is_smul_regular M a) : is_smul_regular M (a • b) ↔ is_smul_regular M b := ⟨of_smul _, ha.smul⟩ lemma is_left_regular [has_mul R] {a : R} (h : is_smul_regular R a) : is_left_regular a := h lemma is_right_regular [has_mul R] {a : R} (h : is_smul_regular R (mul_opposite.op a)) : is_right_regular a := h lemma mul [has_mul R] [is_scalar_tower R R M] (ra : is_smul_regular M a) (rb : is_smul_regular M b) : is_smul_regular M (a * b) := ra.smul rb lemma of_mul [has_mul R] [is_scalar_tower R R M] (ab : is_smul_regular M (a * b)) : is_smul_regular M b := by { rw ← smul_eq_mul at ab, exact ab.of_smul _ } @[simp] lemma mul_iff_right [has_mul R] [is_scalar_tower R R M] (ha : is_smul_regular M a) : is_smul_regular M (a * b) ↔ is_smul_regular M b := ⟨of_mul, ha.mul⟩ /-- Two elements `a` and `b` are `M`-regular if and only if both products `a * b` and `b * a` are `M`-regular. -/ lemma mul_and_mul_iff [has_mul R] [is_scalar_tower R R M] : is_smul_regular M (a * b) ∧ is_smul_regular M (b * a) ↔ is_smul_regular M a ∧ is_smul_regular M b := begin refine ⟨_, _⟩, { rintros ⟨ab, ba⟩, refine ⟨ba.of_mul, ab.of_mul⟩ }, { rintros ⟨ha, hb⟩, exact ⟨ha.mul hb, hb.mul ha⟩ } end end has_scalar section monoid variables [monoid R] [mul_action R M] variable (M) /-- One is `M`-regular always. -/ @[simp] lemma one : is_smul_regular M (1 : R) := λ a b ab, by rwa [one_smul, one_smul] at ab variable {M} /-- An element of `R` admitting a left inverse is `M`-regular. -/ lemma of_mul_eq_one (h : a * b = 1) : is_smul_regular M b := of_mul (by { rw h, exact one M }) /-- Any power of an `M`-regular element is `M`-regular. -/ lemma pow (n : ℕ) (ra : is_smul_regular M a) : is_smul_regular M (a ^ n) := begin induction n with n hn, { simp only [one, pow_zero] }, { rw pow_succ, exact (ra.smul_iff (a ^ n)).mpr hn } end /-- An element `a` is `M`-regular if and only if a positive power of `a` is `M`-regular. -/ lemma pow_iff {n : ℕ} (n0 : 0 < n) : is_smul_regular M (a ^ n) ↔ is_smul_regular M a := begin refine ⟨_, pow n⟩, rw [← nat.succ_pred_eq_of_pos n0, pow_succ', ← smul_eq_mul], exact of_smul _, end end monoid section monoid_smul variables [monoid S] [has_scalar R M] [has_scalar R S] [mul_action S M] [is_scalar_tower R S M] /-- An element of `S` admitting a left inverse in `R` is `M`-regular. -/ lemma of_smul_eq_one (h : a • s = 1) : is_smul_regular M s := of_smul a (by { rw h, exact one M }) end monoid_smul section monoid_with_zero variables [monoid_with_zero R] [monoid_with_zero S] [has_zero M] [mul_action_with_zero R M] [mul_action_with_zero R S] [mul_action_with_zero S M] [is_scalar_tower R S M] /-- The element `0` is `M`-regular if and only if `M` is trivial. -/ protected lemma subsingleton (h : is_smul_regular M (0 : R)) : subsingleton M := ⟨λ a b, h (by repeat { rw mul_action_with_zero.zero_smul })⟩ /-- The element `0` is `M`-regular if and only if `M` is trivial. -/ lemma zero_iff_subsingleton : is_smul_regular M (0 : R) ↔ subsingleton M := ⟨λ h, h.subsingleton, λ H a b h, @subsingleton.elim _ H a b⟩ /-- The `0` element is not `M`-regular, on a non-trivial module. -/ lemma not_zero_iff : ¬ is_smul_regular M (0 : R) ↔ nontrivial M := begin rw [nontrivial_iff, not_iff_comm, zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is `M`-regular when `M` is trivial. -/ lemma zero [sM : subsingleton M] : is_smul_regular M (0 : R) := zero_iff_subsingleton.mpr sM /-- The `0` element is not `M`-regular, on a non-trivial module. -/ lemma not_zero [nM : nontrivial M] : ¬ is_smul_regular M (0 : R) := not_zero_iff.mpr nM end monoid_with_zero section comm_semigroup variables [comm_semigroup R] [has_scalar R M] [is_scalar_tower R R M] /-- A product is `M`-regular if and only if the factors are. -/ lemma mul_iff : is_smul_regular M (a * b) ↔ is_smul_regular M a ∧ is_smul_regular M b := begin rw ← mul_and_mul_iff, exact ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩ end end comm_semigroup end is_smul_regular section group variables {G : Type*} [group G] /-- An element of a group acting on a Type is regular. This relies on the availability of the inverse given by groups, since there is no `left_cancel_smul` typeclass. -/ lemma is_smul_regular_of_group [mul_action G R] (g : G) : is_smul_regular R g := begin intros x y h, convert congr_arg ((•) g⁻¹) h using 1; simp [←smul_assoc] end end group section units variables [monoid R] [mul_action R M] /-- Any element in `Rˣ` is `M`-regular. -/ lemma units.is_smul_regular (a : Rˣ) : is_smul_regular M (a : R) := is_smul_regular.of_mul_eq_one a.inv_val /-- A unit is `M`-regular. -/ lemma is_unit.is_smul_regular (ua : is_unit a) : is_smul_regular M a := begin rcases ua with ⟨a, rfl⟩, exact a.is_smul_regular M end end units
d5a396374c39011916c921ce9041a696e1e81407
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/group/units.lean
a0e1279b185574445361421f590fe6986f9a96ae
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,027
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ universe u variable {α : Type u} /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units namespace units variables [monoid α] @[to_additive] instance : has_coe (units α) α := ⟨val⟩ @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : units α → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : units α} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq (units α) := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : units α) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Units of a monoid form a group. -/ @[to_additive] instance : group (units α) := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := λ u, ⟨u.2, u.1, u.4, u.3⟩, mul_left_inv := λ u, ext u.inv_val } variables (a b : units α) {c : units α} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl attribute [norm_cast] add_units.coe_add @[simp, norm_cast, to_additive] lemma coe_one : ((1 : units α) : α) = 1 := rfl attribute [norm_cast] add_units.coe_zero @[simp, norm_cast, to_additive] lemma coe_eq_one {a : units α} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[to_additive] lemma val_coe : (↑a : α) = a.val := rfl @[norm_cast, to_additive] lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl attribute [norm_cast] add_units.coe_neg @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {u : units α} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv_of_eq {u : units α} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited (units α) := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : units α} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : units α} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := suffices ↑u₁ * (↑u₂⁻¹ : α) = 1, by exact inv_eq_of_mul_eq_one this, by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : units α) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : units α) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : units α} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : units α) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, (u : M) = a @[nontriviality] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv ▸ ⟨v * u, (units.coe_mul v u).symm⟩) lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : units M := classical.some h lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := classical.some_spec h end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
448e1a851987846684ef128fa76efe07fd350fef
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/1293.lean
19c364817c3e9ce22ec92524c8a1fdf91d61d154
[ "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
378
lean
open expr tactic example : true := by whnf (var 0) >> return () example : true := by whnf (app (var 0) (var 0)) >> return () example : true := by zeta (var 0) >> return () example : true := by unify (var 0) (var 0) >> return () example : true := by is_def_eq (var 0) (var 0) >> return () example foo trivial := by do t ← infer_type (var 0), to_expr `(trivial) >>= apply
773bbc528eb9f1f74583477627b21059fc66ef68
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1623.lean
c5590950aee70c901f5f8a2f11695062936f541e
[ "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
158
lean
section parameters {A : Type} (R : list A → Prop) structure foo (x : list A) : Prop := (bar : R x) structure bar (x : Type) structure baz extends bar A end
65218af1342c882f2467baf9134f4c72fcfff0a0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/constructor_tactic.lean
148ff300f41eedc256798a3b9de958249c2a8408
[]
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
366
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.function namespace Mathlib namespace tactic /- Return target after instantiating metavars and whnf -/
c931d380bd528af78d563a12743ccb9855770192
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/vector2.lean
287e9c0cc37131e61e7fdd082cc32c3605987e30
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
379
lean
import logic data.nat.basic open nat inductive vector (A : Type) : nat → Type := vnil : vector A zero, vcons : Π {n : nat}, A → vector A n → vector A (succ n) namespace vector theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ := assume h, no_confusion h (λ n h t, h) end vector
3f0989bfccca5e0b1fdc7dc5810394cfd4349cff
5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65
/src/exercises/src_15_negating_quantifiers.lean
10c44cac1a856bebea3e8c605fc2b30603642b5f
[]
no_license
gihanmarasingha/mth1001_tutorial
8e0817feeb96e7c1bb3bac49b63e3c9a3a329061
bb277eebd5013766e1418365b91416b406275130
refs/heads/master
1,675,008,746,310
1,607,993,443,000
1,607,993,443,000
321,511,270
3
0
null
null
null
null
UTF-8
Lean
false
false
1,662
lean
import tactic.linarith namespace mth1001 section negating_quantifiers /- We *can* deal with negated quantified statements using `intro`, as we did before for other negated statements. -/ -- Exercise 081: -- Finish the proof below using `specialize` and `linarith`. -- *Note*, `linarith` can prove `false` if there is a contradiction amongst the premises. example : ¬(∀ x : ℤ, 2 * x + 6 = 0) := begin intro h, sorry end /- A more natural approach is to recognise that `¬(∀ x, P x)` can always be rewritten as `∃ x, ¬(P x)`, where `P` is any function (more accurately a *predicate*) depending on `x`. The Lean tactic `push_neg`, which we've seen before, accomplishes this transformation. -/ -- Exercise 082: -- Below, `push_neg` transforms the goal into `∃ x : ℤ, 2 * x + 6 ≠ 0`. example : ¬(∀ x : ℤ, 2 * x + 6 = 0) := begin push_neg, sorry end -- Exercise 083: -- Solve the following using `push_neg` example : ¬(∀ x : ℤ, x > 5) := begin sorry end /- Negating existential quantifiers follows a similar principle. We begin by using `intro`. -/ -- Exercise 084: -- Use `cases` and `linarith` to prove the following result. example : ¬(∃ x : ℤ, (x + 2 ≥ 3) ∧ (2 * x + 10 ≤ 8)) := begin intro h, sorry end -- Exercise 085: /- An alternative approach is to recognise that `¬(∃ x, P x)` is equivalent to `∀ x, ¬(P x)`. Lean offers this method via `push_neg`. Finish the proof below. -/ example : ¬(∃ x : ℤ, (x + 2 ≥ 3) ∧ (2 * x + 10 ≤ 8)) := begin push_neg, intro x, by_cases h : x + 2 < 3, { sorry, }, { sorry, }, end end negating_quantifiers end mth1001
cf89dc0938db427aed56789e1ea94a1e64733af8
d642a6b1261b2cbe691e53561ac777b924751b63
/src/tactic/ext.lean
1d6e1a62f586d7206f57bd7e929c10163a0b9a40
[ "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
9,282
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.rcases data.list.defs data.prod data.sum universes u₁ u₂ open interactive interactive.types open lean.parser nat tactic /-- `derive_struct_ext_lemma n` generates an extensionality lemma based on the equality of all non-propositional projections. On the following: ``` @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` `derive_struct_lemma` generates: ``` foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y ``` -/ meta def derive_struct_ext_lemma (n : name) : tactic name := do e ← get_env, fs ← e.structure_fields n, d ← get_decl n, n ← resolve_constant n, let r := @expr.const tt n $ d.univ_params.map level.param, (args,_) ← infer_type r >>= mk_local_pis, let args := args.map expr.to_implicit, let t := r.mk_app args, x ← mk_local_def `x t, y ← mk_local_def `y t, let args_x := args ++ [x], let args_y := args ++ [y], bs ← fs.mmap $ λ f, do { d ← get_decl (n ++ f), let a := @expr.const tt (n ++ f) $ d.univ_params.map level.param, t ← infer_type a, s ← infer_type t, if s ≠ `(Prop) then do let x := a.mk_app args_x, let y := a.mk_app args_y, t ← infer_type x, t' ← infer_type y, some <$> if t = t' then mk_app `eq [x,y] >>= mk_local_def `h else mk_mapp `heq [none,x,none,y] >>= mk_local_def `h else pure none }, let bs := bs.filter_map id, t ← mk_app `eq [x,y], t ← pis (args ++ [x,y] ++ bs) t, pr ← run_async $ do { (_,pr) ← solve_aux t (do { args ← intron args.length, x ← intro1, y ← intro1, cases x, cases y, bs.mmap' (λ _, do e ← intro1, cases e), reflexivity }), instantiate_mvars pr }, let decl_n := n <.> "ext", decl_n <$ add_decl (declaration.thm decl_n d.univ_params t pr) meta def get_ext_subject : expr → tactic name | (expr.pi n bi d b) := do v ← mk_local' n bi d, b' ← whnf $ b.instantiate_var v, get_ext_subject b' | (expr.app _ e) := do t ← infer_type e >>= instantiate_mvars >>= head_beta, if t.get_app_fn.is_constant then pure $ t.get_app_fn.const_name else if t.is_pi then pure $ name.mk_numeral 0 name.anonymous else if t.is_sort then pure $ name.mk_numeral 1 name.anonymous else do t ← pp t, fail format!"only constants and Pi types are supported: {t}" | e := fail format!"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}" open native @[reducible] def ext_param_type := option name ⊕ option name meta def opt_minus : lean.parser (option name → ext_param_type) := sum.inl <$ tk "-" <|> pure sum.inr meta def ext_param := opt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets "(" ")" (tk "→" <|> tk "->") <|> none <$ tk "*" <|> some <$> ident ) meta def saturate_fun : name → tactic expr | (name.mk_numeral 0 name.anonymous) := do v₀ ← mk_mvar, v₁ ← mk_mvar, return $ v₀.imp v₁ | (name.mk_numeral 1 name.anonymous) := do u ← mk_meta_univ, pure $ expr.sort u | n := do e ← resolve_constant n >>= mk_const, a ← get_arity e, e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar) meta def equiv_type_constr (n n' : name) : tactic unit := do e ← saturate_fun n, e' ← saturate_fun n', unify e e' <|> fail format!"{n} and {n'} are not definitionally equal types" /-- Tag lemmas of the form: ``` @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` The attribute indexes extensionality lemma using the type of the objects (i.e. `my_collection`) which it gets from the statement of the lemma. In some cases, the same lemma can be used to state the extensionality of multiple types that are definitionally equivalent. ``` attribute [ext [(→),thunk,stream]] funext ``` Those parameters are cumulative. The following are equivalent: ``` attribute [ext [(→),thunk]] funext attribute [ext [stream]] funext ``` and ``` attribute [ext [(→),thunk,stream]] funext ``` One removes type names from the list for one lemma with: ``` attribute [ext [-stream,-thunk]] funext ``` Also, the following: ``` @[ext] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` is equivalent to ``` @[ext *] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` This allows us specify type synonyms along with the type that referred to in the lemma statement. ``` @[ext [*,my_type_synonym]] lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` Attribute `ext` can be applied to a structure to generate its extensionality lemma: ``` @[ext] structure foo (α : Type*) := (x y : ℕ) (z : {z // z < x}) (k : α) (h : x < y) ``` will generate: ``` @[ext] lemma foo.ext : ∀ {α : Type u_1} (x y : foo α), x.x = y.x → x.y = y.y → x.z == y.z → x.k = y.k → x = y ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute (name_map name) (bool × list ext_param_type × list name × list (name × name)) := { name := `ext, descr := "lemmas usable by `ext` tactic", cache_cfg := { mk_cache := λ ls, do { attrs ← ls.mmap $ λ l, do { ⟨_,_,ls,_⟩ ← extensional_attribute.get_param l, pure $ prod.mk <$> ls <*> pure l }, pure $ rb_map.of_list $ attrs.join }, dependencies := [] }, parser := do { ls ← pure <$> ext_param <|> list_of ext_param <|> pure [], m ← extensional_attribute.get_cache, pure $ (ff,ls,[],m.to_list) }, after_set := some $ λ n _ b, do (ff,ls,_,ls') ← extensional_attribute.get_param n | pure (), e ← get_env, n ← if (e.structure_fields n).is_some then derive_struct_ext_lemma n else pure n, s ← mk_const n >>= infer_type >>= get_ext_subject, let (rs,ls'') := if ls.empty then ([],[s]) else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)), ls''.mmap' (equiv_type_constr s), let l := ls'' ∪ (ls'.filter $ λ l, prod.snd l = n).map prod.fst \ rs, extensional_attribute.set n (tt,[],l,[]) b } attribute [ext] array.ext propext prod.ext attribute [ext [(→),thunk]] _root_.funext namespace ulift @[ext] lemma ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y := begin cases X, cases Y, dsimp at w, rw w, end end ulift namespace plift @[ext] lemma ext {P : Prop} (a b : plift P) : a = b := begin cases a, cases b, refl end end plift namespace tactic meta def try_intros : ext_patt → tactic ext_patt | [] := try intros $> [] | (x::xs) := do tgt ← target >>= whnf, if tgt.is_pi then rintro [x] >> try_intros xs else pure (x :: xs) meta def ext1 (xs : ext_patt) (cfg : apply_cfg := {}) : tactic ext_patt := do subject ← target >>= get_ext_subject, m ← extensional_attribute.get_cache, do { rule ← m.find subject, applyc rule cfg } <|> do { ls ← attribute.get_instances `ext, ls.any_of (λ n, applyc n cfg) } <|> fail format!"no applicable extensionality rule found for {subject}", try_intros xs meta def ext : ext_patt → option ℕ → tactic unit | _ (some 0) := skip | xs n := focus1 $ do ys ← ext1 xs, try (ext ys (nat.pred <$> n)) local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `ext`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. -/ meta def interactive.ext1 (xs : parse ext_parse) : tactic unit := ext1 xs $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. When trying to prove: ``` α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ``` α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : parse ext_parse → parse (tk ":" *> small_nat)? → tactic unit | [] (some n) := iterate_range 1 n (ext1 [] $> ()) | [] none := repeat1 (ext1 [] $> ()) | xs n := tactic.ext xs n end tactic
93930b9195d055241185e1d1b92a9c9faf4adbd8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/matrix/transvection.lean
380e89a252cd1c253d1e95acc737f1678431b8ac
[ "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
33,163
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 linear_algebra.matrix.determinant import linear_algebra.matrix.trace import linear_algebra.matrix.reindex import tactic.field_simp import data.matrix.basis /-! # Transvections Transvections are matrices of the form `1 + std_basis_matrix i j c`, where `std_basis_matrix i j c` is the basic matrix with a `c` at position `(i, j)`. Multiplying by such a transvection on the left (resp. on the right) amounts to adding `c` times the `j`-th row to to the `i`-th row (resp `c` times the `i`-th column to the `j`-th column). Therefore, they are useful to present algorithms operating on rows and columns. Transvections are a special case of *elementary matrices* (according to most references, these also contain the matrices exchanging rows, and the matrices multiplying a row by a constant). We show that, over a field, any matrix can be written as `L ⬝ D ⬝ L'`, where `L` and `L'` are products of transvections and `D` is diagonal. In other words, one can reduce a matrix to diagonal form by operations on its rows and columns, a variant of Gauss' pivot algorithm. ## Main definitions and results * `transvection i j c` is the matrix equal to `1 + std_basis_matrix i j c`. * `transvection_struct n R` is a structure containing the data of `i, j, c` and a proof that `i ≠ j`. These are often easier to manipulate than straight matrices, especially in inductive arguments. * `exists_list_transvec_mul_diagonal_mul_list_transvec` states that any matrix `M` over a field can be written in the form `t_1 ⬝ ... ⬝ t_k ⬝ D ⬝ t'_1 ⬝ ... ⬝ t'_l`, where `D` is diagonal and the `t_i`, `t'_j` are transvections. * `diagonal_transvection_induction` shows that a property which is true for diagonal matrices and transvections, and invariant under product, is true for all matrices. * `diagonal_transvection_induction_of_det_ne_zero` is the same statement over invertible matrices. ## Implementation details The proof of the reduction results is done inductively on the size of the matrices, reducing an `(r + 1) × (r + 1)` matrix to a matrix whose last row and column are zeroes, except possibly for the last diagonal entry. This step is done as follows. If all the coefficients on the last row and column are zero, there is nothing to do. Otherwise, one can put a nonzero coefficient in the last diagonal entry by a row or column operation, and then subtract this last diagonal entry from the other entries in the last row and column to make them vanish. This step is done in the type `fin r ⊕ unit`, where `fin r` is useful to choose arbitrarily some order in which we cancel the coefficients, and the sum structure is useful to use the formalism of block matrices. To proceed with the induction, we reindex our matrices to reduce to the above situation. -/ universes u₁ u₂ namespace matrix open_locale matrix variables (n p : Type*) (R : Type u₂) {𝕜 : Type*} [field 𝕜] variables [decidable_eq n] [decidable_eq p] variables [comm_ring R] section transvection variables {R n} (i j : n) /-- The transvection matrix `transvection i j c` is equal to the identity plus `c` at position `(i, j)`. Multiplying by it on the left (as in `transvection i j c ⬝ M`) corresponds to adding `c` times the `j`-th line of `M` to its `i`-th line. Multiplying by it on the right corresponds to adding `c` times the `i`-th column to the `j`-th column. -/ def transvection (c : R) : matrix n n R := 1 + matrix.std_basis_matrix i j c @[simp] lemma transvection_zero : transvection i j (0 : R) = 1 := by simp [transvection] section variable [fintype n] /-- A transvection matrix is obtained from the identity by adding `c` times the `j`-th row to the `i`-th row. -/ lemma update_row_eq_transvection (c : R) : update_row (1 : matrix n n R) i (((1 : matrix n n R)) i + c • (1 : matrix n n R) j) = transvection i j c := begin ext a b, by_cases ha : i = a; by_cases hb : j = b, { simp only [update_row, transvection, ha, hb, function.update_same, std_basis_matrix.apply_same, pi.add_apply, one_apply_eq, pi.smul_apply, mul_one, algebra.id.smul_eq_mul], }, { simp only [update_row, transvection, ha, hb, std_basis_matrix.apply_of_ne, function.update_same, pi.add_apply, ne.def, not_false_iff, pi.smul_apply, and_false, one_apply_ne, algebra.id.smul_eq_mul, mul_zero] }, { simp only [update_row, transvection, ha, ne.symm ha, std_basis_matrix.apply_of_ne, add_zero, algebra.id.smul_eq_mul, function.update_noteq, ne.def, not_false_iff, dmatrix.add_apply, pi.smul_apply, mul_zero, false_and] }, { simp only [update_row, transvection, ha, hb, ne.symm ha, std_basis_matrix.apply_of_ne, add_zero, algebra.id.smul_eq_mul, function.update_noteq, ne.def, not_false_iff, and_self, dmatrix.add_apply, pi.smul_apply, mul_zero] } end lemma transvection_mul_transvection_same (h : i ≠ j) (c d : R) : transvection i j c ⬝ transvection i j d = transvection i j (c + d) := by simp [transvection, matrix.add_mul, matrix.mul_add, h, h.symm, add_smul, add_assoc, std_basis_matrix_add] @[simp] lemma transvection_mul_apply_same (b : n) (c : R) (M : matrix n n R) : (transvection i j c ⬝ M) i b = M i b + c * M j b := by simp [transvection, matrix.add_mul] @[simp] lemma mul_transvection_apply_same (a : n) (c : R) (M : matrix n n R) : (M ⬝ transvection i j c) a j = M a j + c * M a i := by simp [transvection, matrix.mul_add, mul_comm] @[simp] lemma transvection_mul_apply_of_ne (a b : n) (ha : a ≠ i) (c : R) (M : matrix n n R) : (transvection i j c ⬝ M) a b = M a b := by simp [transvection, matrix.add_mul, ha] @[simp] lemma mul_transvection_apply_of_ne (a b : n) (hb : b ≠ j) (c : R) (M : matrix n n R) : (M ⬝ transvection i j c) a b = M a b := by simp [transvection, matrix.mul_add, hb] @[simp] lemma det_transvection_of_ne (h : i ≠ j) (c : R) : det (transvection i j c) = 1 := by rw [← update_row_eq_transvection i j, det_update_row_add_smul_self _ h, det_one] end variables (R n) /-- A structure containing all the information from which one can build a nontrivial transvection. This structure is easier to manipulate than transvections as one has a direct access to all the relevant fields. -/ @[nolint has_inhabited_instance] structure transvection_struct := (i j : n) (hij : i ≠ j) (c : R) instance [nontrivial n] : nonempty (transvection_struct n R) := by { choose x y hxy using exists_pair_ne n, exact ⟨⟨x, y, hxy, 0⟩⟩ } namespace transvection_struct variables {R n} /-- Associating to a `transvection_struct` the corresponding transvection matrix. -/ def to_matrix (t : transvection_struct n R) : matrix n n R := transvection t.i t.j t.c @[simp] lemma to_matrix_mk (i j : n) (hij : i ≠ j) (c : R) : transvection_struct.to_matrix ⟨i, j, hij, c⟩ = transvection i j c := rfl @[simp] protected lemma det [fintype n] (t : transvection_struct n R) : det t.to_matrix = 1 := det_transvection_of_ne _ _ t.hij _ @[simp] lemma det_to_matrix_prod [fintype n] (L : list (transvection_struct n 𝕜)) : det ((L.map to_matrix).prod) = 1 := begin induction L with t L IH, { simp }, { simp [IH], } end /-- The inverse of a `transvection_struct`, designed so that `t.inv.to_matrix` is the inverse of `t.to_matrix`. -/ @[simps] protected def inv (t : transvection_struct n R) : transvection_struct n R := { i := t.i, j := t.j, hij := t.hij, c := - t.c } section variable [fintype n] lemma inv_mul (t : transvection_struct n R) : t.inv.to_matrix ⬝ t.to_matrix = 1 := by { rcases t, simp [to_matrix, transvection_mul_transvection_same, t_hij] } lemma mul_inv (t : transvection_struct n R) : t.to_matrix ⬝ t.inv.to_matrix = 1 := by { rcases t, simp [to_matrix, transvection_mul_transvection_same, t_hij] } lemma reverse_inv_prod_mul_prod (L : list (transvection_struct n R)) : (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (L.map to_matrix).prod = 1 := begin induction L with t L IH, { simp }, { suffices : (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (t.inv.to_matrix ⬝ t.to_matrix) ⬝ (L.map to_matrix).prod = 1, by simpa [matrix.mul_assoc], simpa [inv_mul] using IH, } end lemma prod_mul_reverse_inv_prod (L : list (transvection_struct n R)) : (L.map to_matrix).prod ⬝ (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod = 1 := begin induction L with t L IH, { simp }, { suffices : t.to_matrix ⬝ ((L.map to_matrix).prod ⬝ (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod) ⬝ t.inv.to_matrix = 1, by simpa [matrix.mul_assoc], simp_rw [IH, matrix.mul_one, t.mul_inv], } end end variables (p) open sum /-- Given a `transvection_struct` on `n`, define the corresponding `transvection_struct` on `n ⊕ p` using the identity on `p`. -/ def sum_inl (t : transvection_struct n R) : transvection_struct (n ⊕ p) R := { i := inl t.i, j := inl t.j, hij := by simp [t.hij], c := t.c } lemma to_matrix_sum_inl (t : transvection_struct n R) : (t.sum_inl p).to_matrix = from_blocks t.to_matrix 0 0 1 := begin cases t, ext a b, cases a; cases b, { by_cases h : a = b; simp [transvection_struct.sum_inl, transvection, h, std_basis_matrix], }, { simp [transvection_struct.sum_inl, transvection] }, { simp [transvection_struct.sum_inl, transvection] }, { by_cases h : a = b; simp [transvection_struct.sum_inl, transvection, h] }, end @[simp] lemma sum_inl_to_matrix_prod_mul [fintype n] [fintype p] (M : matrix n n R) (L : list (transvection_struct n R)) (N : matrix p p R) : (L.map (to_matrix ∘ sum_inl p)).prod ⬝ from_blocks M 0 0 N = from_blocks ((L.map to_matrix).prod ⬝ M) 0 0 N := begin induction L with t L IH, { simp }, { simp [matrix.mul_assoc, IH, to_matrix_sum_inl, from_blocks_multiply], }, end @[simp] lemma mul_sum_inl_to_matrix_prod [fintype n] [fintype p] (M : matrix n n R) (L : list (transvection_struct n R)) (N : matrix p p R) : (from_blocks M 0 0 N) ⬝ (L.map (to_matrix ∘ sum_inl p)).prod = from_blocks (M ⬝ (L.map to_matrix).prod) 0 0 N := begin induction L with t L IH generalizing M N, { simp }, { simp [IH, to_matrix_sum_inl, from_blocks_multiply], }, end variable {p} /-- Given a `transvection_struct` on `n` and an equivalence between `n` and `p`, define the corresponding `transvection_struct` on `p`. -/ def reindex_equiv (e : n ≃ p) (t : transvection_struct n R) : transvection_struct p R := { i := e t.i, j := e t.j, hij := by simp [t.hij], c := t.c } variables [fintype n] [fintype p] lemma to_matrix_reindex_equiv (e : n ≃ p) (t : transvection_struct n R) : (t.reindex_equiv e).to_matrix = reindex_alg_equiv R e t.to_matrix := begin cases t, ext a b, simp only [reindex_equiv, transvection, mul_boole, algebra.id.smul_eq_mul, to_matrix_mk, minor_apply, reindex_apply, dmatrix.add_apply, pi.smul_apply, reindex_alg_equiv_apply], by_cases ha : e t_i = a; by_cases hb : e t_j = b; by_cases hab : a = b; simp [ha, hb, hab, ← e.apply_eq_iff_eq_symm_apply, std_basis_matrix] end lemma to_matrix_reindex_equiv_prod (e : n ≃ p) (L : list (transvection_struct n R)) : (L.map (to_matrix ∘ (reindex_equiv e))).prod = reindex_alg_equiv R e (L.map to_matrix).prod := begin induction L with t L IH, { simp }, { simp only [to_matrix_reindex_equiv, IH, function.comp_app, list.prod_cons, mul_eq_mul, reindex_alg_equiv_apply, list.map], exact (reindex_alg_equiv_mul _ _ _ _).symm } end end transvection_struct end transvection /-! # Reducing matrices by left and right multiplication by transvections In this section, we show that any matrix can be reduced to diagonal form by left and right multiplication by transvections (or, equivalently, by elementary operations on lines and columns). The main step is to kill the last row and column of a matrix in `fin r ⊕ unit` with nonzero last coefficient, by subtracting this coefficient from the other ones. The list of these operations is recorded in `list_transvec_col M` and `list_transvec_row M`. We have to analyze inductively how these operations affect the coefficients in the last row and the last column to conclude that they have the desired effect. Once this is done, one concludes the reduction by induction on the size of the matrices, through a suitable reindexing to identify any fintype with `fin r ⊕ unit`. -/ namespace pivot variables {R} {r : ℕ} (M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) open sum unit fin transvection_struct /-- A list of transvections such that multiplying on the left with these transvections will replace the last column with zeroes. -/ def list_transvec_col : list (matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) := list.of_fn $ λ i : fin r, transvection (inl i) (inr star) $ -M (inl i) (inr star) / M (inr star) (inr star) /-- A list of transvections such that multiplying on the right with these transvections will replace the last row with zeroes. -/ def list_transvec_row : list (matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) := list.of_fn $ λ i : fin r, transvection (inr star) (inl i) $ -M (inr star) (inl i) / M (inr star) (inr star) /-- Multiplying by some of the matrices in `list_transvec_col M` does not change the last row. -/ lemma list_transvec_col_mul_last_row_drop (i : fin r ⊕ unit) {k : ℕ} (hk : k ≤ r) : (((list_transvec_col M).drop k).prod ⬝ M) (inr star) i = M (inr star) i := begin apply nat.decreasing_induction' _ hk, { simp only [list_transvec_col, list.length_of_fn, matrix.one_mul, list.drop_eq_nil_of_le, list.prod_nil], }, { assume n hn hk IH, have hn' : n < (list_transvec_col M).length, by simpa [list_transvec_col] using hn, rw ← list.cons_nth_le_drop_succ hn', simpa [list_transvec_col, matrix.mul_assoc] } end /-- Multiplying by all the matrices in `list_transvec_col M` does not change the last row. -/ lemma list_transvec_col_mul_last_row (i : fin r ⊕ unit) : ((list_transvec_col M).prod ⬝ M) (inr star) i = M (inr star) i := by simpa using list_transvec_col_mul_last_row_drop M i (zero_le _) /-- Multiplying by all the matrices in `list_transvec_col M` kills all the coefficients in the last column but the last one. -/ lemma list_transvec_col_mul_last_col (hM : M (inr star) (inr star) ≠ 0) (i : fin r) : ((list_transvec_col M).prod ⬝ M) (inl i) (inr star) = 0 := begin suffices H : ∀ (k : ℕ), k ≤ r → (((list_transvec_col M).drop k).prod ⬝ M) (inl i) (inr star) = if k ≤ i then 0 else M (inl i) (inr star), by simpa only [if_true, list.drop.equations._eqn_1] using H 0 (zero_le _), assume k hk, apply nat.decreasing_induction' _ hk, { simp only [list_transvec_col, list.length_of_fn, matrix.one_mul, list.drop_eq_nil_of_le, list.prod_nil], rw if_neg, simpa only [not_le] using i.2 }, { assume n hn hk IH, have hn' : n < (list_transvec_col M).length, by simpa [list_transvec_col] using hn, let n' : fin r := ⟨n, hn⟩, rw ← list.cons_nth_le_drop_succ hn', have A : (list_transvec_col M).nth_le n hn' = transvection (inl n') (inr star) (-M (inl n') (inr star) / M (inr star) (inr star)), by simp [list_transvec_col], simp only [matrix.mul_assoc, A, matrix.mul_eq_mul, list.prod_cons], by_cases h : n' = i, { have hni : n = i, { cases i, simp only [subtype.mk_eq_mk] at h, simp [h] }, rw [h, transvection_mul_apply_same, IH, list_transvec_col_mul_last_row_drop _ _ hn, ← hni], field_simp [hM] }, { have hni : n ≠ i, { rintros rfl, cases i, simpa using h }, simp only [transvection_mul_apply_of_ne, ne.def, not_false_iff, ne.symm h], rw IH, rcases le_or_lt (n+1) i with hi|hi, { simp only [hi, n.le_succ.trans hi, if_true] }, { rw [if_neg, if_neg], { simpa only [hni.symm, not_le, or_false] using nat.lt_succ_iff_lt_or_eq.1 hi }, { simpa only [not_le] using hi } } } } end /-- Multiplying by some of the matrices in `list_transvec_row M` does not change the last column. -/ lemma mul_list_transvec_row_last_col_take (i : fin r ⊕ unit) {k : ℕ} (hk : k ≤ r) : (M ⬝ ((list_transvec_row M).take k).prod) i (inr star) = M i (inr star) := begin induction k with k IH, { simp only [matrix.mul_one, list.take_zero, list.prod_nil], }, { have hkr : k < r := hk, let k' : fin r := ⟨k, hkr⟩, have : (list_transvec_row M).nth k = ↑(transvection (inr unit.star) (inl k') (-M (inr unit.star) (inl k') / M (inr unit.star) (inr unit.star))), { simp only [list_transvec_row, list.of_fn_nth_val, hkr, dif_pos, list.nth_of_fn], refl }, simp only [list.take_succ, ← matrix.mul_assoc, this, list.prod_append, matrix.mul_one, matrix.mul_eq_mul, list.prod_cons, list.prod_nil, option.to_list_some], rw [mul_transvection_apply_of_ne, IH hkr.le], simp only [ne.def, not_false_iff], } end /-- Multiplying by all the matrices in `list_transvec_row M` does not change the last column. -/ lemma mul_list_transvec_row_last_col (i : fin r ⊕ unit) : (M ⬝ (list_transvec_row M).prod) i (inr star) = M i (inr star) := begin have A : (list_transvec_row M).length = r, by simp [list_transvec_row], rw [← list.take_length (list_transvec_row M), A], simpa using mul_list_transvec_row_last_col_take M i le_rfl, end /-- Multiplying by all the matrices in `list_transvec_row M` kills all the coefficients in the last row but the last one. -/ lemma mul_list_transvec_row_last_row (hM : M (inr star) (inr star) ≠ 0) (i : fin r) : (M ⬝ (list_transvec_row M).prod) (inr star) (inl i) = 0 := begin suffices H : ∀ (k : ℕ), k ≤ r → (M ⬝ ((list_transvec_row M).take k).prod) (inr star) (inl i) = if k ≤ i then M (inr star) (inl i) else 0, { have A : (list_transvec_row M).length = r, by simp [list_transvec_row], rw [← list.take_length (list_transvec_row M), A], have : ¬ (r ≤ i), by simpa using i.2, simpa only [this, ite_eq_right_iff] using H r le_rfl }, assume k hk, induction k with n IH, { simp only [if_true, matrix.mul_one, list.take_zero, zero_le', list.prod_nil] }, { have hnr : n < r := hk, let n' : fin r := ⟨n, hnr⟩, have A : (list_transvec_row M).nth n = ↑(transvection (inr unit.star) (inl n') (-M (inr unit.star) (inl n') / M (inr unit.star) (inr unit.star))), { simp only [list_transvec_row, list.of_fn_nth_val, hnr, dif_pos, list.nth_of_fn], refl }, simp only [list.take_succ, A, ← matrix.mul_assoc, list.prod_append, matrix.mul_one, matrix.mul_eq_mul, list.prod_cons, list.prod_nil, option.to_list_some], by_cases h : n' = i, { have hni : n = i, { cases i, simp only [subtype.mk_eq_mk] at h, simp only [h, coe_mk] }, have : ¬ (n.succ ≤ i), by simp only [← hni, n.lt_succ_self, not_le], simp only [h, mul_transvection_apply_same, list.take, if_false, mul_list_transvec_row_last_col_take _ _ hnr.le, hni.le, this, if_true, IH hnr.le], field_simp [hM] }, { have hni : n ≠ i, { rintros rfl, cases i, simpa using h }, simp only [IH hnr.le, ne.def, mul_transvection_apply_of_ne, not_false_iff, ne.symm h], rcases le_or_lt (n+1) i with hi|hi, { simp [hi, n.le_succ.trans hi, if_true], }, { rw [if_neg, if_neg], { simpa only [not_le] using hi }, { simpa only [hni.symm, not_le, or_false] using nat.lt_succ_iff_lt_or_eq.1 hi } } } } end /-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` kills all the coefficients in the last row but the last one. -/ lemma list_transvec_col_mul_mul_list_transvec_row_last_col (hM : M (inr star) (inr star) ≠ 0) (i : fin r) : ((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) (inr star) (inl i) = 0 := begin have : list_transvec_row M = list_transvec_row ((list_transvec_col M).prod ⬝ M), by simp [list_transvec_row, list_transvec_col_mul_last_row], rw this, apply mul_list_transvec_row_last_row, simpa [list_transvec_col_mul_last_row] using hM end /-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` kills all the coefficients in the last column but the last one. -/ lemma list_transvec_col_mul_mul_list_transvec_row_last_row (hM : M (inr star) (inr star) ≠ 0) (i : fin r) : ((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) (inl i) (inr star) = 0 := begin have : list_transvec_col M = list_transvec_col (M ⬝ (list_transvec_row M).prod), by simp [list_transvec_col, mul_list_transvec_row_last_col], rw [this, matrix.mul_assoc], apply list_transvec_col_mul_last_col, simpa [mul_list_transvec_row_last_col] using hM end /-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` turns the matrix in block-diagonal form. -/ lemma is_two_block_diagonal_list_transvec_col_mul_mul_list_transvec_row (hM : M (inr star) (inr star) ≠ 0) : is_two_block_diagonal ((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) := begin split, { ext i j, have : j = star, by simp only [eq_iff_true_of_subsingleton], simp [to_blocks₁₂, this, list_transvec_col_mul_mul_list_transvec_row_last_row M hM] }, { ext i j, have : i = star, by simp only [eq_iff_true_of_subsingleton], simp [to_blocks₂₁, this, list_transvec_col_mul_mul_list_transvec_row_last_col M hM] }, end /-- There exist two lists of `transvection_struct` such that multiplying by them on the left and on the right makes a matrix block-diagonal, when the last coefficient is nonzero. -/ lemma exists_is_two_block_diagonal_of_ne_zero (hM : M (inr star) (inr star) ≠ 0) : ∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)), is_two_block_diagonal ((L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod) := begin let L : list (transvection_struct (fin r ⊕ unit) 𝕜) := list.of_fn (λ i : fin r, ⟨inl i, inr star, by simp, -M (inl i) (inr star) / M (inr star) (inr star)⟩), let L' : list (transvection_struct (fin r ⊕ unit) 𝕜) := list.of_fn (λ i : fin r, ⟨inr star, inl i, by simp, -M (inr star) (inl i) / M (inr star) (inr star)⟩), refine ⟨L, L', _⟩, have A : L.map to_matrix = list_transvec_col M, by simp [L, list_transvec_col, (∘)], have B : L'.map to_matrix = list_transvec_row M, by simp [L, list_transvec_row, (∘)], rw [A, B], exact is_two_block_diagonal_list_transvec_col_mul_mul_list_transvec_row M hM end /-- There exist two lists of `transvection_struct` such that multiplying by them on the left and on the right makes a matrix block-diagonal. -/ lemma exists_is_two_block_diagonal_list_transvec_mul_mul_list_transvec (M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) : ∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)), is_two_block_diagonal ((L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod) := begin by_cases H : is_two_block_diagonal M, { refine ⟨list.nil, list.nil, by simpa using H⟩ }, -- we have already proved this when the last coefficient is nonzero by_cases hM : M (inr star) (inr star) ≠ 0, { exact exists_is_two_block_diagonal_of_ne_zero M hM }, -- when the last coefficient is zero but there is a nonzero coefficient on the last row or the -- last column, we will first put this nonzero coefficient in last position, and then argue as -- above. push_neg at hM, simp [not_and_distrib, is_two_block_diagonal, to_blocks₁₂, to_blocks₂₁] at H, have : ∃ (i : fin r), M (inl i) (inr star) ≠ 0 ∨ M (inr star) (inl i) ≠ 0, { cases H, { contrapose! H, ext i j, convert (H i).1, simp only [eq_iff_true_of_subsingleton] }, { contrapose! H, ext i j, convert (H j).2, simp only [eq_iff_true_of_subsingleton] } }, rcases this with ⟨i, h|h⟩, { let M' := transvection (inr unit.star) (inl i) 1 ⬝ M, have hM' : M' (inr star) (inr star) ≠ 0, by simpa [M', hM], rcases exists_is_two_block_diagonal_of_ne_zero M' hM' with ⟨L, L', hLL'⟩, rw matrix.mul_assoc at hLL', refine ⟨L ++ [⟨inr star, inl i, by simp, 1⟩], L', _⟩, simp only [list.map_append, list.prod_append, matrix.mul_one, to_matrix_mk, list.prod_cons, list.prod_nil, mul_eq_mul, list.map, matrix.mul_assoc (L.map to_matrix).prod], exact hLL' }, { let M' := M ⬝ transvection (inl i) (inr star) 1, have hM' : M' (inr star) (inr star) ≠ 0, by simpa [M', hM], rcases exists_is_two_block_diagonal_of_ne_zero M' hM' with ⟨L, L', hLL'⟩, refine ⟨L, ⟨inl i, inr star, by simp, 1⟩ :: L', _⟩, simp only [←matrix.mul_assoc, to_matrix_mk, list.prod_cons, mul_eq_mul, list.map], rw [matrix.mul_assoc (L.map to_matrix).prod], exact hLL' } end /-- Inductive step for the reduction: if one knows that any size `r` matrix can be reduced to diagonal form by elementary operations, then one deduces it for matrices over `fin r ⊕ unit`. -/ lemma exists_list_transvec_mul_mul_list_transvec_eq_diagonal_induction (IH : ∀ (M : matrix (fin r) (fin r) 𝕜), ∃ (L₀ L₀' : list (transvection_struct (fin r) 𝕜)) (D₀ : (fin r) → 𝕜), (L₀.map to_matrix).prod ⬝ M ⬝ (L₀'.map to_matrix).prod = diagonal D₀) (M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) : ∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)) (D : fin r ⊕ unit → 𝕜), (L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D := begin rcases exists_is_two_block_diagonal_list_transvec_mul_mul_list_transvec M with ⟨L₁, L₁', hM⟩, let M' := (L₁.map to_matrix).prod ⬝ M ⬝ (L₁'.map to_matrix).prod, let M'' := to_blocks₁₁ M', rcases IH M'' with ⟨L₀, L₀', D₀, h₀⟩, set c := M' (inr star) (inr star) with hc, refine ⟨L₀.map (sum_inl unit) ++ L₁, L₁' ++ L₀'.map (sum_inl unit), sum.elim D₀ (λ _, M' (inr star) (inr star)), _⟩, suffices : (L₀.map (to_matrix ∘ sum_inl unit)).prod ⬝ M' ⬝ (L₀'.map (to_matrix ∘ sum_inl unit)).prod = diagonal (sum.elim D₀ (λ _, c)), by simpa [M', matrix.mul_assoc, c], have : M' = from_blocks M'' 0 0 (diagonal (λ _, c)), { rw ← from_blocks_to_blocks M', congr, { exact hM.1 }, { exact hM.2 }, { ext i j, rw [hc, to_blocks₂₂], congr } }, rw this, simp [h₀], end variables {n p} [fintype n] [fintype p] /-- Reduction to diagonal form by elementary operations is invariant under reindexing. -/ lemma reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal (M : matrix p p 𝕜) (e : p ≃ n) (H : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜), (L.map to_matrix).prod ⬝ (matrix.reindex_alg_equiv 𝕜 e M) ⬝ (L'.map to_matrix).prod = diagonal D) : ∃ (L L' : list (transvection_struct p 𝕜)) (D : p → 𝕜), (L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D := begin rcases H with ⟨L₀, L₀', D₀, h₀⟩, refine ⟨L₀.map (reindex_equiv e.symm), L₀'.map (reindex_equiv e.symm), D₀ ∘ e, _⟩, have : M = reindex_alg_equiv 𝕜 e.symm (reindex_alg_equiv 𝕜 e M), by simp only [equiv.symm_symm, minor_minor, reindex_apply, minor_id_id, equiv.symm_comp_self, reindex_alg_equiv_apply], rw this, simp only [to_matrix_reindex_equiv_prod, list.map_map, reindex_alg_equiv_apply], simp only [← reindex_alg_equiv_apply, ← reindex_alg_equiv_mul, h₀], simp only [equiv.symm_symm, reindex_apply, minor_diagonal_equiv, reindex_alg_equiv_apply], end /-- Any matrix can be reduced to diagonal form by elementary operations. Formulated here on `Type 0` because we will make an induction using `fin r`. See `exists_list_transvec_mul_mul_list_transvec_eq_diagonal` for the general version (which follows from this one and reindexing). -/ lemma exists_list_transvec_mul_mul_list_transvec_eq_diagonal_aux (n : Type) [fintype n] [decidable_eq n] (M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜), (L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D := begin unfreezingI { induction hn : fintype.card n with r IH generalizing n M }, { refine ⟨list.nil, list.nil, λ _, 1, _⟩, ext i j, rw fintype.card_eq_zero_iff at hn, exact hn.elim' i }, { have e : n ≃ fin r ⊕ unit, { refine fintype.equiv_of_card_eq _, rw hn, convert (@fintype.card_sum (fin r) unit _ _).symm, simp }, apply reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal M e, apply exists_list_transvec_mul_mul_list_transvec_eq_diagonal_induction (λ N, IH (fin r) N (by simp)) } end /-- Any matrix can be reduced to diagonal form by elementary operations. -/ theorem exists_list_transvec_mul_mul_list_transvec_eq_diagonal (M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜), (L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D := begin have e : n ≃ fin (fintype.card n) := fintype.equiv_of_card_eq (by simp), apply reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal M e, apply exists_list_transvec_mul_mul_list_transvec_eq_diagonal_aux end /-- Any matrix can be written as the product of transvections, a diagonal matrix, and transvections.-/ theorem exists_list_transvec_mul_diagonal_mul_list_transvec (M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜), M = (L.map to_matrix).prod ⬝ diagonal D ⬝ (L'.map to_matrix).prod := begin rcases exists_list_transvec_mul_mul_list_transvec_eq_diagonal M with ⟨L, L', D, h⟩, refine ⟨L.reverse.map transvection_struct.inv, L'.reverse.map transvection_struct.inv, D, _⟩, suffices : M = ((L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (L.map to_matrix).prod) ⬝ M ⬝ ((L'.map to_matrix).prod ⬝ (L'.reverse.map (to_matrix ∘ transvection_struct.inv)).prod), by simpa [← h, matrix.mul_assoc], rw [reverse_inv_prod_mul_prod, prod_mul_reverse_inv_prod, matrix.one_mul, matrix.mul_one], end end pivot open pivot transvection_struct variables {n} [fintype n] /-- Induction principle for matrices based on transvections: if a property is true for all diagonal matrices, all transvections, and is stable under product, then it is true for all matrices. This is the useful way to say that matrices are generated by diagonal matrices and transvections. We state a slightly more general version: to prove a property for a matrix `M`, it suffices to assume that the diagonal matrices we consider have the same determinant as `M`. This is useful to obtain similar principles for `SLₙ` or `GLₙ`. -/ lemma diagonal_transvection_induction (P : matrix n n 𝕜 → Prop) (M : matrix n n 𝕜) (hdiag : ∀ D : n → 𝕜, det (diagonal D) = det M → P (diagonal D)) (htransvec : ∀ (t : transvection_struct n 𝕜), P t.to_matrix) (hmul : ∀ A B, P A → P B → P (A ⬝ B)) : P M := begin rcases exists_list_transvec_mul_diagonal_mul_list_transvec M with ⟨L, L', D, h⟩, have PD : P (diagonal D) := hdiag D (by simp [h]), suffices H : ∀ (L₁ L₂ : list (transvection_struct n 𝕜)) (E : matrix n n 𝕜), P E → P ((L₁.map to_matrix).prod ⬝ E ⬝ (L₂.map to_matrix).prod), by { rw h, apply H L L', exact PD }, assume L₁ L₂ E PE, induction L₁ with t L₁ IH, { simp only [matrix.one_mul, list.prod_nil, list.map], induction L₂ with t L₂ IH generalizing E, { simpa }, { simp only [←matrix.mul_assoc, list.prod_cons, mul_eq_mul, list.map], apply IH, exact hmul _ _ PE (htransvec _) } }, { simp only [matrix.mul_assoc, list.prod_cons, mul_eq_mul, list.map] at ⊢ IH, exact hmul _ _ (htransvec _) IH } end /-- Induction principle for invertible matrices based on transvections: if a property is true for all invertible diagonal matrices, all transvections, and is stable under product of invertible matrices, then it is true for all invertible matrices. This is the useful way to say that invertible matrices are generated by invertible diagonal matrices and transvections. -/ lemma diagonal_transvection_induction_of_det_ne_zero (P : matrix n n 𝕜 → Prop) (M : matrix n n 𝕜) (hMdet : det M ≠ 0) (hdiag : ∀ D : n → 𝕜, det (diagonal D) ≠ 0 → P (diagonal D)) (htransvec : ∀ (t : transvection_struct n 𝕜), P t.to_matrix) (hmul : ∀ A B, det A ≠ 0 → det B ≠ 0 → P A → P B → P (A ⬝ B)) : P M := begin let Q : matrix n n 𝕜 → Prop := λ N, det N ≠ 0 ∧ P N, have : Q M, { apply diagonal_transvection_induction Q M, { assume D hD, have detD : det (diagonal D) ≠ 0, by { rw hD, exact hMdet }, exact ⟨detD, hdiag _ detD⟩ }, { assume t, exact ⟨by simp, htransvec t⟩ }, { assume A B QA QB, exact ⟨by simp [QA.1, QB.1], hmul A B QA.1 QB.1 QA.2 QB.2⟩ } }, exact this.2 end end matrix
42a87710702adec38262b67d327d6259a7c6bf7b
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.15.lean
a0b1362815440aae63b19b77cb6cd7e383e1c8cd
[]
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
156
lean
/- page 105 -/ import standard open nat -- BEGIN definition f : nat → nat → nat | f 0 y := 1 | f x 0 := 2 | f (x+1) (y+1) := 3 -- END
72319a2f943bc27c1ef769fbc8babb2a9e7de952
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group/with_one/basic.lean
08b23c3badf5a48aa620090c426d5f315c3b77ad
[ "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,167
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 -/ import algebra.group.with_one.defs import algebra.hom.equiv.basic /-! # More operations on `with_one` and `with_zero` This file defines various bundled morphisms on `with_one` and `with_zero` that were not available in `algebra/group/with_one/defs`. ## Main definitions * `with_one.lift`, `with_zero.lift` * `with_one.map`, `with_zero.map` -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace with_one section -- workaround: we make `with_one`/`with_zero` irreducible for this definition, otherwise `simps` -- will unfold it in the statement of the lemma it generates. local attribute [irreducible] with_one with_zero /-- `coe` as a bundled morphism -/ @[to_additive "`coe` as a bundled morphism", simps apply] def coe_mul_hom [has_mul α] : α →ₙ* (with_one α) := { to_fun := coe, map_mul' := λ x y, rfl } end section lift local attribute [semireducible] with_one with_zero variables [has_mul α] [mul_one_class β] /-- Lift a semigroup homomorphism `f` to a bundled monoid homorphism. -/ @[to_additive "Lift an add_semigroup homomorphism `f` to a bundled add_monoid homorphism."] def lift : (α →ₙ* β) ≃ (with_one α →* β) := { to_fun := λ f, { to_fun := λ x, option.cases_on x 1 f, map_one' := rfl, map_mul' := λ x y, with_one.cases_on x (by { rw one_mul, exact (one_mul _).symm }) $ λ x, with_one.cases_on y (by { rw mul_one, exact (mul_one _).symm }) $ λ y, f.map_mul x y }, inv_fun := λ F, F.to_mul_hom.comp coe_mul_hom, left_inv := λ f, mul_hom.ext $ λ x, rfl, right_inv := λ F, monoid_hom.ext $ λ x, with_one.cases_on x F.map_one.symm $ λ x, rfl } variables (f : α →ₙ* β) @[simp, to_additive] lemma lift_coe (x : α) : lift f x = f x := rfl @[simp, to_additive] lemma lift_one : lift f 1 = 1 := rfl @[to_additive] theorem lift_unique (f : with_one α →* β) : f = lift (f.to_mul_hom.comp coe_mul_hom) := (lift.apply_symm_apply f).symm end lift section map variables [has_mul α] [has_mul β] [has_mul γ] /-- Given a multiplicative map from `α → β` returns a monoid homomorphism from `with_one α` to `with_one β` -/ @[to_additive "Given an additive map from `α → β` returns an add_monoid homomorphism from `with_zero α` to `with_zero β`"] def map (f : α →ₙ* β) : with_one α →* with_one β := lift (coe_mul_hom.comp f) @[simp, to_additive] lemma map_coe (f : α →ₙ* β) (a : α) : map f (a : with_one α) = f a := lift_coe _ _ @[simp, to_additive] lemma map_id : map (mul_hom.id α) = monoid_hom.id (with_one α) := by { ext, induction x using with_one.cases_on; refl } @[to_additive] lemma map_map (f : α →ₙ* β) (g : β →ₙ* γ) (x) : map g (map f x) = map (g.comp f) x := by { induction x using with_one.cases_on; refl } @[simp, to_additive] lemma map_comp (f : α →ₙ* β) (g : β →ₙ* γ) : map (g.comp f) = (map g).comp (map f) := monoid_hom.ext $ λ x, (map_map f g x).symm /-- A version of `equiv.option_congr` for `with_one`. -/ @[to_additive "A version of `equiv.option_congr` for `with_zero`.", simps apply] def _root_.mul_equiv.with_one_congr (e : α ≃* β) : with_one α ≃* with_one β := { to_fun := map e.to_mul_hom, inv_fun := map e.symm.to_mul_hom, left_inv := λ x, (map_map _ _ _).trans $ by induction x using with_one.cases_on; { simp }, right_inv := λ x, (map_map _ _ _).trans $ by induction x using with_one.cases_on; { simp }, .. map e.to_mul_hom } @[simp] lemma _root_.mul_equiv.with_one_congr_refl : (mul_equiv.refl α).with_one_congr = mul_equiv.refl _ := mul_equiv.to_monoid_hom_injective map_id @[simp] lemma _root_.mul_equiv.with_one_congr_symm (e : α ≃* β) : e.with_one_congr.symm = e.symm.with_one_congr := rfl @[simp] lemma _root_.mul_equiv.with_one_congr_trans (e₁ : α ≃* β) (e₂ : β ≃* γ) : e₁.with_one_congr.trans e₂.with_one_congr = (e₁.trans e₂).with_one_congr := mul_equiv.to_monoid_hom_injective (map_comp _ _).symm end map end with_one
f89759fd33ace5edaa02dd161cccf84b449b18ba
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/weak_dual_topology.lean
6c7bc8b971b69ab40df619e3493f18ec2b656faa
[ "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
6,777
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import topology.algebra.module /-! # Weak dual topology This file defines the weak-* topology on duals of suitable topological modules `E` over suitable topological semirings `𝕜`. The (weak) dual consists of continuous linear functionals `E →L[𝕜] 𝕜` from `E` to scalars `𝕜`. The weak-* topology is the coarsest topology on this dual `weak_dual 𝕜 E := (E →L[𝕜] 𝕜)` w.r.t. which the evaluation maps at all `z : E` are continuous. The weak dual is a module over `𝕜` if the semiring `𝕜` is commutative. ## Main definitions The main definitions are the type `weak_dual 𝕜 E` and a topology instance on it. * `weak_dual 𝕜 E` is a type synonym for `dual 𝕜 E` (when the latter is defined): both are equal to the type `E →L[𝕜] 𝕜` of continuous linear maps from a module `E` over `𝕜` to the ring `𝕜`. * The instance `weak_dual.topological_space` is the weak-* topology on `weak_dual 𝕜 E`, i.e., the coarsest topology making the evaluation maps at all `z : E` continuous. ## Main results We establish that `weak_dual 𝕜 E` has the following structure: * `weak_dual.has_continuous_add`: The addition in `weak_dual 𝕜 E` is continuous. * `weak_dual.module`: If the scalars `𝕜` are a commutative semiring, then `weak_dual 𝕜 E` is a module over `𝕜`. * `weak_dual.has_continuous_smul`: If the scalars `𝕜` are a commutative semiring, then the scalar multiplication by `𝕜` in `weak_dual 𝕜 E` is continuous. We prove the following results characterizing the weak-* topology: * `weak_dual.eval_continuous`: For any `z : E`, the evaluation mapping `weak_dual 𝕜 E → 𝕜` taking `x'`to `x' z` is continuous. * `weak_dual.continuous_of_continuous_eval`: For a mapping to `weak_dual 𝕜 E` to be continuous, it suffices that its compositions with evaluations at all points `z : E` are continuous. * `weak_dual.tendsto_iff_forall_eval_tendsto`: Convergence in `weak_dual 𝕜 E` can be characterized in terms of convergence of the evaluations at all points `z : E`. ## Notations No new notation is introduced. ## Implementation notes The weak-* topology is defined as the induced topology under the mapping that associates to a dual element `x'` the functional `E → 𝕜`, when the space `E → 𝕜` of functionals is equipped with the topology of pointwise convergence (product topology). Typically one might assume that `𝕜` is a topological semiring in the sense of the typeclasses `topological_space 𝕜`, `semiring 𝕜`, `has_continuous_add 𝕜`, `has_continuous_mul 𝕜`, and that the space `E` is a topological module over `𝕜` in the sense of the typeclasses `topological_space E`, `add_comm_monoid E`, `has_continuous_add E`, `module 𝕜 E`, `has_continuous_smul 𝕜 E`. The definitions and results are, however, given with weaker assumptions when possible. ## References * https://en.wikipedia.org/wiki/Weak_topology#Weak-*_topology ## Tags weak-star, weak dual -/ noncomputable theory open filter open_locale topological_space universes u v section weak_star_topology /-! ### Weak star topology on duals of topological modules -/ variables (𝕜 : Type*) [topological_space 𝕜] [semiring 𝕜] variables (E : Type*) [topological_space E] [add_comm_monoid E] [module 𝕜 E] /-- The weak dual of a topological module `E` over a topological semiring `𝕜` consists of continuous linear functionals from `E` to scalars `𝕜`. It is a type synonym with the usual dual (when the latter is defined), but will be equipped with a different topology. -/ @[derive [inhabited, λ α, has_coe_to_fun α (λ _, E → 𝕜)]] def weak_dual := E →L[𝕜] 𝕜 instance [has_continuous_add 𝕜] : add_comm_monoid (weak_dual 𝕜 E) := continuous_linear_map.add_comm_monoid namespace weak_dual /-- The weak-* topology instance `weak_dual.topological_space` on the dual of a topological module `E` over a topological semiring `𝕜` is defined as the induced topology under the mapping that associates to a dual element `x' : weak_dual 𝕜 E` the functional `E → 𝕜`, when the space `E → 𝕜` of functionals is equipped with the topology of pointwise convergence (product topology). -/ instance : topological_space (weak_dual 𝕜 E) := topological_space.induced (λ x' : weak_dual 𝕜 E, λ z : E, x' z) Pi.topological_space lemma coe_fn_continuous : continuous (λ (x' : (weak_dual 𝕜 E)), (λ (z : E), x' z)) := continuous_induced_dom lemma eval_continuous (z : E) : continuous (λ (x' : weak_dual 𝕜 E), x' z) := (continuous_pi_iff.mp (coe_fn_continuous 𝕜 E)) z lemma continuous_of_continuous_eval {α : Type u} [topological_space α] {g : α → weak_dual 𝕜 E} (h : ∀ z, continuous (λ a, g a z)) : continuous g := continuous_induced_rng (continuous_pi_iff.mpr h) theorem tendsto_iff_forall_eval_tendsto {γ : Type u} {F : filter γ} {ψs : γ → weak_dual 𝕜 E} {ψ : weak_dual 𝕜 E} : tendsto ψs F (𝓝 ψ) ↔ ∀ z : E, tendsto (λ i, ψs i z) F (𝓝 (ψ z)) := begin rw ←tendsto_pi, split, { intros weak_star_conv, exact (((coe_fn_continuous 𝕜 E).tendsto ψ).comp weak_star_conv), }, { intro h_lim_forall, rwa [nhds_induced, tendsto_comap_iff], }, end /-- Addition in `weak_dual 𝕜 E` is continuous. -/ instance [has_continuous_add 𝕜] : has_continuous_add (weak_dual 𝕜 E) := { continuous_add := begin apply continuous_of_continuous_eval, intros z, have h : continuous (λ p : 𝕜 × 𝕜, p.1 + p.2) := continuous_add, exact h.comp ((eval_continuous 𝕜 E z).prod_map (eval_continuous 𝕜 E z)), end, } /-- If the scalars `𝕜` are a commutative semiring, then `weak_dual 𝕜 E` is a module over `𝕜`. -/ instance (𝕜 : Type u) [topological_space 𝕜] [comm_semiring 𝕜] [has_continuous_add 𝕜] [has_continuous_mul 𝕜] (E : Type*) [topological_space E] [add_comm_group E] [module 𝕜 E] : module 𝕜 (weak_dual 𝕜 E) := continuous_linear_map.module /-- Scalar multiplication in `weak_dual 𝕜 E` is continuous (when `𝕜` is a commutative semiring). -/ instance (𝕜 : Type u) [topological_space 𝕜] [comm_semiring 𝕜] [has_continuous_add 𝕜] [has_continuous_mul 𝕜] (E : Type*) [topological_space E] [add_comm_group E] [module 𝕜 E] : has_continuous_smul 𝕜 (weak_dual 𝕜 E) := { continuous_smul := begin apply continuous_of_continuous_eval, intros z, have h : continuous (λ p : 𝕜 × 𝕜, p.1 * p.2) := continuous_mul, exact h.comp ((continuous_id').prod_map (eval_continuous 𝕜 E z)), end, } end weak_dual end weak_star_topology
7b47c98e8c8b3cb2df50ba47417f1a0388df27b1
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/arith/ext.lean
824e6e5a6249bff90b57ac3c9e5d9e04c5f9f065
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,530
lean
import galois.tactic inductive ext (A : Type) : Type | inj {} : A → ext | inf {} : ext | neg_inf {} : ext namespace ext section parameters (A : Type) [decidable_linear_order A] def le : ext A → ext A → Prop | neg_inf _ := true | _ inf := true | (inj _) neg_inf := false | (inj x) (inj y) := x ≤ y | inf (inj _) := false | inf neg_inf := false instance : has_le (ext A) := ⟨ le ⟩ inductive lt (x y : ext A) : Prop | mk : ∀ (le : x ≤ y) (not_rev_le : ¬ (y ≤ x)), lt instance : has_lt (ext A) := ⟨ lt ⟩ instance le_decidable : decidable_rel (@has_le.le (ext A) _) := begin intros x y, induction x; induction y; simp [(≤), le]; apply_instance, end lemma lt_equiv (a b : ext A) : a < b ↔ a ≤ b ∧ ¬b ≤ a := begin split; intros H; induction H; split; assumption, end instance lt_decidable : decidable_rel (@has_lt.lt (ext A) _) := begin intros x y, rw lt_equiv, apply_instance, end lemma le_refl (x : ext A) : x ≤ x := begin simp only [(≤)], induction x; simp only [le], end lemma le_trans {x y z : ext A} (H : x ≤ y) (H' : y ≤ z) : x ≤ z := begin simp only [(≤)] at *, induction x; induction y; induction z; simp only [le] at *; try { contradiction }, apply le_trans; assumption end lemma le_antisymm (a b : ext A) : a ≤ b → b ≤ a → a = b := begin simp only [(≤)], intros H H', induction a; induction b; simp only [le] at *; try { contradiction }, f_equal, apply le_antisymm; assumption end lemma le_total (a b : ext A) : a ≤ b ∨ b ≤ a := begin simp only [(≤)], induction a; induction b; simp only [le]; try {cc}, apply le_total, end lemma neg_inf_le (x : ext A) : neg_inf ≤ x := begin simp only [(≤)], induction x; simp [le], end lemma le_inf (x : ext A) : x ≤ inf := begin simp only [(≤)], induction x; simp [le], end instance eq_decidable : decidable_eq (ext A) := by tactic.mk_dec_eq_instance instance linear_order_decidable : decidable_linear_order (ext A) := begin constructor, apply ext.le_decidable, apply_instance, apply ext.lt_decidable, apply le_refl, apply le_trans, unfold auto_param, intros, apply lt_equiv, apply le_antisymm, apply le_total, end end end ext namespace list def maximum_ext {α:Type _} [decidable_linear_order α] : list (ext α) → ext α := list.foldr max ext.neg_inf def minimum_ext {α:Type _} [decidable_linear_order α] : list (ext α) → ext α := list.foldr min ext.inf end list lemma maximum_ext_le {α: Type _} [decidable_linear_order α] (xs : list (ext α)) (u : ext α) (H : ∀ x : ext α, x ∈ xs → x ≤ u) : xs.maximum_ext ≤ u := begin unfold list.maximum_ext, induction xs; dsimp [list.foldr], apply ext.neg_inf_le, apply max_le, apply H, rw list.mem_cons_eq, left, reflexivity, apply ih_1, intros, apply H,rw list.mem_cons_eq, right, assumption end lemma le_minimum_ext {α: Type _} [decidable_linear_order α] (xs : list (ext α)) (l : ext α) (H : ∀ x : ext α, x ∈ xs → l ≤ x) : l ≤ xs.minimum_ext := begin unfold list.minimum_ext, induction xs; dsimp [list.foldr], apply ext.le_inf, apply le_min, apply H, rw list.mem_cons_eq, left, reflexivity, apply ih_1, intros, apply H,rw list.mem_cons_eq, right, assumption end theorem le_ext_maximum_minimum {α: Type _} [decidable_linear_order α] (ll ul : list (ext α)) (pr : ∀ (l u : ext α), l ∈ ll → u ∈ ul → l ≤ u) : ll.maximum_ext ≤ ul.minimum_ext := begin apply maximum_ext_le, intros, apply le_minimum_ext, intros, apply pr; assumption end
80863a95567c705cb2ff03aa43494a744e905fbf
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/exercises_sources/thursday/groups_rings_fields.lean
3ae3d3edba3cf809b085d3ce94297aebe2ff172b
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,398
lean
import linear_algebra.finite_dimensional import ring_theory.algebraic import data.zmod.basic import data.real.basic import tactic /-! ``` ____ / ___|_ __ ___ _ _ _ __ ___ | | _| '__/ _ \| | | | '_ \/ __| | |_| | | | (_) | |_| | |_) \__ \_ \____|_| \___/ \__,_| .__/|___( ) |_| |/ _ __ (_) _ __ __ _ ___ | '__| | | | '_ \ / _` | / __| | | | | | | | | | (_| | \__ \ _ |_| |_| |_| |_| \__, | |___/ ( ) |___/ |/ _ __ _ _ _ __ _ _ __ __| | / _| (_) ___ | | __| | ___ / _` | | '_ \ / _` | | |_ | | / _ \ | | / _` | / __| | (_| | | | | | | (_| | | _| | | | __/ | | | (_| | \__ \ \__,_| |_| |_| \__,_| |_| |_| \___| |_| \__,_| |___/ ``` -/ /-! ## Reminder on updating the exercises These instructions are now available at: https://leanprover-community.github.io/lftcm2020/exercises.html To get a new copy of the exercises, run the following commands in your terminal: ``` leanproject get lftcm2020 cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises code lftcm2020 ``` To update your exercise files, run the following commands: ``` cd /path/to/lftcm2020 git pull leanproject get-mathlib-cache ``` Don’t forget to copy the updated files to `src/my_exercises`. -/ /-! ## What do we have? Too much to cover in detail in 10 minutes. Take a look at the “General algebra” section on https://leanprover-community.github.io/mathlib-overview.html All the basic concepts are there: `group`, `ring`, `field`, `module`, etc... Also versions that are compatible with an ordering, like `ordered_ring` And versions that express compatibility with a topology: `topological_group` Finally constructions, like `polynomial R`, or `mv_polynomial σ R`, or `monoid_algebra K G`, or `ℤ_[p]`, or `zmod n`, or `localization R S`. -/ /-! ## Morphisms We are in the middle of a transition to “bundled” morphisms. (Why? Long story... but they work better with `simp`) * `X → Y` -- ordinary function * `X →+ Y` -- function respects `0` and `+` * `X →* Y` -- function respects `1` and `*` * `X →+* Y` -- function respects `0`, `1`, `+`, `*` (surprise!) -/ section variables {R S : Type*} [ring R] [ring S] -- We used to write example (f : R → S) [is_ring_hom f] : true := trivial -- But now we write example (f : R →+* S) : true := trivial /- This heavily relies on the “coercion to function” that we have seen a couple of times this week. -/ end /-! ## Where are these things in the library? `algebra/` for basic definitions and properties; “algebraic hierarchy” `group_theory/` ⎫ `ring_theory/` ⎬ “advanced” and “specialised” material `field_theory/` | `number_theory` ⎭ `data/` definitions and examples To give an idea: * `algebra/ordered_ring.lean` * `ring_theory/noetherian.lean` * `field_theory/chevalley_warning.lean` * `data/nat/*.lean`, `data/real/*.lean`, `number_theory/padics/*.lean` -/ /-! ## How to find things (search tools) * `library_search` -- it often helps to carve out the exact lemma statement that you are looking for * online documentation: https://leanprover-community.github.io/mathlib_docs/ new search bar under construction * Old-skool: `grep` * Search in VS Code: - `Ctrl - Shift - F` -- don't forget to change settings, to search everywhere -- click the three dots (`…`) below the search bar -- disable the blue cogwheel - `Ctrl - P` -- search for filenames - `Ctrl - P`, `#` -- search for lemmas and definitions -/ /-! ## How to find things (autocomplete) Mathlib follows pretty strict naming conventions: ``` /-- The binomial theorem-/ theorem add_pow [comm_semiring α] (x y : α) (n : ℕ) : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := (commute.all x y).add_pow n ``` After a while, you get the hang of this, and you can start guessing names. -/ open_locale big_operators -- nice notation ∑, ∏ open finset -- `finset.range n` is the finite set `{0,1,..., n-1}` -- Demonstrate autocompletion example (f : ℕ → ℝ) (n : ℕ) : 57 + ∑ i in range (n+1), f i = 57 + f n + ∑ i in range n, f i := begin sorry end /-! ## How to find things (jump to definition) Another good strategy for finding useful results about `X`, is to “jump to the definition” and scroll through the next 3 screens of lemmas. If you are looking for a basic fact about `X`, you will usually find it there. -/ -- demonstrate “jump to definition” #check polynomial.coeff /-! ## Exercise 1 We will warm up with a well-known result: “Subgroups of abelian groups are normal.” Hints for proving this result: * Notice that `normal` is a structure, which you can see by going to the definition. The `constructor` tactic will help you to get started. -/ namespace add_subgroup variables {A : Type*} [add_comm_group A] lemma normal_of_add_comm_group (H : add_subgroup A) : normal H := begin sorry end end add_subgroup /-! ## Exercise 2 The following exercise will show the classical fact: “Finite field extensions are algebraic.” Hints for proving this result: * Look up the definition of `finite_dimensional`. * Search the library for useful lemmas about `is_algebraic` and `is_integral`. -/ namespace algebra variables {K L : Type*} [field K] [field L] [algebra K L] [finite_dimensional K L] lemma is_algebraic_of_finite_dimensional : is_algebraic K L := begin sorry end end algebra /-! ## Exercise 3 In this exercise we will define the Frobenius morphism. -/ section variables (p : ℕ) [fact p.prime] variables (K : Type*) [field K] [char_p K p] /-! ### Subchallenge -/ lemma add_pow_char' (x y : K) : (x + y) ^ p = x ^ p + y ^ p := begin -- Hint: `add_pow_char` already exists. -- You can use it if you don't want to spend time on this. /- Hints if you do want to attempt this: * `finset.sum_range_succ` * `finset.sum_eq_single` * `nat.prime.ne_zero` * `char_p.cast_eq_zero_iff` * `nat.prime.dvd_choose_self` * `fact.out p.prime` obtains the primality of `p` from the typeclass assumption `[fact p.prime]` -/ sorry end def frobenius_hom : K →+* K := { to_fun := λ x, x^p, map_zero' := begin -- Hint: `zero_pow`, search for lemmas near `nat.prime` sorry end, map_one' := begin sorry end, map_mul' := begin sorry end, map_add' := begin -- Hint: `add_pow_char` -- can you prove that one yourself? sorry end } end /-! ## Exercise 4 [challenging] The next exercise asks to show that a monic polynomial `f ∈ ℤ[X]` is irreducible if it is irreducible modulo a prime `p`. This fact is also not in mathlib. Hint: prove the helper lemma that is stated first. Follow-up question: Can you generalise `irreducible_of_irreducible_mod_prime`? -/ namespace polynomial variables {R S : Type*} [semiring R] [integral_domain S] (φ : R →+* S) /- Useful library lemmas (in no particular order): - `degree_eq_zero_of_is_unit` - `eq_C_of_degree_eq_zero` - `is_unit.map'` - `leading_coeff_C` - `degree_map_eq_of_leading_coeff_ne_zero` - `is_unit.map'` - `is_unit.ne_zero` -/ lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map' (f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := begin sorry end /- Useful library lemmas (in no particular order): - `is_unit.map'` - `is_unit_of_mul_is_unit_left` (also `_right`) - `leading_coeff_mul` - `is_unit_of_is_unit_leading_coeff_of_is_unit_map` (the helper lemma we just proved) - `is_unit_one` -/ lemma irreducible_of_irreducible_mod_prime (f : polynomial ℤ) (p : ℕ) [fact p.prime] (h_mon : monic f) (h_irr : irreducible (map (int.cast_ring_hom (zmod p)) f)) : irreducible f := begin sorry end end polynomial -- SCROLL DOWN FOR THE BONUS EXERCISE section /-! ## Bonus exercise (wicked hard) -/ noncomputable theory -- because `polynomial` is noncomputable (implementation detail) open polynomial -- we want to write `X`, instead of `polynomial.X` /- First we make some definitions Scroll to the end for the actual exercise -/ def partial_ramanujan_tau_polynomial (n : ℕ) : polynomial ℤ := X * ∏ k in finset.Ico 1 n, (1 - X^k)^24 def ramanujan_tau (n : ℕ) : ℤ := coeff (partial_ramanujan_tau_polynomial n) n -- Some nice suggestive notation prefix `τ`:300 := ramanujan_tau /- Some lemmas to warm up Hint: unfold definitions, `simp` -/ example : τ 0 = 0 := begin sorry end example : τ 1 = 1 := begin sorry end -- This one is nontrivial -- Use `have : subresult,` or state helper lemmas and prove them first! example : τ 2 = -24 := begin -- Really, we ought to have a tactic that makes this easy delta ramanujan_tau partial_ramanujan_tau_polynomial, rw [mul_comm, coeff_mul_X], suffices : ((1 - X) ^ 24 : polynomial ℤ).coeff 1 = -(24 : ℕ), by simpa, generalize : (24 : ℕ) = n, sorry end /- The actual exercise. Good luck (-; -/ theorem deligne (p : ℕ) (hp : p.prime) : (abs (τ p) : ℝ) ≤ 2 * p^(11/2) := begin sorry end end
7460123428ffabf43322b84071a9cad6f5d1dad4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/integral_domain_auto.lean
c0c5922439b2e49ae5adc0ea0db38b2f4000e9c0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,546
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.card import Mathlib.data.polynomial.ring_division import Mathlib.group_theory.order_of_element import Mathlib.algebra.geom_sum import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Integral domains Assorted theorems about integral domains. ## Main theorems * `is_cyclic_of_subgroup_integral_domain` : A finite subgroup of the units of an integral domain is cyclic. * `field_of_integral_domain` : A finite integral domain is a field. ## Tags integral domain, finite integral domain, finite field -/ theorem card_nth_roots_subgroup_units {R : Type u_1} {G : Type u_2} [integral_domain R] [group G] [fintype G] (f : G →* R) (hf : function.injective ⇑f) {n : ℕ} (hn : 0 < n) (g₀ : G) : finset.card (has_sep.sep (fun (g : G) => g ^ n = g₀) finset.univ) ≤ coe_fn multiset.card (polynomial.nth_roots n (coe_fn f g₀)) := sorry /-- A finite subgroup of the unit group of an integral domain is cyclic. -/ theorem is_cyclic_of_subgroup_integral_domain {R : Type u_1} {G : Type u_2} [integral_domain R] [group G] [fintype G] (f : G →* R) (hf : function.injective ⇑f) : is_cyclic G := sorry /-- The unit group of a finite integral domain is cyclic. -/ protected instance units.is_cyclic {R : Type u_1} [integral_domain R] [fintype R] : is_cyclic (units R) := is_cyclic_of_subgroup_integral_domain (units.coe_hom R) units.ext /-- Every finite integral domain is a field. -/ def field_of_integral_domain {R : Type u_1} [integral_domain R] [DecidableEq R] [fintype R] : field R := field.mk integral_domain.add sorry integral_domain.zero sorry sorry integral_domain.neg integral_domain.sub sorry sorry integral_domain.mul sorry integral_domain.one sorry sorry sorry sorry sorry (fun (a : R) => dite (a = 0) (fun (h : a = 0) => 0) fun (h : ¬a = 0) => fintype.bij_inv sorry 1) sorry sorry sorry /-- A finite subgroup of the units of an integral domain is cyclic. -/ protected instance subgroup_units_cyclic {R : Type u_1} [integral_domain R] (S : set (units R)) [is_subgroup S] [fintype ↥S] : is_cyclic ↥S := sorry theorem card_fiber_eq_of_mem_range {G : Type u_2} [group G] [fintype G] {H : Type u_1} [group H] [DecidableEq H] (f : G →* H) {x : H} {y : H} (hx : x ∈ set.range ⇑f) (hy : y ∈ set.range ⇑f) : finset.card (finset.filter (fun (g : G) => coe_fn f g = x) finset.univ) = finset.card (finset.filter (fun (g : G) => coe_fn f g = y) finset.univ) := sorry /-- In an integral domain, a sum indexed by a nontrivial homomorphism from a finite group is zero. -/ theorem sum_hom_units_eq_zero {R : Type u_1} {G : Type u_2} [integral_domain R] [group G] [fintype G] (f : G →* R) (hf : f ≠ 1) : (finset.sum finset.univ fun (g : G) => coe_fn f g) = 0 := sorry /-- In an integral domain, a sum indexed by a homomorphism from a finite group is zero, unless the homomorphism is trivial, in which case the sum is equal to the cardinality of the group. -/ theorem sum_hom_units {R : Type u_1} {G : Type u_2} [integral_domain R] [group G] [fintype G] (f : G →* R) [Decidable (f = 1)] : (finset.sum finset.univ fun (g : G) => coe_fn f g) = ite (f = 1) (↑(fintype.card G)) 0 := sorry end Mathlib
dbb254c85fc74375bed1f023004af7cb98fd5203
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_fast_ec_add_soundness.lean
ea5a6c209f45f8a296fd880563d9f108778868e7
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
44,345
lean
/- File: signature_recover_public_key_fast_ec_add_soundness.lean Autogenerated file. -/ import starkware.cairo.lean.semantics.soundness.hoare import .signature_recover_public_key_code import ..signature_recover_public_key_spec import .signature_recover_public_key_unreduced_sqr_soundness import .signature_recover_public_key_compute_slope_soundness open tactic open starkware.cairo.common.cairo_secp.ec open starkware.cairo.common.cairo_secp.bigint open starkware.cairo.common.cairo_secp.field variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] variable mem : F → F variable σ : register_state F /- starkware.cairo.common.cairo_secp.ec.fast_ec_add autogenerated soundness theorem -/ theorem auto_sound_fast_ec_add_block9 -- An independent ap variable. (ap : F) -- arguments (range_check_ptr : F) (point0 point1 : EcPoint F) -- code is in memory at σ.pc (h_mem : mem_at mem code_fast_ec_add σ.pc) -- all dependencies are in memory (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 317)) (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 305)) (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 285)) (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 269)) (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 97)) -- input arguments on the stack (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15)) (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14)) (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8)) (νbound : ℕ) -- conclusion : ensuresb_ret νbound mem {pc := σ.pc + 28, ap := ap, fp := σ.fp} (λ κ τ, ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 7) (auto_spec_fast_ec_add_block9 mem κ range_check_ptr point0 point1 (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) := begin have h_mem_rec := h_mem, unpack_memory code_fast_ec_add at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86⟩, -- function call step_assert_eq hpc28 with arg0, step_assert_eq hpc29 with arg1, step_assert_eq hpc30 with arg2, step_assert_eq hpc31 with arg3, step_assert_eq hpc32 with arg4, step_assert_eq hpc33 with arg5, step_assert_eq hpc34 with arg6, step_assert_eq hpc35 with arg7, step_assert_eq hpc36 with arg8, step_assert_eq hpc37 with arg9, step_assert_eq hpc38 with arg10, step_assert_eq hpc39 with arg11, step_assert_eq hpc40 with arg12, step_sub hpc41 (auto_sound_compute_slope mem _ range_check_ptr point0 point1 _ _ _ _ _ _ _), { rw hpc42, norm_num2, exact h_mem_13 }, { rw hpc42, norm_num2, exact h_mem_4 }, { rw hpc42, norm_num2, exact h_mem_5 }, { rw hpc42, norm_num2, exact h_mem_7 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call43 ap43 h_call43, rcases h_call43 with ⟨h_call43_ap_offset, h_call43⟩, rcases h_call43 with ⟨rc_m43, rc_mle43, hl_range_check_ptr₁, h_call43⟩, generalize' hr_rev_range_check_ptr₁: mem (ap43 - 4) = range_check_ptr₁, have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁, generalize' hr_rev_slope: cast_BigInt3 mem (ap43 - 3) = slope, simp only [hr_rev_slope] at h_call43, have htv_slope := hr_rev_slope.symm, clear hr_rev_slope, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at hl_range_check_ptr₁ }, rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call43 }, rw [hin_range_check_ptr] at h_call43, clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12, -- function call step_sub hpc43 (auto_sound_unreduced_sqr mem _ slope _ _), { rw hpc44, norm_num2, exact h_mem_6 }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { simp only [h_call43_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call45 ap45 h_call45, rcases h_call45 with ⟨h_call45_ap_offset, h_call45⟩, generalize' hr_rev_slope_sqr: cast_UnreducedBigInt3 mem (ap45 - 3) = slope_sqr, simp only [hr_rev_slope_sqr] at h_call45, have htv_slope_sqr := hr_rev_slope_sqr.symm, clear hr_rev_slope_sqr, clear , -- function call step_assert_eq hpc45 with arg0, step_sub hpc46 (auto_sound_nondet_bigint3 mem _ range_check_ptr₁ _ _), { rw hpc47, norm_num2, exact h_mem_4 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, intros κ_call48 ap48 h_call48, rcases h_call48 with ⟨h_call48_ap_offset, h_call48⟩, rcases h_call48 with ⟨rc_m48, rc_mle48, hl_range_check_ptr₂, h_call48⟩, generalize' hr_rev_range_check_ptr₂: mem (ap48 - 4) = range_check_ptr₂, have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂, generalize' hr_rev_new_x: cast_BigInt3 mem (ap48 - 3) = new_x, simp only [hr_rev_new_x] at h_call48, have htv_new_x := hr_rev_new_x.symm, clear hr_rev_new_x, try { simp only [arg0] at hl_range_check_ptr₂ }, try { rw [h_call45_ap_offset] at hl_range_check_ptr₂ }, try { arith_simps at hl_range_check_ptr₂ }, rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂, try { simp only [arg0] at h_call48 }, try { rw [h_call45_ap_offset] at h_call48 }, try { arith_simps at h_call48 }, rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call48, clear arg0, -- function call step_assert_eq hpc48 with arg0, step_sub hpc49 (auto_sound_nondet_bigint3 mem _ range_check_ptr₂ _ _), { rw hpc50, norm_num2, exact h_mem_4 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, intros κ_call51 ap51 h_call51, rcases h_call51 with ⟨h_call51_ap_offset, h_call51⟩, rcases h_call51 with ⟨rc_m51, rc_mle51, hl_range_check_ptr₃, h_call51⟩, generalize' hr_rev_range_check_ptr₃: mem (ap51 - 4) = range_check_ptr₃, have htv_range_check_ptr₃ := hr_rev_range_check_ptr₃.symm, clear hr_rev_range_check_ptr₃, generalize' hr_rev_new_y: cast_BigInt3 mem (ap51 - 3) = new_y, simp only [hr_rev_new_y] at h_call51, have htv_new_y := hr_rev_new_y.symm, clear hr_rev_new_y, try { simp only [arg0] at hl_range_check_ptr₃ }, rw [←htv_range_check_ptr₃, ←htv_range_check_ptr₂] at hl_range_check_ptr₃, try { simp only [arg0] at h_call51 }, rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call51, clear arg0, -- function call step_assert_eq hpc51 with arg0, step_assert_eq hpc52 with arg1, step_assert_eq hpc53 with arg2, step_assert_eq hpc54 with arg3, step_assert_eq hpc55 with arg4, step_assert_eq hpc56 with arg5, step_assert_eq hpc57 with arg6, step_assert_eq hpc58 with arg7, step_assert_eq hpc59 with arg8, step_assert_eq hpc60 with arg9, step_sub hpc61 (auto_sound_verify_zero mem _ range_check_ptr₃ { d0 := slope_sqr.d0 - new_x.d0 - point0.x.d0 - point1.x.d0, d1 := slope_sqr.d1 - new_x.d1 - point0.x.d1 - point1.x.d1, d2 := slope_sqr.d2 - new_x.d2 - point0.x.d2 - point1.x.d2 } _ _ _), { rw hpc62, norm_num2, exact h_mem_7 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), (eq_sub_of_eq_add arg3), (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), arg6, (eq_sub_of_eq_add arg7), (eq_sub_of_eq_add arg8), (eq_sub_of_eq_add arg9)] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), (eq_sub_of_eq_add arg3), (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), arg6, (eq_sub_of_eq_add arg7), (eq_sub_of_eq_add arg8), (eq_sub_of_eq_add arg9)] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call63 ap63 h_call63, rcases h_call63 with ⟨h_call63_ap_offset, h_call63⟩, rcases h_call63 with ⟨rc_m63, rc_mle63, hl_range_check_ptr₄, h_call63⟩, generalize' hr_rev_range_check_ptr₄: mem (ap63 - 1) = range_check_ptr₄, have htv_range_check_ptr₄ := hr_rev_range_check_ptr₄.symm, clear hr_rev_range_check_ptr₄, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at hl_range_check_ptr₄ }, rw [←htv_range_check_ptr₄, ←htv_range_check_ptr₃] at hl_range_check_ptr₄, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at h_call63 }, rw [←htv_range_check_ptr₃, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call63, clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9, -- function call step_assert_eq hpc63 with arg0, step_assert_eq hpc64 with arg1, step_assert_eq hpc65 with arg2, step_assert_eq hpc66 with arg3, step_assert_eq hpc67 with arg4, step_assert_eq hpc68 with arg5, step_sub hpc69 (auto_sound_unreduced_mul mem _ { d0 := point0.x.d0 - new_x.d0, d1 := point0.x.d1 - new_x.d1, d2 := point0.x.d2 - new_x.d2 } slope _ _ _), { rw hpc70, norm_num2, exact h_mem_5 }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call71 ap71 h_call71, rcases h_call71 with ⟨h_call71_ap_offset, h_call71⟩, generalize' hr_rev_x_diff_slope: cast_UnreducedBigInt3 mem (ap71 - 3) = x_diff_slope, simp only [hr_rev_x_diff_slope] at h_call71, have htv_x_diff_slope := hr_rev_x_diff_slope.symm, clear hr_rev_x_diff_slope, clear arg0 arg1 arg2 arg3 arg4 arg5, -- function call step_assert_eq hpc71 with arg0, step_assert_eq hpc72 with arg1, step_assert_eq hpc73 with arg2, step_assert_eq hpc74 with arg3, step_assert_eq hpc75 with arg4, step_assert_eq hpc76 with arg5, step_assert_eq hpc77 with arg6, step_sub hpc78 (auto_sound_verify_zero mem _ range_check_ptr₄ { d0 := x_diff_slope.d0 - point0.y.d0 - new_y.d0, d1 := x_diff_slope.d1 - point0.y.d1 - new_y.d1, d2 := x_diff_slope.d2 - point0.y.d2 - new_y.d2 } _ _ _), { rw hpc79, norm_num2, exact h_mem_7 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), (eq_sub_of_eq_add arg6)] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset, h_call71_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), (eq_sub_of_eq_add arg6)] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset, h_call71_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call80 ap80 h_call80, rcases h_call80 with ⟨h_call80_ap_offset, h_call80⟩, rcases h_call80 with ⟨rc_m80, rc_mle80, hl_range_check_ptr₅, h_call80⟩, generalize' hr_rev_range_check_ptr₅: mem (ap80 - 1) = range_check_ptr₅, have htv_range_check_ptr₅ := hr_rev_range_check_ptr₅.symm, clear hr_rev_range_check_ptr₅, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr₅ }, try { rw [h_call71_ap_offset] at hl_range_check_ptr₅ }, try { arith_simps at hl_range_check_ptr₅ }, rw [←htv_range_check_ptr₅, ←htv_range_check_ptr₄] at hl_range_check_ptr₅, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at h_call80 }, try { rw [h_call71_ap_offset] at h_call80 }, try { arith_simps at h_call80 }, rw [←htv_range_check_ptr₄, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call80, clear arg0 arg1 arg2 arg3 arg4 arg5 arg6, -- return step_assert_eq hpc80 with hret0, step_assert_eq hpc81 with hret1, step_assert_eq hpc82 with hret2, step_assert_eq hpc83 with hret3, step_assert_eq hpc84 with hret4, step_assert_eq hpc85 with hret5, step_ret hpc86, -- finish step_done, use_only [rfl, rfl], -- range check condition use_only (rc_m43+rc_m48+rc_m51+rc_m63+rc_m80+0+0), split, linarith [rc_mle43, rc_mle48, rc_mle51, rc_mle63, rc_mle80], split, { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5] }, rw [←htv_range_check_ptr₅, hl_range_check_ptr₅, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof dsimp [auto_spec_fast_ec_add_block9], try { norm_num1 }, try { arith_simps }, use_only [κ_call43], use_only [range_check_ptr₁], use_only [slope], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have spec43 := h_call43 rc_h_range_check_ptr', rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec43, try { dsimp at spec43, arith_simps at spec43 }, use_only [spec43], use_only [κ_call45], use_only [slope_sqr], try { dsimp at h_call45, arith_simps at h_call45 }, try { use_only [h_call45] }, use_only [κ_call48], use_only [range_check_ptr₂], use_only [new_x], have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁, have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' }, have spec48 := h_call48 rc_h_range_check_ptr₁', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec48, try { dsimp at spec48, arith_simps at spec48 }, use_only [spec48], use_only [κ_call51], use_only [range_check_ptr₃], use_only [new_y], have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂, have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃, try { norm_cast at rc_h_range_check_ptr₃' }, have spec51 := h_call51 rc_h_range_check_ptr₂', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←htv_range_check_ptr₃] at spec51, try { dsimp at spec51, arith_simps at spec51 }, use_only [spec51], use_only [κ_call63], use_only [range_check_ptr₄], have rc_h_range_check_ptr₄ := range_checked_offset' rc_h_range_check_ptr₃, have rc_h_range_check_ptr₄' := range_checked_add_right rc_h_range_check_ptr₄, try { norm_cast at rc_h_range_check_ptr₄' }, have spec63 := h_call63 rc_h_range_check_ptr₃', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←htv_range_check_ptr₄] at spec63, try { dsimp at spec63, arith_simps at spec63 }, use_only [spec63], use_only [κ_call71], use_only [x_diff_slope], try { dsimp at h_call71, arith_simps at h_call71 }, try { use_only [h_call71] }, use_only [κ_call80], use_only [range_check_ptr₅], have rc_h_range_check_ptr₅ := range_checked_offset' rc_h_range_check_ptr₄, have rc_h_range_check_ptr₅' := range_checked_add_right rc_h_range_check_ptr₅, try { norm_cast at rc_h_range_check_ptr₅' }, have spec80 := h_call80 rc_h_range_check_ptr₄', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←hl_range_check_ptr₄, ←htv_range_check_ptr₅] at spec80, try { dsimp at spec80, arith_simps at spec80 }, use_only [spec80], try { split, linarith }, try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope, htv_range_check_ptr₅] }, }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5] }, try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset, h_call71_ap_offset, h_call80_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, end theorem auto_sound_fast_ec_add_block5 -- An independent ap variable. (ap : F) -- arguments (range_check_ptr : F) (point0 point1 : EcPoint F) -- code is in memory at σ.pc (h_mem : mem_at mem code_fast_ec_add σ.pc) -- all dependencies are in memory (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 317)) (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 305)) (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 285)) (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 269)) (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 97)) -- input arguments on the stack (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15)) (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14)) (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8)) (νbound : ℕ) -- conclusion : ensuresb_ret νbound mem {pc := σ.pc + 14, ap := ap, fp := σ.fp} (λ κ τ, ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 7) (auto_spec_fast_ec_add_block5 mem κ range_check_ptr point0 point1 (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) := begin have h_mem_rec := h_mem, unpack_memory code_fast_ec_add at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86⟩, -- if statement step_jnz hpc14 hpc15 with hcond hcond, { -- if: positive branch have a14 : point1.x.d0 = 0, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a14 }, try { arith_simps at a14 }, clear hcond, -- if statement step_jnz hpc16 hpc17 with hcond hcond, { -- if: positive branch have a16 : point1.x.d1 = 0, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a16 }, try { arith_simps at a16 }, clear hcond, -- if statement step_jnz hpc18 hpc19 with hcond hcond, { -- if: positive branch have a18 : point1.x.d2 = 0, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a18 }, try { arith_simps at a18 }, clear hcond, -- return step_assert_eq hpc20 with hret0, step_assert_eq hpc21 with hret1, step_assert_eq hpc22 with hret2, step_assert_eq hpc23 with hret3, step_assert_eq hpc24 with hret4, step_assert_eq hpc25 with hret5, step_assert_eq hpc26 with hret6, step_ret hpc27, -- finish step_done, use_only [rfl, rfl], -- range check condition use_only (0+0), split, linarith [], split, { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof dsimp [auto_spec_fast_ec_add_block5], try { norm_num1 }, try { arith_simps }, left, use_only [a14], left, use_only [a16], left, use_only [a18], try { split, linarith }, try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { -- if: negative branch have a18 : point1.x.d2 ≠ 0, { try { simp only [ne.def] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a18 }, try { arith_simps at a18 }, clear hcond, -- Use the block soundness theorem. apply ensuresb_ret_trans (auto_sound_fast_ec_add_block9 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound), intros κ_block9 τ, try { arith_simps }, intro h_block9, rcases h_block9 with ⟨rc_m_block9, rc_m_le_block9, hblk_range_check_ptr₁, h_block9⟩, -- range check condition use_only (rc_m_block9+0+0), split, linarith [rc_m_le_block9], split, { arith_simps, try { simp only [hblk_range_check_ptr₁] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof dsimp [auto_spec_fast_ec_add_block5], try { norm_num1 }, try { arith_simps }, left, use_only [a14], left, use_only [a16], right, use_only [a18], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have h_block9' := h_block9 rc_h_range_check_ptr', try { rw [←hin_range_check_ptr] at h_block9' }, try { dsimp at h_block9, arith_simps at h_block9' }, have h_block9 := h_block9', use_only[κ_block9], use [h_block9], try { linarith } } }, { -- if: negative branch have a16 : point1.x.d1 ≠ 0, { try { simp only [ne.def] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a16 }, try { arith_simps at a16 }, clear hcond, -- Use the block soundness theorem. apply ensuresb_ret_trans (auto_sound_fast_ec_add_block9 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound), intros κ_block9 τ, try { arith_simps }, intro h_block9, rcases h_block9 with ⟨rc_m_block9, rc_m_le_block9, hblk_range_check_ptr₁, h_block9⟩, -- range check condition use_only (rc_m_block9+0+0), split, linarith [rc_m_le_block9], split, { arith_simps, try { simp only [hblk_range_check_ptr₁] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof dsimp [auto_spec_fast_ec_add_block5], try { norm_num1 }, try { arith_simps }, left, use_only [a14], right, use_only [a16], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have h_block9' := h_block9 rc_h_range_check_ptr', try { rw [←hin_range_check_ptr] at h_block9' }, try { dsimp at h_block9, arith_simps at h_block9' }, have h_block9 := h_block9', use_only[κ_block9], use [h_block9], try { linarith } } }, { -- if: negative branch have a14 : point1.x.d0 ≠ 0, { try { simp only [ne.def] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a14 }, try { arith_simps at a14 }, clear hcond, -- Use the block soundness theorem. apply ensuresb_ret_trans (auto_sound_fast_ec_add_block9 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound), intros κ_block9 τ, try { arith_simps }, intro h_block9, rcases h_block9 with ⟨rc_m_block9, rc_m_le_block9, hblk_range_check_ptr₁, h_block9⟩, -- range check condition use_only (rc_m_block9+0+0), split, linarith [rc_m_le_block9], split, { arith_simps, try { simp only [hblk_range_check_ptr₁] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof dsimp [auto_spec_fast_ec_add_block5], try { norm_num1 }, try { arith_simps }, right, use_only [a14], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have h_block9' := h_block9 rc_h_range_check_ptr', try { rw [←hin_range_check_ptr] at h_block9' }, try { dsimp at h_block9, arith_simps at h_block9' }, have h_block9 := h_block9', use_only[κ_block9], use [h_block9], try { linarith } } end theorem auto_sound_fast_ec_add -- arguments (range_check_ptr : F) (point0 point1 : EcPoint F) -- code is in memory at σ.pc (h_mem : mem_at mem code_fast_ec_add σ.pc) -- all dependencies are in memory (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 317)) (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 305)) (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 285)) (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 269)) (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 97)) -- input arguments on the stack (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15)) (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14)) (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8)) -- conclusion : ensures_ret mem σ (λ κ τ, ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 7) (spec_fast_ec_add mem κ range_check_ptr point0 point1 (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) := begin apply ensures_of_ensuresb, intro νbound, have h_mem_rec := h_mem, unpack_memory code_fast_ec_add at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86⟩, -- if statement step_jnz hpc0 hpc1 with hcond hcond, { -- if: positive branch have a0 : point0.x.d0 = 0, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a0 }, try { arith_simps at a0 }, clear hcond, -- if statement step_jnz hpc2 hpc3 with hcond hcond, { -- if: positive branch have a2 : point0.x.d1 = 0, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a2 }, try { arith_simps at a2 }, clear hcond, -- if statement step_jnz hpc4 hpc5 with hcond hcond, { -- if: positive branch have a4 : point0.x.d2 = 0, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a4 }, try { arith_simps at a4 }, clear hcond, -- return step_assert_eq hpc6 with hret0, step_assert_eq hpc7 with hret1, step_assert_eq hpc8 with hret2, step_assert_eq hpc9 with hret3, step_assert_eq hpc10 with hret4, step_assert_eq hpc11 with hret5, step_assert_eq hpc12 with hret6, step_ret hpc13, -- finish step_done, use_only [rfl, rfl], -- range check condition use_only (0+0), split, linarith [], split, { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _, { apply sound_fast_ec_add, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_fast_ec_add], try { norm_num1 }, try { arith_simps }, left, use_only [a0], left, use_only [a2], left, use_only [a4], try { split, linarith }, try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { -- if: negative branch have a4 : point0.x.d2 ≠ 0, { try { simp only [ne.def] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a4 }, try { arith_simps at a4 }, clear hcond, -- Use the block soundness theorem. apply ensuresb_ret_trans (auto_sound_fast_ec_add_block5 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound), intros κ_block5 τ, try { arith_simps }, intro h_block5, rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩, -- range check condition use_only (rc_m_block5+0+0), split, linarith [rc_m_le_block5], split, { arith_simps, try { simp only [hblk_range_check_ptr₁] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _, { apply sound_fast_ec_add, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_fast_ec_add], try { norm_num1 }, try { arith_simps }, left, use_only [a0], left, use_only [a2], right, use_only [a4], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have h_block5' := h_block5 rc_h_range_check_ptr', try { rw [←hin_range_check_ptr] at h_block5' }, try { dsimp at h_block5, arith_simps at h_block5' }, have h_block5 := h_block5', use_only[κ_block5], use [h_block5], try { linarith } } }, { -- if: negative branch have a2 : point0.x.d1 ≠ 0, { try { simp only [ne.def] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a2 }, try { arith_simps at a2 }, clear hcond, -- Use the block soundness theorem. apply ensuresb_ret_trans (auto_sound_fast_ec_add_block5 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound), intros κ_block5 τ, try { arith_simps }, intro h_block5, rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩, -- range check condition use_only (rc_m_block5+0+0), split, linarith [rc_m_le_block5], split, { arith_simps, try { simp only [hblk_range_check_ptr₁] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _, { apply sound_fast_ec_add, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_fast_ec_add], try { norm_num1 }, try { arith_simps }, left, use_only [a0], right, use_only [a2], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have h_block5' := h_block5 rc_h_range_check_ptr', try { rw [←hin_range_check_ptr] at h_block5' }, try { dsimp at h_block5, arith_simps at h_block5' }, have h_block5 := h_block5', use_only[κ_block5], use [h_block5], try { linarith } } }, { -- if: negative branch have a0 : point0.x.d0 ≠ 0, { try { simp only [ne.def] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [hcond] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a0 }, try { arith_simps at a0 }, clear hcond, -- Use the block soundness theorem. apply ensuresb_ret_trans (auto_sound_fast_ec_add_block5 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound), intros κ_block5 τ, try { arith_simps }, intro h_block5, rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩, -- range check condition use_only (rc_m_block5+0+0), split, linarith [rc_m_le_block5], split, { arith_simps, try { simp only [hblk_range_check_ptr₁] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _, { apply sound_fast_ec_add, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_fast_ec_add], try { norm_num1 }, try { arith_simps }, right, use_only [a0], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have h_block5' := h_block5 rc_h_range_check_ptr', try { rw [←hin_range_check_ptr] at h_block5' }, try { dsimp at h_block5, arith_simps at h_block5' }, have h_block5 := h_block5', use_only[κ_block5], use [h_block5], try { linarith } } end
4b968098e7c98f87dcbd3eaa851eb3ff07edfa7e
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/class_number/finite.lean
332cfe561384c1078728de2f22d64b36c7ea5720
[ "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
17,765
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import analysis.special_functions.pow import linear_algebra.free_module.pid import linear_algebra.matrix.absolute_value import number_theory.class_number.admissible_absolute_value import ring_theory.class_group import ring_theory.dedekind_domain.integral_closure import ring_theory.norm /-! # Class numbers of global fields In this file, we use the notion of "admissible absolute value" to prove finiteness of the class group for number fields and function fields, and define `class_number` as the order of this group. ## Main definitions - `class_group.fintype_of_admissible`: if `R` has an admissible absolute value, its integral closure has a finite class group -/ open_locale big_operators open_locale non_zero_divisors namespace class_group open ring open_locale big_operators section euclidean_domain variables (R S K L : Type*) [euclidean_domain R] [comm_ring S] [is_domain S] variables [field K] [field L] variables [algebra R K] [is_fraction_ring R K] variables [algebra K L] [finite_dimensional K L] [is_separable K L] variables [algRL : algebra R L] [is_scalar_tower R K L] variables [algebra R S] [algebra S L] variables [ist : is_scalar_tower R S L] [iic : is_integral_closure S R L] variables {R S} (abv : absolute_value R ℤ) variables {ι : Type*} [decidable_eq ι] [fintype ι] (bS : basis ι R S) /-- If `b` is an `R`-basis of `S` of cardinality `n`, then `norm_bound abv b` is an integer such that for every `R`-integral element `a : S` with coordinates `≤ y`, we have algebra.norm a ≤ norm_bound abv b * y ^ n`. (See also `norm_le` and `norm_lt`). -/ noncomputable def norm_bound : ℤ := let n := fintype.card ι, i : ι := nonempty.some bS.index_nonempty, m : ℤ := finset.max' (finset.univ.image (λ (ijk : ι × ι × ι), abv (algebra.left_mul_matrix bS (bS ijk.1) ijk.2.1 ijk.2.2))) ⟨_, finset.mem_image.mpr ⟨⟨i, i, i⟩, finset.mem_univ _, rfl⟩⟩ in nat.factorial n • (n • m) ^ n lemma norm_bound_pos : 0 < norm_bound abv bS := begin obtain ⟨i, j, k, hijk⟩ : ∃ i j k, algebra.left_mul_matrix bS (bS i) j k ≠ 0, { by_contra' h, obtain ⟨i⟩ := bS.index_nonempty, apply bS.ne_zero i, apply (injective_iff_map_eq_zero (algebra.left_mul_matrix bS)).mp (algebra.left_mul_matrix_injective bS), ext j k, simp [h, dmatrix.zero_apply] }, simp only [norm_bound, algebra.smul_def, eq_nat_cast], refine mul_pos (int.coe_nat_pos.mpr (nat.factorial_pos _)) _, refine pow_pos (mul_pos (int.coe_nat_pos.mpr (fintype.card_pos_iff.mpr ⟨i⟩)) _) _, refine lt_of_lt_of_le (abv.pos hijk) (finset.le_max' _ _ _), exact finset.mem_image.mpr ⟨⟨i, j, k⟩, finset.mem_univ _, rfl⟩ end /-- If the `R`-integral element `a : S` has coordinates `≤ y` with respect to some basis `b`, its norm is less than `norm_bound abv b * y ^ dim S`. -/ lemma norm_le (a : S) {y : ℤ} (hy : ∀ k, abv (bS.repr a k) ≤ y) : abv (algebra.norm R a) ≤ norm_bound abv bS * y ^ fintype.card ι := begin conv_lhs { rw ← bS.sum_repr a }, rw [algebra.norm_apply, ← linear_map.det_to_matrix bS], simp only [algebra.norm_apply, alg_hom.map_sum, alg_hom.map_smul, linear_equiv.map_sum, linear_equiv.map_smul, algebra.to_matrix_lmul_eq, norm_bound, smul_mul_assoc, ← mul_pow], convert matrix.det_sum_smul_le finset.univ _ hy using 3, { rw [finset.card_univ, smul_mul_assoc, mul_comm] }, { intros i j k, apply finset.le_max', exact finset.mem_image.mpr ⟨⟨i, j, k⟩, finset.mem_univ _, rfl⟩ }, end /-- If the `R`-integral element `a : S` has coordinates `< y` with respect to some basis `b`, its norm is strictly less than `norm_bound abv b * y ^ dim S`. -/ lemma norm_lt {T : Type*} [linear_ordered_ring T] (a : S) {y : T} (hy : ∀ k, (abv (bS.repr a k) : T) < y) : (abv (algebra.norm R a) : T) < norm_bound abv bS * y ^ fintype.card ι := begin obtain ⟨i⟩ := bS.index_nonempty, have him : (finset.univ.image (λ k, abv (bS.repr a k))).nonempty := ⟨_, finset.mem_image.mpr ⟨i, finset.mem_univ _, rfl⟩⟩, set y' : ℤ := finset.max' _ him with y'_def, have hy' : ∀ k, abv (bS.repr a k) ≤ y', { intro k, exact finset.le_max' _ _ (finset.mem_image.mpr ⟨k, finset.mem_univ _, rfl⟩) }, have : (y' : T) < y, { rw [y'_def, ← finset.max'_image (show monotone (coe : ℤ → T), from λ x y h, int.cast_le.mpr h)], apply (finset.max'_lt_iff _ (him.image _)).mpr, simp only [finset.mem_image, exists_prop], rintros _ ⟨x, ⟨k, -, rfl⟩, rfl⟩, exact hy k }, have y'_nonneg : 0 ≤ y' := le_trans (abv.nonneg _) (hy' i), apply (int.cast_le.mpr (norm_le abv bS a hy')).trans_lt, simp only [int.cast_mul, int.cast_pow], apply mul_lt_mul' le_rfl, { exact pow_lt_pow_of_lt_left this (int.cast_nonneg.mpr y'_nonneg) (fintype.card_pos_iff.mpr ⟨i⟩) }, { exact pow_nonneg (int.cast_nonneg.mpr y'_nonneg) _ }, { exact int.cast_pos.mpr (norm_bound_pos abv bS) }, { apply_instance } end /-- A nonzero ideal has an element of minimal norm. -/ lemma exists_min (I : (ideal S)⁰) : ∃ b ∈ (I : ideal S), b ≠ 0 ∧ ∀ c ∈ (I : ideal S), abv (algebra.norm R c) < abv (algebra.norm R b) → c = (0 : S) := begin obtain ⟨_, ⟨b, b_mem, b_ne_zero, rfl⟩, min⟩ := @int.exists_least_of_bdd (λ a, ∃ b ∈ (I : ideal S), b ≠ (0 : S) ∧ abv (algebra.norm R b) = a) _ _, { refine ⟨b, b_mem, b_ne_zero, _⟩, intros c hc lt, contrapose! lt with c_ne_zero, exact min _ ⟨c, hc, c_ne_zero, rfl⟩ }, { use 0, rintros _ ⟨b, b_mem, b_ne_zero, rfl⟩, apply abv.nonneg }, { obtain ⟨b, b_mem, b_ne_zero⟩ := (I : ideal S).ne_bot_iff.mp (non_zero_divisors.coe_ne_zero I), exact ⟨_, ⟨b, b_mem, b_ne_zero, rfl⟩⟩ } end section is_admissible variables (L) {abv} (adm : abv.is_admissible) include adm /-- If we have a large enough set of elements in `R^ι`, then there will be a pair whose remainders are close together. We'll show that all sets of cardinality at least `cardM bS adm` elements satisfy this condition. The value of `cardM` is not at all optimal: for specific choices of `R`, the minimum cardinality can be exponentially smaller. -/ noncomputable def cardM : ℕ := adm.card (norm_bound abv bS ^ (-1 / (fintype.card ι) : ℝ)) ^ fintype.card ι variables [infinite R] /-- In the following results, we need a large set of distinct elements of `R`. -/ noncomputable def distinct_elems : fin (cardM bS adm).succ ↪ R := fin.coe_embedding.trans (infinite.nat_embedding R) variables [decidable_eq R] /-- `finset_approx` is a finite set such that each fractional ideal in the integral closure contains an element close to `finset_approx`. -/ noncomputable def finset_approx : finset R := (finset.univ.image $ λ xy : _ × _, distinct_elems bS adm xy.1 - distinct_elems bS adm xy.2).erase 0 lemma finset_approx.zero_not_mem : (0 : R) ∉ finset_approx bS adm := finset.not_mem_erase _ _ @[simp] lemma mem_finset_approx {x : R} : x ∈ finset_approx bS adm ↔ ∃ i j, i ≠ j ∧ distinct_elems bS adm i - distinct_elems bS adm j = x := begin simp only [finset_approx, finset.mem_erase, finset.mem_image], split, { rintros ⟨hx, ⟨i, j⟩, _, rfl⟩, refine ⟨i, j, _, rfl⟩, rintro rfl, simpa using hx }, { rintros ⟨i, j, hij, rfl⟩, refine ⟨_, ⟨i, j⟩, finset.mem_univ _, rfl⟩, rw [ne.def, sub_eq_zero], exact λ h, hij ((distinct_elems bS adm).injective h) } end section real open real local attribute [-instance] real.decidable_eq /-- We can approximate `a / b : L` with `q / r`, where `r` has finitely many options for `L`. -/ theorem exists_mem_finset_approx (a : S) {b} (hb : b ≠ (0 : R)) : ∃ (q : S) (r ∈ finset_approx bS adm), abv (algebra.norm R (r • a - b • q)) < abv (algebra.norm R (algebra_map R S b)) := begin have dim_pos := fintype.card_pos_iff.mpr bS.index_nonempty, set ε : ℝ := norm_bound abv bS ^ (-1 / (fintype.card ι) : ℝ) with ε_eq, have hε : 0 < ε := real.rpow_pos_of_pos (int.cast_pos.mpr (norm_bound_pos abv bS)) _, have ε_le : (norm_bound abv bS : ℝ) * (abv b • ε) ^ fintype.card ι ≤ (abv b ^ fintype.card ι), { have := norm_bound_pos abv bS, have := abv.nonneg b, rw [ε_eq, algebra.smul_def, eq_int_cast, ← rpow_nat_cast, mul_rpow, ← rpow_mul, div_mul_cancel, rpow_neg_one, mul_left_comm, mul_inv_cancel, mul_one, rpow_nat_cast]; try { norm_cast, linarith }, { apply rpow_nonneg_of_nonneg, norm_cast, linarith } }, let μ : fin (cardM bS adm).succ ↪ R := distinct_elems bS adm, set s := bS.repr a, have s_eq : ∀ i, s i = bS.repr a i := λ i, rfl, set qs := λ j i, (μ j * s i) / b, have q_eq : ∀ j i, qs j i = (μ j * s i) / b := λ i j, rfl, set rs := λ j i, (μ j * s i) % b with r_eq, have r_eq : ∀ j i, rs j i = (μ j * s i) % b := λ i j, rfl, have μ_eq : ∀ i j, μ j * s i = b * qs j i + rs j i, { intros i j, rw [q_eq, r_eq, euclidean_domain.div_add_mod], }, have μ_mul_a_eq : ∀ j, μ j • a = b • ∑ i, qs j i • bS i + ∑ i, rs j i • bS i, { intro j, rw ← bS.sum_repr a, simp only [finset.smul_sum, ← finset.sum_add_distrib], refine finset.sum_congr rfl (λ i _, _), rw [← s_eq, ← mul_smul, μ_eq, add_smul, mul_smul] }, obtain ⟨j, k, j_ne_k, hjk⟩ := adm.exists_approx hε hb (λ j i, μ j * s i), have hjk' : ∀ i, (abv (rs k i - rs j i) : ℝ) < abv b • ε, { simpa only [r_eq] using hjk }, set q := ∑ i, (qs k i - qs j i) • bS i with q_eq, set r := μ k - μ j with r_eq, refine ⟨q, r, (mem_finset_approx bS adm).mpr _, _⟩, { exact ⟨k, j, j_ne_k.symm, rfl⟩ }, have : r • a - b • q = (∑ (x : ι), (rs k x • bS x - rs j x • bS x)), { simp only [r_eq, sub_smul, μ_mul_a_eq, q_eq, finset.smul_sum, ← finset.sum_add_distrib, ← finset.sum_sub_distrib, smul_sub], refine finset.sum_congr rfl (λ x _, _), ring }, rw [this, algebra.norm_algebra_map_of_basis bS, abv.map_pow], refine int.cast_lt.mp ((norm_lt abv bS _ (λ i, lt_of_le_of_lt _ (hjk' i))).trans_le _), { apply le_of_eq, congr, simp_rw [linear_equiv.map_sum, linear_equiv.map_sub, linear_equiv.map_smul, finset.sum_apply', finsupp.sub_apply, finsupp.smul_apply, finset.sum_sub_distrib, basis.repr_self_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq', finset.mem_univ, if_true] }, { exact_mod_cast ε_le }, end include ist iic /-- We can approximate `a / b : L` with `q / r`, where `r` has finitely many options for `L`. -/ theorem exists_mem_finset_approx' (h : algebra.is_algebraic R L) (a : S) {b : S} (hb : b ≠ 0) : ∃ (q : S) (r ∈ finset_approx bS adm), abv (algebra.norm R (r • a - q * b)) < abv (algebra.norm R b) := begin have inj : function.injective (algebra_map R L), { rw is_scalar_tower.algebra_map_eq R S L, exact (is_integral_closure.algebra_map_injective S R L).comp bS.algebra_map_injective }, obtain ⟨a', b', hb', h⟩ := is_integral_closure.exists_smul_eq_mul h inj a hb, obtain ⟨q, r, hr, hqr⟩ := exists_mem_finset_approx bS adm a' hb', refine ⟨q, r, hr, _⟩, refine lt_of_mul_lt_mul_left _ (show 0 ≤ abv (algebra.norm R (algebra_map R S b')), from abv.nonneg _), refine lt_of_le_of_lt (le_of_eq _) (mul_lt_mul hqr le_rfl (abv.pos ((algebra.norm_ne_zero_iff_of_basis bS).mpr hb)) (abv.nonneg _)), rw [← abv.map_mul, ← monoid_hom.map_mul, ← abv.map_mul, ← monoid_hom.map_mul, ← algebra.smul_def, smul_sub b', sub_mul, smul_comm, h, mul_comm b a', algebra.smul_mul_assoc r a' b, algebra.smul_mul_assoc b' q b] end end real lemma prod_finset_approx_ne_zero : algebra_map R S (∏ m in finset_approx bS adm, m) ≠ 0 := begin refine mt ((injective_iff_map_eq_zero _).mp bS.algebra_map_injective _) _, simp only [finset.prod_eq_zero_iff, not_exists], rintros x hx rfl, exact finset_approx.zero_not_mem bS adm hx end lemma ne_bot_of_prod_finset_approx_mem (J : ideal S) (h : algebra_map _ _ (∏ m in finset_approx bS adm, m) ∈ J) : J ≠ ⊥ := (submodule.ne_bot_iff _).mpr ⟨_, h, prod_finset_approx_ne_zero _ _⟩ include ist iic /-- Each class in the class group contains an ideal `J` such that `M := Π m ∈ finset_approx` is in `J`. -/ theorem exists_mk0_eq_mk0 [is_dedekind_domain S] [is_fraction_ring S L] (h : algebra.is_algebraic R L) (I : (ideal S)⁰) : ∃ (J : (ideal S)⁰), class_group.mk0 L I = class_group.mk0 L J ∧ algebra_map _ _ (∏ m in finset_approx bS adm, m) ∈ (J : ideal S) := begin set M := ∏ m in finset_approx bS adm, m with M_eq, have hM : algebra_map R S M ≠ 0 := prod_finset_approx_ne_zero bS adm, obtain ⟨b, b_mem, b_ne_zero, b_min⟩ := exists_min abv I, suffices : ideal.span {b} ∣ ideal.span {algebra_map _ _ M} * I.1, { obtain ⟨J, hJ⟩ := this, refine ⟨⟨J, _⟩, _, _⟩, { rw mem_non_zero_divisors_iff_ne_zero, rintro rfl, rw [ideal.zero_eq_bot, ideal.mul_bot] at hJ, exact hM (ideal.span_singleton_eq_bot.mp (I.2 _ hJ)) }, { rw class_group.mk0_eq_mk0_iff, exact ⟨algebra_map _ _ M, b, hM, b_ne_zero, hJ⟩ }, rw [← set_like.mem_coe, ← set.singleton_subset_iff, ← ideal.span_le, ← ideal.dvd_iff_le], refine (mul_dvd_mul_iff_left _).mp _, swap, { exact mt ideal.span_singleton_eq_bot.mp b_ne_zero }, rw [subtype.coe_mk, ideal.dvd_iff_le, ← hJ, mul_comm], apply ideal.mul_mono le_rfl, rw [ideal.span_le, set.singleton_subset_iff], exact b_mem }, rw [ideal.dvd_iff_le, ideal.mul_le], intros r' hr' a ha, rw ideal.mem_span_singleton at ⊢ hr', obtain ⟨q, r, r_mem, lt⟩ := exists_mem_finset_approx' L bS adm h a b_ne_zero, apply @dvd_of_mul_left_dvd _ _ q, simp only [algebra.smul_def] at lt, rw ← sub_eq_zero.mp (b_min _ (I.1.sub_mem (I.1.mul_mem_left _ ha) (I.1.mul_mem_left _ b_mem)) lt), refine mul_dvd_mul_right (dvd_trans (ring_hom.map_dvd _ _) hr') _, exact multiset.dvd_prod (multiset.mem_map.mpr ⟨_, r_mem, rfl⟩) end omit iic ist /-- `class_group.mk_M_mem` is a specialization of `class_group.mk0` to (the finite set of) ideals that contain `M := ∏ m in finset_approx L f abs, m`. By showing this function is surjective, we prove that the class group is finite. -/ noncomputable def mk_M_mem [is_fraction_ring S L] [is_dedekind_domain S] (J : {J : ideal S // algebra_map _ _ (∏ m in finset_approx bS adm, m) ∈ J}) : class_group S L := class_group.mk0 _ ⟨J.1, mem_non_zero_divisors_iff_ne_zero.mpr (ne_bot_of_prod_finset_approx_mem bS adm J.1 J.2)⟩ include iic ist lemma mk_M_mem_surjective [is_fraction_ring S L] [is_dedekind_domain S] (h : algebra.is_algebraic R L) : function.surjective (class_group.mk_M_mem L bS adm) := begin intro I', obtain ⟨⟨I, hI⟩, rfl⟩ := class_group.mk0_surjective I', obtain ⟨J, mk0_eq_mk0, J_dvd⟩ := exists_mk0_eq_mk0 L bS adm h ⟨I, hI⟩, exact ⟨⟨J, J_dvd⟩, mk0_eq_mk0.symm⟩ end open_locale classical /-- The main theorem: the class group of an integral closure `S` of `R` in an algebraic extension `L` is finite if there is an admissible absolute value. See also `class_group.fintype_of_admissible_of_finite` where `L` is a finite extension of `K = Frac(R)`, supplying most of the required assumptions automatically. -/ noncomputable def fintype_of_admissible_of_algebraic [is_fraction_ring S L] [is_dedekind_domain S] (h : algebra.is_algebraic R L) : fintype (class_group S L) := @fintype.of_surjective _ _ _ (@fintype.of_equiv _ {J // J ∣ ideal.span ({algebra_map R S (∏ (m : R) in finset_approx bS adm, m)} : set S)} (unique_factorization_monoid.fintype_subtype_dvd _ (by { rw [ne.def, ideal.zero_eq_bot, ideal.span_singleton_eq_bot], exact prod_finset_approx_ne_zero bS adm })) ((equiv.refl _).subtype_equiv (λ I, ideal.dvd_iff_le.trans (by rw [equiv.refl_apply, ideal.span_le, set.singleton_subset_iff])))) (class_group.mk_M_mem L bS adm) (class_group.mk_M_mem_surjective L bS adm h) /-- The main theorem: the class group of an integral closure `S` of `R` in a finite extension `L` of `K = Frac(R)` is finite if there is an admissible absolute value. See also `class_group.fintype_of_admissible_of_algebraic` where `L` is an algebraic extension of `R`, that includes some extra assumptions. -/ noncomputable def fintype_of_admissible_of_finite [is_dedekind_domain R] : fintype (@class_group S L _ _ _ (is_integral_closure.is_fraction_ring_of_finite_extension R K L S)) := begin letI := classical.dec_eq L, letI := is_integral_closure.is_fraction_ring_of_finite_extension R K L S, letI := is_integral_closure.is_dedekind_domain R K L S, choose s b hb_int using finite_dimensional.exists_is_basis_integral R K L, obtain ⟨n, b⟩ := submodule.basis_of_pid_of_le_span _ (is_integral_closure.range_le_span_dual_basis S b hb_int), let bS := b.map ((linear_map.quot_ker_equiv_range _).symm ≪≫ₗ _), refine fintype_of_admissible_of_algebraic L bS adm (λ x, (is_fraction_ring.is_algebraic_iff R K L).mpr (algebra.is_algebraic_of_finite _ _ x)), { rw linear_map.ker_eq_bot.mpr, { exact submodule.quot_equiv_of_eq_bot _ rfl }, { exact is_integral_closure.algebra_map_injective _ R _ } }, { refine (basis.linear_independent _).restrict_scalars _, simp only [algebra.smul_def, mul_one], apply is_fraction_ring.injective } end end is_admissible end euclidean_domain end class_group
fb194602c008bea23574d131e0caebd0f10687fa
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/algebra/field.lean
ccf8f200cedb69f191acb62398e8145dc43f873f
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
18,244
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura Structures with multiplicative and additive components, including division rings and fields. The development is modeled after Isabelle's library. -/ prelude import init.algebra.ring universe variables u /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 class division_ring (α : Type u) extends ring α, has_inv α, zero_ne_one_class α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) variable {α : Type u} section division_ring variables [division_ring α] protected definition algebra.div (a b : α) : α := a * b⁻¹ instance division_ring_has_div [division_ring α] : has_div α := ⟨algebra.div⟩ lemma division_def (a b : α) : a / b = a * b⁻¹ := rfl lemma mul_inv_cancel {a : α} (h : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel h lemma inv_mul_cancel {a : α} (h : a ≠ 0) : a⁻¹ * a = 1 := division_ring.inv_mul_cancel h lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := eq.symm $ one_mul (a⁻¹) local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma div_eq_mul_one_div (a b : α) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel {a : α} (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel {a : α} (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] lemma div_self {a : α} (h : a ≠ 0) : a / a = 1 := by simp [h] lemma one_div_one : 1 / 1 = (1:α) := div_self (ne.symm zero_ne_one) lemma mul_div_assoc (a b c : α) : (a * b) / c = a * (b / c) := by simp lemma one_div_ne_zero {a : α} (h : a ≠ 0) : 1 / a ≠ 0 := suppose 1 / a = 0, have 0 = (1:α), from eq.symm (by rw [-(mul_one_div_cancel h), this, mul_zero]), absurd this zero_ne_one lemma one_inv_eq : 1⁻¹ = (1:α) := suffices 1 * 1⁻¹ = (1:α), begin simp at this, assumption end, mul_inv_cancel (ne.symm (@zero_ne_one α _)) local attribute [simp] one_inv_eq lemma div_one (a : α) : a / 1 = a := by simp lemma zero_div (a : α) : 0 / a = 0 := by simp -- note: integral domain has a "mul_ne_zero". α commutative division ring is an integral -- domain, but let's not define that class for now. lemma division_ring.mul_ne_zero {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := suppose a * b = 0, have a * 1 = 0, by rw [-(mul_one_div_cancel hb), -mul_assoc, this, zero_mul], have a = 0, by rwa mul_one at this, absurd this ha lemma mul_ne_zero_comm {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h, have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h, division_ring.mul_ne_zero h₂ h₁ lemma eq_one_div_of_mul_eq_one {a b : α} (h : a * b = 1) : b = 1 / a := have a ≠ 0, from suppose a = 0, have 0 = (1:α), by rwa [this, zero_mul] at h, absurd this zero_ne_one, have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul], show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this lemma eq_one_div_of_mul_eq_one_left {a b : α} (h : b * a = 1) : b = 1 / a := have a ≠ 0, from suppose a = 0, have 0 = (1:α), by rwa [this, mul_zero] at h, absurd this zero_ne_one, by rw [-h, mul_div_assoc, div_self this, mul_one] lemma division_ring.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (b * a) := have (b * a) * ((1 / a) * (1 / b)) = 1, by rw [mul_assoc, -(mul_assoc a), mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb], eq_one_div_of_mul_eq_one this lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma division_ring.one_div_neg_eq_neg_one_div {a : α} (h : a ≠ 0) : 1 / (- a) = - (1 / a) := have -1 ≠ (0:α), from (suppose -1 = 0, absurd (eq.symm (calc 1 = -(-1) : (neg_neg (1:α))^.symm ... = -0 : by rw this ... = (0:α) : neg_zero)) zero_ne_one), calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw (division_ring.one_div_mul_one_div h this) ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div {a : α} (b : α) (ha : a ≠ 0) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [-inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw (division_ring.one_div_neg_eq_neg_one_div ha) ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, -neg_eq_neg_one_mul] lemma division_ring.neg_div_neg_eq (a : α) {b : α} (hb : b ≠ 0) : (-a) / (-b) = a / b := by rw [(div_neg_eq_neg_div _ hb), neg_div, neg_neg] lemma division_ring.one_div_one_div {a : α} (h : a ≠ 0) : 1 / (1 / a) = a := eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h)) lemma division_ring.eq_of_one_div_eq_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : 1 / a = 1 / b) : a = b := by rw [-(division_ring.one_div_one_div ha), h, (division_ring.one_div_one_div hb)] lemma mul_inv_eq {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := eq.symm $ calc a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp ... = (1 / (b * a)) : division_ring.one_div_mul_one_div ha hb ... = (b * a)⁻¹ : by simp lemma mul_div_cancel (a : α) {b : α} (hb : b ≠ 0) : a * b / b = a := by simp [hb] lemma div_mul_cancel (a : α) {b : α} (hb : b ≠ 0) : a / b * b = a := by simp [hb] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, -neg_div, div_add_div_same, sub_eq_add_neg] lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (suppose a / b = 1, calc a = a / b * b : by simp [hb] ... = 1 * b : by rw this ... = b : by simp) (suppose a = b, by simp [this, hb]) lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b := iff.mp $ div_eq_one_iff_eq a Hb lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (suppose a = b / c, by rw [this, (div_mul_cancel _ hc)]) (suppose a * c = b, by rw [-this, mul_div_cancel _ hc]) lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c := iff.mpr $ eq_div_iff_mul_eq a b hc lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b := iff.mp $ eq_div_iff_mul_eq a b hc lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)], (iff.mpr (eq_div_iff_mul_eq _ _ hc)) this lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) := by simp [hc] end division_ring class field (α : Type u) extends division_ring α, comm_ring α section field variable [field α] lemma field.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [(division_ring.one_div_mul_one_div ha hb), mul_comm b] lemma field.div_mul_right {a b : α} (hb : b ≠ 0) (h : a * b ≠ 0) : a / (a * b) = 1 / b := have a ≠ 0, from ne_zero_of_mul_ne_zero_right h, eq.symm (calc 1 / b = a * ((1 / a) * (1 / b)) : by rw [-mul_assoc, mul_one_div_cancel this, one_mul] ... = a * (1 / (b * a)) : by rw (division_ring.one_div_mul_one_div this hb) ... = a * (a * b)⁻¹ : by rw [inv_eq_one_div, mul_comm a b]) lemma field.div_mul_left {a b : α} (ha : a ≠ 0) (h : a * b ≠ 0) : b / (a * b) = 1 / a := have b * a ≠ 0, from mul_ne_zero_comm h, by rw [mul_comm a, (field.div_mul_right ha this)] lemma mul_div_cancel_left {a : α} (b : α) (ha : a ≠ 0) : a * b / a = b := by rw [mul_comm a, (mul_div_cancel _ ha)] lemma mul_div_cancel' (a : α) {b : α} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel _ hb)] lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := have a * b ≠ 0, from (division_ring.mul_ne_zero ha hb), by rw [add_comm, -(field.div_mul_left ha this), -(field.div_mul_right hb this), division_def, division_def, division_def, -right_distrib] lemma field.div_mul_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) * (c / d) = (a * c) / (b * d) := begin simp [division_def], rw [mul_inv_eq hd hb, mul_comm d⁻¹] end lemma mul_div_mul_left (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [-(field.div_mul_div _ _ hc hb), div_self hc, one_mul] lemma mul_div_mul_right (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, mul_div_mul_left _ hb hc] lemma div_mul_eq_mul_div (a b c : α) : (b / c) * a = (b * a) / c := by simp [division_def] lemma field.div_mul_eq_mul_div_comm (a b : α) {c : α} (hc : c ≠ 0) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div, -(one_mul c), -(field.div_mul_div _ _ (ne.symm zero_ne_one) hc), div_one, one_mul] lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [-(mul_div_mul_right _ hb hd), -(mul_div_mul_left _ hd hb), div_add_div_same] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, -mul_div_assoc, div_add_div _ _ hb hd, -mul_assoc, mul_comm b, mul_assoc, -neg_eq_neg_one_mul] end lemma mul_eq_mul_of_div_eq_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [-(mul_one (a*d)), mul_assoc, (mul_comm d), -mul_assoc, -(div_self hb), -(field.div_mul_eq_mul_div_comm _ _ hb), h, div_mul_eq_mul_div, div_mul_cancel _ hd] lemma field.one_div_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / (a / b) = b / a := have (a / b) * (b / a) = 1, from calc (a / b) * (b / a) = (a * b) / (b * a) : field.div_mul_div _ _ hb ha ... = (a * b) / (a * b) : by rw mul_comm ... = 1 : div_self (division_ring.mul_ne_zero ha hb), eq.symm (eq_one_div_of_mul_eq_one this) lemma field.div_div_eq_mul_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, field.one_div_div hb hc, -mul_div_assoc] lemma field.div_div_eq_div_mul (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, field.div_mul_div _ _ hb hc, mul_one] lemma field.div_div_div_div_eq (a : α) {b c d : α} (hb : b ≠ 0) (hc : c ≠ 0) (hd : d ≠ 0) : (a / b) / (c / d) = (a * d) / (b * c) := by rw [field.div_div_eq_mul_div _ hc hd, div_mul_eq_mul_div, field.div_div_eq_div_mul _ hb hc] lemma field.div_mul_eq_div_mul_one_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : a / (b * c) = (a / b) * (1 / c) := by rw [-(field.div_div_eq_div_mul _ hb hc), -div_eq_mul_one_div] lemma eq_of_mul_eq_mul_of_nonzero_left {a b c : α} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c := by rw [-one_mul b, -div_self h, div_mul_eq_mul_div, h₂, mul_div_cancel_left _ h] lemma eq_of_mul_eq_mul_of_nonzero_right {a b c : α} (h : c ≠ 0) (h2 : a * c = b * c) : a = b := by rw [-mul_one a, -div_self h, -mul_div_assoc, h2, mul_div_cancel _ h] end field class discrete_field (α : Type u) extends field α := (has_decidable_eq : decidable_eq α) (inv_zero : inv zero = zero) attribute [instance] discrete_field.has_decidable_eq section discrete_field variable [discrete_field α] -- many of the lemmas in discrete_field are the same as lemmas in field or division ring, -- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable. lemma discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero (a b : α) (h : a * b = 0) : a = 0 ∨ b = 0 := decidable.by_cases (suppose a = 0, or.inl this) (suppose a ≠ 0, or.inr (by rw [-(one_mul b), -(inv_mul_cancel this), mul_assoc, h, mul_zero])) instance discrete_field.to_integral_domain [s : discrete_field α] : integral_domain α := {s with eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero} lemma inv_zero : 0⁻¹ = (0:α) := discrete_field.inv_zero α lemma one_div_zero : 1 / 0 = (0:α) := calc 1 / 0 = (1:α) * 0⁻¹ : by rw division_def ... = 1 * 0 : by rw inv_zero ... = (0:α) : by rw mul_zero lemma div_zero (a : α) : a / 0 = 0 := by rw [div_eq_mul_one_div, one_div_zero, mul_zero] lemma ne_zero_of_one_div_ne_zero {a : α} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, one_div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero {a : α} (h : 1 / a = 0) : a = 0 := decidable.by_cases (assume ha, ha) (assume ha, false.elim ((one_div_ne_zero ha) h)) lemma one_div_mul_one_div' (a b : α) : (1 / a) * (1 / b) = 1 / (b * a) := decidable.by_cases (suppose a = 0, by rw [this, div_zero, zero_mul, mul_zero, div_zero]) (assume ha : a ≠ 0, decidable.by_cases (suppose b = 0, by rw [this, div_zero, mul_zero, zero_mul, div_zero]) (suppose b ≠ 0, division_ring.one_div_mul_one_div ha this)) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := decidable.by_cases (suppose a = 0, by rw [this, neg_zero, div_zero, neg_zero]) (suppose a ≠ 0, division_ring.one_div_neg_eq_neg_one_div this) lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := decidable.by_cases (assume hb : b = 0, by rw [hb, neg_zero, div_zero, div_zero]) (assume hb : b ≠ 0, division_ring.neg_div_neg_eq _ hb) lemma one_div_one_div (a : α) : 1 / (1 / a) = a := decidable.by_cases (assume ha : a = 0, by rw [ha, div_zero, div_zero]) (assume ha : a ≠ 0, division_ring.one_div_one_div ha) lemma eq_of_one_div_eq_one_div {a b : α} (h : 1 / a = 1 / b) : a = b := decidable.by_cases (assume ha : a = 0, have hb : b = 0, from eq_zero_of_one_div_eq_zero (by rw [-h, ha, div_zero]), hb^.symm ▸ ha) (assume ha : a ≠ 0, have hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (h ▸ (one_div_ne_zero ha)), division_ring.eq_of_one_div_eq_one_div ha hb h) lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := decidable.by_cases (assume ha : a = 0, by rw [ha, mul_zero, inv_zero, zero_mul]) (assume ha : a ≠ 0, decidable.by_cases (assume hb : b = 0, by rw [hb, zero_mul, inv_zero, mul_zero]) (assume hb : b ≠ 0, mul_inv_eq ha hb)) -- the following are specifically for fields lemma one_div_mul_one_div (a b : α) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [one_div_mul_one_div', mul_comm b] lemma div_mul_right {a : α} (b : α) (ha : a ≠ 0) : a / (a * b) = 1 / b := decidable.by_cases (assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero]) (assume hb : b ≠ 0, field.div_mul_right hb (mul_ne_zero ha hb)) lemma div_mul_left (a : α) {b : α} (hb : b ≠ 0) : b / (a * b) = 1 / a := by rw [mul_comm a, div_mul_right _ hb] lemma div_mul_div (a b c d : α) : (a / b) * (c / d) = (a * c) / (b * d) := decidable.by_cases (assume hb : b = 0, by rw [hb, div_zero, zero_mul, zero_mul, div_zero]) (assume hb : b ≠ 0, decidable.by_cases (assume hd : d = 0, by rw [hd, div_zero, mul_zero, mul_zero, div_zero]) (assume hd : d ≠ 0, field.div_mul_div _ _ hb hd)) lemma mul_div_mul_left' (a b : α) {c : α} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := decidable.by_cases (assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero]) (assume hb : b ≠ 0, mul_div_mul_left _ hb hc) lemma mul_div_mul_right' (a b : α) {c : α} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, (mul_div_mul_left' _ _ hc)] lemma div_mul_eq_mul_div_comm (a b c : α) : (b / c) * a = b * (a / c) := decidable.by_cases (assume hc : c = 0, by rw [hc, div_zero, zero_mul, div_zero, mul_zero]) (assume hc : c ≠ 0, field.div_mul_eq_mul_div_comm _ _ hc) lemma one_div_div (a b : α) : 1 / (a / b) = b / a := decidable.by_cases (assume ha : a = 0, by rw [ha, zero_div, div_zero, div_zero]) (assume ha : a ≠ 0, decidable.by_cases (assume hb : b = 0, by rw [hb, div_zero, zero_div, div_zero]) (assume hb : b ≠ 0, field.one_div_div ha hb)) lemma div_div_eq_mul_div (a b c : α) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, one_div_div, -mul_div_assoc] lemma div_div_eq_div_mul (a b c : α) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, div_mul_div, mul_one] lemma div_div_div_div_eq (a b c d : α) : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] lemma div_helper {a : α} (b : α) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h] lemma div_mul_eq_div_mul_one_div (a b c : α) : a / (b * c) = (a / b) * (1 / c) := by rw [-div_div_eq_div_mul, -div_eq_mul_one_div] end discrete_field
91e1001d610d58c051366b7e8db15415091a2578
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/revertlet.lean
882e9a3e676088bf864a67049f91686fc28ad6a5
[ "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
153
lean
theorem ex (n : Nat) (h : n = 0) : 0 + n = 0 := by let m := n + 1 let v := m + 1 have : v = n + 2 := rfl traceState subst h traceState rfl
b8b03982c0ea986b5fd551b32a9c3b8f5789cbd3
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/tactic/default.lean
3e8e99f272ee53c019d742f0109571bda9b0b3e0
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
832
lean
/- This file imports many useful tactics ("the kitchen sink"). You can use `import tactic` at the beginning of your file to get everything. (Although you may want to strip things down when you're polishing.) Because this file imports some complicated tactics, it has many transitive dependencies (which of course may not use `import tactic`, and must import selectively). As (non-exhaustive) examples, these includes things like: * algebra.group_power * algebra.ordered_ring * data.rat * data.nat.prime * data.list.perm * data.set.lattice * data.equiv.encodable * order.complete_lattice -/ import tactic.basic tactic.monotonicity.interactive tactic.finish tactic.tauto tactic.tidy tactic.abel tactic.ring tactic.linarith tactic.omega tactic.wlog tactic.tfae tactic.apply_fun tactic.localized tactic.apply
975458d2dbcf1b8dbc9d7cf52634ea980839a925
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/lattice.lean
f7b1afa3db4c92c02610c1ba190459be003882ea
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
36,518
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.monotone import order.rel_classes import tactic.simps import tactic.pi_instances /-! # (Semi-)lattices Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or meet (least upper bound, or `inf`) operations. Lattices are posets that are both join-semilattices and meet-semilattices. Distributive lattices are lattices which satisfy any of four equivalent distributivity properties, of `sup` over `inf`, on the left or on the right. ## Main declarations * `has_sup`: type class for the `⊔` notation * `has_inf`: type class for the `⊓` notation * `semilattice_sup`: a type class for join semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is commutative, associative and idempotent. * `semilattice_inf`: a type class for meet semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is commutative, associative and idempotent. * `lattice`: a type class for lattices * `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are commutative, associative and satisfy a pair of "absorption laws". * `distrib_lattice`: a type class for distributive lattices. ## Notations * `a ⊔ b`: the supremum or join of `a` and `b` * `a ⊓ b`: the infimum or meet of `a` and `b` ## TODO * (Semi-)lattice homomorphisms * Alternative constructors for distributive lattices from the other distributive properties ## Tags semilattice, lattice -/ set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ /-- Typeclass for the `⊔` (`\lub`) notation -/ @[notation_class] class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ @[notation_class] class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf /-! ### Join-semilattices -/ /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) /-- A type with a commutative, associative and idempotent binary `sup` operation has the structure of a join-semilattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def semilattice_sup.mk' {α : Type*} [has_sup α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α := { sup := (⊔), le := λ a b, a ⊔ b = b, le_refl := sup_idem, le_trans := λ a b c hab hbc, begin dsimp only [(≤)] at *, rwa [←hbc, ←sup_assoc, hab], end, le_antisymm := λ a b hab hba, begin dsimp only [(≤)] at *, rwa [←hba, sup_comm], end, le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem], le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem], sup_le := λ a b c hac hbc, begin dsimp only [(≤), preorder.le] at *, rwa [sup_assoc, hbc], end } instance (α : Type*) [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩ instance (α : Type*) [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩ section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := le_sup_left @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := le_sup_right theorem le_sup_of_le_left (h : c ≤ a) : c ≤ a ⊔ b := le_trans h le_sup_left theorem le_sup_of_le_right (h : c ≤ b) : c ≤ a ⊔ b := le_trans h le_sup_right theorem lt_sup_of_lt_left (h : c < a) : c < a ⊔ b := h.trans_le le_sup_left theorem lt_sup_of_lt_right (h : c < b) : c < a ⊔ b := h.trans_le le_sup_right theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ @[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := sup_eq_left.2 h @[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left @[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := sup_eq_right.2 h @[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := sup_le (le_sup_of_le_left h₁) (le_sup_of_le_right h₂) theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := sup_le_sup le_rfl h₁ theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := sup_le_sup h₁ le_rfl theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by { rw ← h, simp } lemma sup_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h) @[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a := ⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩ @[simp] lemma le_sup_iff [is_total α (≤)] {a b c : α} : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim le_sup_of_le_left le_sup_of_le_right⟩ @[simp] lemma lt_sup_iff [is_total α (≤)] {a b c : α} : a < b ⊔ c ↔ a < b ∨ a < c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩ @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; simp instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; simp instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := le_antisymm (sup_le (sup_le le_sup_left (le_sup_of_le_right le_sup_left)) (le_sup_of_le_right le_sup_right)) (sup_le (le_sup_of_le_left le_sup_left) (sup_le (le_sup_of_le_left le_sup_right) le_sup_right)) instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_right_swap (a b c : α) : a ⊔ b ⊔ c = c ⊔ b ⊔ a := by rw [sup_comm, @sup_comm _ _ a, sup_assoc] @[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b := by rw [← sup_assoc, sup_idem] @[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b := by rw [sup_assoc, sup_idem] lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b := by rw [sup_assoc, sup_assoc, @sup_comm _ _ b] lemma sup_sup_sup_comm (a b c d : α) : a ⊔ b ⊔ (c ⊔ d) = a ⊔ c ⊔ (b ⊔ d) := by rw [sup_assoc, sup_left_comm b, ←sup_assoc] lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) := suffices (∃b, ¬b ≤ a) → (∃b, a < b), by rwa [or_iff_not_imp_left, not_forall], assume ⟨b, hb⟩, ⟨a ⊔ b, lt_of_le_of_ne le_sup_left $ mt left_eq_sup.1 hb⟩ /-- If `f` is monotone, `g` is antitone, and `f ≤ g`, then for all `a`, `b` we have `f a ≤ g b`. -/ theorem monotone.forall_le_of_antitone {β : Type*} [preorder β] {f g : α → β} (hf : monotone f) (hg : antitone g) (h : f ≤ g) (m n : α) : f m ≤ g n := calc f m ≤ f (m ⊔ n) : hf le_sup_left ... ≤ g (m ⊔ n) : h _ ... ≤ g n : hg le_sup_right theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), casesI A, casesI B, injection this; congr' end theorem exists_lt_of_sup (α : Type*) [semilattice_sup α] [nontrivial α] : ∃ a b : α, a < b := begin rcases exists_pair_ne α with ⟨a, b, hne⟩, rcases forall_le_or_exists_lt_sup b with (hb|H), exacts [⟨a, b, (hb a).lt_of_ne hne⟩, ⟨b, H⟩] end lemma ite_le_sup (s s' : α) (P : Prop) [decidable P] : ite P s s' ≤ s ⊔ s' := if h : P then (if_pos h).trans_le le_sup_left else (if_neg h).trans_le le_sup_right end semilattice_sup /-! ### Meet-semilattices -/ /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) instance (α) [semilattice_inf α] : semilattice_sup (order_dual α) := { le_sup_left := semilattice_inf.inf_le_left, le_sup_right := semilattice_inf.inf_le_right, sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance (α) [semilattice_sup α] : semilattice_inf (order_dual α) := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] : order_dual.semilattice_sup (order_dual α) = H := semilattice_sup.ext $ λ _ _, iff.rfl section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_of_left_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_of_right_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h theorem inf_lt_of_left_lt (h : a < c) : a ⊓ b < c := lt_of_le_of_lt inf_le_left h theorem inf_lt_of_right_lt (h : b < c) : a ⊓ b < c := lt_of_le_of_lt inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := @sup_le_iff (order_dual α) _ _ _ _ @[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := inf_eq_left.2 h @[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left @[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := inf_eq_right.2 h @[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := le_inf (inf_le_of_left_le h₁) (inf_le_of_right_le h₂) lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a := inf_le_inf h le_rfl lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c := inf_le_inf le_rfl h theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by { rw ← h, simp } lemma inf_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊓ b) := @sup_ind (order_dual α) _ _ _ _ _ ha hb @[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c := @sup_lt_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_le_iff [is_total α (≤)] {a b c : α} : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a := @le_sup_iff (order_dual α) _ _ _ _ _ @[simp] theorem inf_idem : a ⊓ a = a := @sup_idem (order_dual α) _ _ instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ theorem inf_comm : a ⊓ b = b ⊓ a := @sup_comm (order_dual α) _ _ _ instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := @sup_assoc (order_dual α) _ a b c instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_right_swap (a b c : α) : a ⊓ b ⊓ c = c ⊓ b ⊓ a := by rw [inf_comm, @inf_comm _ _ a, inf_assoc] @[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b := @sup_left_idem (order_dual α) _ a b @[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b := @sup_right_idem (order_dual α) _ a b lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := @sup_left_comm (order_dual α) _ a b c lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b := @sup_right_comm (order_dual α) _ a b c lemma inf_inf_inf_comm (a b c d : α) : a ⊓ b ⊓ (c ⊓ d) = a ⊓ c ⊓ (b ⊓ d) := @sup_sup_sup_comm (order_dual α) _ _ _ _ _ lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) := @forall_le_or_exists_lt_sup (order_dual α) _ a theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), casesI A, casesI B, injection this; congr' end theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] : order_dual.semilattice_inf (order_dual α) = H := semilattice_inf.ext $ λ _ _, iff.rfl theorem exists_lt_of_inf (α : Type*) [semilattice_inf α] [nontrivial α] : ∃ a b : α, a < b := let ⟨a, b, h⟩ := exists_lt_of_sup (order_dual α) in ⟨b, a, h⟩ lemma inf_le_ite (s s' : α) (P : Prop) [decidable P] : s ⊓ s' ≤ ite P s s' := if h : P then inf_le_left.trans_eq (if_pos h).symm else inf_le_right.trans_eq (if_neg h).symm end semilattice_inf /-- A type with a commutative, associative and idempotent binary `inf` operation has the structure of a meet-semilattice. The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`. -/ def semilattice_inf.mk' {α : Type*} [has_inf α] (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α := begin haveI : semilattice_sup (order_dual α) := semilattice_sup.mk' inf_comm inf_assoc inf_idem, haveI i := order_dual.semilattice_inf (order_dual α), exact i, end /-! ### Lattices -/ /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ @[protect_proj] class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α instance (α) [lattice α] : lattice (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } /-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`) and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/ lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : @semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) = @semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) := partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from ⟨λ h, by rw [←h, inf_comm, inf_sup_self], λ h, by rw [←h, sup_comm, sup_inf_self]⟩ /-- A type with a pair of commutative and associative binary operations which satisfy two absorption laws relating the two operations has the structure of a lattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def lattice.mk' {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α := have sup_idem : ∀ (b : α), b ⊔ b = b := λ b, calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self ... = b : by rw sup_inf_self, have inf_idem : ∀ (b : α), b ⊓ b = b := λ b, calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self ... = b : by rw inf_sup_self, let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem, semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem, -- here we help Lean to see that the two partial orders are equal partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in have partial_order_eq : partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst := semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _ sup_inf_self inf_sup_self, { inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left }, inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right }, le_inf := λ a b c, by { rw partial_order_eq, apply le_inf }, ..partial_order_inst, ..semilatt_sup_inst, ..semilatt_inf_inst, } section lattice variables [lattice α] {a b c d : α} lemma inf_le_sup : a ⊓ b ≤ a ⊔ b := inf_le_left.trans le_sup_left @[simp] lemma inf_lt_sup : a ⊓ b < a ⊔ b ↔ a ≠ b := begin split, { rintro H rfl, simpa using H }, { refine λ Hne, lt_iff_le_and_ne.2 ⟨inf_le_sup, λ Heq, Hne _⟩, refine le_antisymm _ _, exacts [le_sup_left.trans (Heq.symm.trans_le inf_le_right), le_sup_right.trans (Heq.symm.trans_le inf_le_left)] } end /-! #### Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _) theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right) theorem inf_sup_self : a ⊓ (a ⊔ b) = a := by simp theorem sup_inf_self : a ⊔ (a ⊓ b) = a := by simp theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a := by rw [sup_eq_right, ←inf_eq_left] theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, casesI A, casesI B, injection SS; injection II; congr' end end lattice /-! ### Distributive lattices -/ /-- A distributive lattice is a lattice that satisfies any of four equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`, on the left or right). The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) /- TODO: alternative constructors from the other distributive properties, and perhaps a `tfae` statement -/ section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] instance (α : Type*) [distrib_lattice α] : distrib_lattice (order_dual α) := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y := calc x ≤ (y ⊓ z) ⊔ x : le_sup_right ... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x] ... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂ ... = y ⊔ (x ⊓ z) : sup_inf_left.symm ... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _ ... ≤ _ : sup_le (le_refl y) inf_le_left lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂)) (le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm)) end distrib_lattice /-! ### Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance linear_order.to_lattice {α : Type u} [o : linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } theorem sup_eq_max [linear_order α] {x y : α} : x ⊔ y = max x y := rfl theorem inf_eq_min [linear_order α] {x y : α} : x ⊓ y = min x y := rfl lemma sup_eq_max_default [semilattice_sup α] [decidable_rel ((≤) : α → α → Prop)] [is_total α (≤)] : (⊔) = (max_default : α → α → α) := begin ext x y, dunfold max_default, split_ifs with h', exacts [sup_of_le_left h', sup_of_le_right $ (total_of (≤) x y).resolve_right h'] end lemma inf_eq_min_default [semilattice_inf α] [decidable_rel ((≤) : α → α → Prop)] [is_total α (≤)] : (⊓) = (min_default : α → α → α) := @sup_eq_max_default (order_dual α) _ _ _ /-- A lattice with total order is a linear order. See note [reducible non-instances]. -/ @[reducible] def lattice.to_linear_order (α : Type u) [lattice α] [decidable_eq α] [decidable_rel ((≤) : α → α → Prop)] [decidable_rel ((<) : α → α → Prop)] [is_total α (≤)] : linear_order α := { decidable_le := ‹_›, decidable_eq := ‹_›, decidable_lt := ‹_›, le_total := total_of (≤), max := (⊔), max_def := sup_eq_max_default, min := (⊓), min_def := inf_eq_min_default, ..‹lattice α› } @[priority 100] -- see Note [lower instance priority] instance linear_order.to_distrib_lattice {α : Type u} [o : linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_of_left_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_of_right_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..linear_order.to_lattice } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance /-! ### Function lattices -/ namespace pi variables {ι : Type*} {α' : ι → Type*} instance [Π i, has_sup (α' i)] : has_sup (Π i, α' i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply [Π i, has_sup (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl lemma sup_def [Π i, has_sup (α' i)] (f g : Π i, α' i) : f ⊔ g = λ i, f i ⊔ g i := rfl instance [Π i, has_inf (α' i)] : has_inf (Π i, α' i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply [Π i, has_inf (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl lemma inf_def [Π i, has_inf (α' i)] (f g : Π i, α' i) : f ⊓ g = λ i, f i ⊓ g i := rfl instance [Π i, semilattice_sup (α' i)] : semilattice_sup (Π i, α' i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, semilattice_inf (α' i)] : semilattice_inf (Π i, α' i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, lattice (α' i)] : lattice (Π i, α' i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance [Π i, distrib_lattice (α' i)] : distrib_lattice (Π i, α' i) := by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field end pi /-! ### Monotone functions and lattices -/ namespace monotone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, min (f x) (g x)) := hf.inf hg lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_sup [semilattice_sup α] [is_total α (≤)] [semilattice_sup β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (is_total.total x y).elim (λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right]) (λ h, by simp only [h, hf h, sup_of_le_left]) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) lemma map_inf [semilattice_inf α] [is_total α (≤)] [semilattice_inf β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := @monotone.map_sup (order_dual α) _ _ _ _ _ hf.dual x y end monotone namespace antitone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (λ x, min (f x) (g x)) := hf.inf hg lemma map_sup_le [semilattice_sup α] [semilattice_inf β] {f : α → β} (h : antitone f) (x y : α) : f (x ⊔ y) ≤ f x ⊓ f y := h.dual_right.le_map_sup x y lemma map_sup [semilattice_sup α] [is_total α (≤)] [semilattice_inf β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊔ y) = f x ⊓ f y := hf.dual_right.map_sup x y lemma le_map_inf [semilattice_inf α] [semilattice_sup β] {f : α → β} (h : antitone f) (x y : α) : f x ⊔ f y ≤ f (x ⊓ y) := h.dual_right.map_inf_le x y lemma map_inf [semilattice_inf α] [is_total α (≤)] [semilattice_sup β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊓ y) = f x ⊔ f y := hf.dual_right.map_inf x y end antitone /-! ### Products of (semi-)lattices -/ namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod /-! ### Subtypes of (semi-)lattices -/ namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype section lift /-- A type endowed with `⊔` is a `semilattice_sup`, if it admits an injective map that preserves `⊔` to a `semilattice_sup`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semilattice_sup [has_sup α] [semilattice_sup β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) : semilattice_sup α := { sup := has_sup.sup, le_sup_left := λ a b, by { change f a ≤ f (a ⊔ b), rw map_sup, exact le_sup_left, }, le_sup_right := λ a b, by { change f b ≤ f (a ⊔ b), rw map_sup, exact le_sup_right, }, sup_le := λ a b c ha hb, by { change f (a ⊔ b) ≤ f c, rw map_sup, exact sup_le ha hb, }, ..partial_order.lift f hf_inj} /-- A type endowed with `⊓` is a `semilattice_inf`, if it admits an injective map that preserves `⊓` to a `semilattice_inf`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semilattice_inf [has_inf α] [semilattice_inf β] (f : α → β) (hf_inj : function.injective f) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : semilattice_inf α := { inf := has_inf.inf, inf_le_left := λ a b, by { change f (a ⊓ b) ≤ f a, rw map_inf, exact inf_le_left, }, inf_le_right := λ a b, by { change f (a ⊓ b) ≤ f b, rw map_inf, exact inf_le_right, }, le_inf := λ a b c ha hb, by { change f a ≤ f (b ⊓ c), rw map_inf, exact le_inf ha hb, }, ..partial_order.lift f hf_inj} /-- A type endowed with `⊔` and `⊓` is a `lattice`, if it admits an injective map that preserves `⊔` and `⊓` to a `lattice`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.lattice [has_sup α] [has_inf α] [lattice β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : lattice α := { ..hf_inj.semilattice_sup f map_sup, ..hf_inj.semilattice_inf f map_inf} /-- A type endowed with `⊔` and `⊓` is a `distrib_lattice`, if it admits an injective map that preserves `⊔` and `⊓` to a `distrib_lattice`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_lattice [has_sup α] [has_inf α] [distrib_lattice β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : distrib_lattice α := { le_sup_inf := λ a b c, by { change f ((a ⊔ b) ⊓ (a ⊔ c)) ≤ f (a ⊔ b ⊓ c), rw [map_inf, map_sup, map_sup, map_sup, map_inf], exact le_sup_inf, }, ..hf_inj.lattice f map_sup map_inf, } end lift --To avoid noncomputability poisoning from `bool.complete_boolean_algebra` instance : distrib_lattice bool := linear_order.to_distrib_lattice
1ae183d4d9f250f57292e1dfd6d9bd2ec8dd99fc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/explode.lean
4307de7d5ced615b1ed74edd0c2d43017223f1ee
[ "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
9,383
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Minchao Wu -/ import meta.rb_map import tactic.core /-! # `#explode` command Displays a proof term in a line by line format somewhat akin to a Fitch style proof or the Metamath proof style. -/ open expr tactic namespace tactic namespace explode @[derive inhabited] inductive status : Type | reg | intro | lam | sintro /-- A type to distinguish introduction or elimination rules represented as strings from theorems referred to by their names. -/ meta inductive thm : Type | expr (e : expr) | name (n : name) | string (s : string) /-- Turn a thm into a string. -/ meta def thm.to_string : thm → string | (thm.expr e) := e.to_string | (thm.name n) := n.to_string | (thm.string s) := s meta structure entry : Type := (expr : expr) (line : nat) (depth : nat) (status : status) (thm : thm) (deps : list nat) meta def pad_right (l : list string) : list string := let n := l.foldl (λ r (s:string), max r s.length) 0 in l.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s @[derive inhabited] meta structure entries : Type := mk' :: (s : expr_map entry) (l : list entry) meta def entries.find (es : entries) (e : expr) : option entry := es.s.find e meta def entries.size (es : entries) : ℕ := es.s.size meta def entries.add : entries → entry → entries | es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩ meta def entries.head (es : entries) : option entry := es.l.head' meta def format_aux : list string → list string → list string → list entry → tactic format | (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do fmt ← do { let margin := string.join (list.replicate en.depth " │"), let margin := match en.status with | status.sintro := " ├" ++ margin | status.intro := " │" ++ margin ++ " ┌" | status.reg := " │" ++ margin ++ "" | status.lam := " │" ++ margin ++ "" end, p ← infer_type en.expr >>= pp, let lhs := line ++ "│" ++ dep ++ "│ " ++ thm ++ margin ++ " ", return $ format.of_string lhs ++ (p.nest lhs.length).group ++ format.line }, (++ fmt) <$> format_aux lines deps thms es | _ _ _ _ := return format.nil meta instance : has_to_tactic_format entries := ⟨λ es : entries, let lines := pad_right $ es.l.map (λ en, to_string en.line), deps := pad_right $ es.l.map (λ en, string.intercalate "," (en.deps.map to_string)), thms := pad_right $ es.l.map (λ en, (entry.thm en).to_string) in format_aux lines deps thms es.l⟩ meta def append_dep (filter : expr → tactic unit) (es : entries) (e : expr) (deps : list nat) : tactic (list nat) := do { ei ← es.find e, filter ei.expr, return (ei.line :: deps) } <|> return deps meta def may_be_proof (e : expr) : tactic bool := do expr.sort u ← infer_type e >>= infer_type, return $ bnot u.nonzero end explode open explode meta mutual def explode.core, explode.args (filter : expr → tactic unit) with explode.core : expr → bool → nat → entries → tactic entries | e@(lam n bi d b) si depth es := do m ← mk_fresh_name, let l := local_const m n bi d, let b' := instantiate_var b l, if si then let en : entry := ⟨l, es.size, depth, status.sintro, thm.name n, []⟩ in do es' ← explode.core b' si depth (es.add en), return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string "∀I", [es.size, es'.size - 1]⟩ else do let en : entry := ⟨l, es.size, depth, status.intro, thm.name n, []⟩, es' ← explode.core b' si (depth + 1) (es.add en), -- in case of a "have" clause, the b' here has an annotation deps' ← explode.append_dep filter es' b'.erase_annotations [], deps' ← explode.append_dep filter es' l deps', return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string "∀I", deps'⟩ | e@(elet n t a b) si depth es := explode.core (reduce_lets e) si depth es | e@(macro n l) si depth es := explode.core l.head si depth es | e si depth es := filter e >> match get_app_fn_args e with | (nm@(const n _), args) := explode.args e args depth es (thm.expr nm) [] | (fn, []) := do let en : entry := ⟨fn, es.size, depth, status.reg, thm.expr fn, []⟩, return (es.add en) | (fn, args) := do es' ← explode.core fn ff depth es, -- in case of a "have" clause, the fn here has an annotation deps ← explode.append_dep filter es' fn.erase_annotations [], explode.args e args depth es' (thm.string "∀E") deps end with explode.args : expr → list expr → nat → entries → thm → list nat → tactic entries | e (arg :: args) depth es thm deps := do es' ← explode.core arg ff depth es <|> return es, deps' ← explode.append_dep filter es' arg deps, explode.args e args depth es' thm deps' | e [] depth es thm deps := return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩) meta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries := let filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in tactic.explode.core filter e tt 0 default meta def explode (n : name) : tactic unit := do const n _ ← resolve_name n | fail "cannot resolve name", d ← get_decl n, v ← match d with | (declaration.defn _ _ _ v _ _) := return v | (declaration.thm _ _ _ v) := return v.get | _ := fail "not a definition" end, t ← pp d.type, explode_expr v <* trace (to_fmt n ++ " : " ++ t) >>= trace setup_tactic_parser /-- `#explode decl_name` displays a proof term in a line-by-line format somewhat akin to a Fitch-style proof or the Metamath proof style. `#explode_widget decl_name` renders a widget that displays an `#explode` proof. `#explode iff_true_intro` produces ```lean iff_true_intro : ∀ {a : Prop}, a → (a ↔ true) 0│ │ a ├ Prop 1│ │ h ├ a 2│ │ hl │ ┌ a 3│ │ trivial │ │ true 4│2,3│ ∀I │ a → true 5│ │ hr │ ┌ true 6│5,1│ ∀I │ true → a 7│4,6│ iff.intro │ a ↔ true 8│1,7│ ∀I │ a → (a ↔ true) 9│0,8│ ∀I │ ∀ {a : Prop}, a → (a ↔ true) ``` In more detail: The output of `#explode` is a Fitch-style proof in a four-column diagram modeled after Metamath proof displays like [this](http://us.metamath.org/mpeuni/ru.html). The headers of the columns are "Step", "Hyp", "Ref", "Type" (or "Expression" in the case of Metamath): * Step: An increasing sequence of numbers to number each step in the proof, used in the Hyp field. * Hyp: The direct children of the current step. Most theorems are implications like `A -> B -> C`, and so on the step proving `C` the Hyp field will refer to the steps that prove `A` and `B`. * Ref: The name of the theorem being applied. This is well-defined in Metamath, but in Lean there are some special steps that may have long names because the structure of proof terms doesn't exactly match this mold. * If the theorem is `foo (x y : Z) : A x -> B y -> C x y`: * the Ref field will contain `foo`, * `x` and `y` will be suppressed, because term construction is not interesting, and * the Hyp field will reference steps proving `A x` and `B y`. This corresponds to a proof term like `@foo x y pA pB` where `pA` and `pB` are subproofs. * If the head of the proof term is a local constant or lambda, then in this case the Ref will say `∀E` for forall-elimination. This happens when you have for example `h : A -> B` and `ha : A` and prove `b` by `h ha`; we reinterpret this as if it said `∀E h ha` where `∀E` is (n-ary) modus ponens. * If the proof term is a lambda, we will also use `∀I` for forall-introduction, referencing the body of the lambda. The indentation level will increase, and a bracket will surround the proof of the body of the lambda, starting at a proof step labeled with the name of the lambda variable and its type, and ending with the `∀I` step. Metamath doesn't have steps like this, but the style is based on Fitch proofs in first-order logic. * Type: This contains the type of the proof term, the theorem being proven at the current step. This proof layout differs from `#print` in using lots of intermediate step displays so that you can follow along and don't have to see term construction steps because they are implicitly in the intermediate step displays. Also, it is common for a Lean theorem to begin with a sequence of lambdas introducing local constants of the theorem. In order to minimize the indentation level, the `∀I` steps at the end of the proof will be introduced in a group and the indentation will stay fixed. (The indentation brackets are only needed in order to delimit the scope of assumptions, and these assumptions have global scope anyway so detailed tracking is not necessary.) -/ @[user_command] meta def explode_cmd (_ : parse $ tk "#explode") : parser unit := do n ← ident, explode n . add_tactic_doc { name := "#explode / #explode_widget", category := doc_category.cmd, decl_names := [`tactic.explode_cmd, `tactic.explode_widget_cmd], inherit_description_from := `tactic.explode_cmd, tags := ["proof display", "widgets"] } end tactic
f9b2e09a2e35fe4e85a5d9eb3d1c3d5bff87dc55
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/measure_theory/ae_eq_fun.lean
8d0d3fb7ba56e7412a4b2886707fa6679ce52b48
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,401
lean
/- Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Zhouhang Zhou -/ import measure_theory.integration import order.filter.germ import topology.continuous_function.algebra /-! # Almost everywhere equal functions Two measurable functions are treated as identical if they are almost everywhere equal. We form the set of equivalence classes under the relation of being almost everywhere equal, which is sometimes known as the `L⁰` space. See `l1_space.lean` for `L¹` space. ## Notation * `α →ₘ[μ] β` is the type of `L⁰` space, where `α` and `β` are measurable spaces and `μ` is a measure on `α`. `f : α →ₘ β` is a "function" in `L⁰`. In comments, `[f]` is also used to denote an `L⁰` function. `ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing. ## Main statements * The linear structure of `L⁰` : Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e., `[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring. See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`, `add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun` * The order structure of `L⁰` : `≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain. And `α →ₘ β` inherits the preorder and partial order of `β`. TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a linear order, since otherwise `f ⊔ g` may not be a measurable function. ## Implementation notes * `f.to_fun` : To find a representative of `f : α →ₘ β`, use `f.to_fun`. For each operation `op` in `L⁰`, there is a lemma called `op_to_fun`, characterizing, say, `(f op g).to_fun`. * `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from a measurable function `f : α → β`, use `ae_eq_fun.mk` * `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ` * `comp₂` : Use `comp₂ g f₁ f₂ to get `[λa, g (f₁ a) (f₂ a)]`. For example, `[f + g]` is `comp₂ (+)` ## Tags function space, almost everywhere equal, `L⁰`, ae_eq_fun -/ noncomputable theory open_locale classical ennreal open set filter topological_space ennreal emetric measure_theory function variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α} namespace measure_theory section measurable_space variables [measurable_space β] variable (β) /-- The equivalence relation of being almost everywhere equal -/ def measure.ae_eq_setoid (μ : measure α) : setoid { f : α → β // ae_measurable f μ } := ⟨λf g, (f : α → β) =ᵐ[μ] g, λ f, ae_eq_refl f, λ f g, ae_eq_symm, λ f g h, ae_eq_trans⟩ variable (α) /-- The space of equivalence classes of measurable functions, where two measurable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def ae_eq_fun (μ : measure α) : Type* := quotient (μ.ae_eq_setoid β) variables {α β} notation α ` →ₘ[`:25 μ `] ` β := ae_eq_fun α β μ end measurable_space namespace ae_eq_fun variables [measurable_space β] [measurable_space γ] [measurable_space δ] /-- Construct the equivalence class `[f]` of an almost everywhere measurable function `f`, based on the equivalence relation of being almost everywhere equal. -/ def mk (f : α → β) (hf : ae_measurable f μ) : α →ₘ[μ] β := quotient.mk' ⟨f, hf⟩ /-- A measurable representative of an `ae_eq_fun` [f] -/ instance : has_coe_to_fun (α →ₘ[μ] β) := ⟨_, λf, ae_measurable.mk _ (quotient.out' f : {f : α → β // ae_measurable f μ}).2⟩ protected lemma measurable (f : α →ₘ[μ] β) : measurable f := ae_measurable.measurable_mk _ protected lemma ae_measurable (f : α →ₘ[μ] β) : ae_measurable f μ := f.measurable.ae_measurable @[simp] lemma quot_mk_eq_mk (f : α → β) (hf) : (quot.mk (@setoid.r _ $ μ.ae_eq_setoid β) ⟨f, hf⟩ : α →ₘ[μ] β) = mk f hf := rfl @[simp] lemma mk_eq_mk {f g : α → β} {hf hg} : (mk f hf : α →ₘ[μ] β) = mk g hg ↔ f =ᵐ[μ] g := quotient.eq' @[simp] lemma mk_coe_fn (f : α →ₘ[μ] β) : mk f f.ae_measurable = f := begin conv_rhs { rw ← quotient.out_eq' f }, set g : {f : α → β // ae_measurable f μ} := quotient.out' f with hg, have : g = ⟨g.1, g.2⟩ := subtype.eq rfl, rw [this, ← mk, mk_eq_mk], exact (ae_measurable.ae_eq_mk _).symm, end @[ext] lemma ext {f g : α →ₘ[μ] β} (h : f =ᵐ[μ] g) : f = g := by rwa [← f.mk_coe_fn, ← g.mk_coe_fn, mk_eq_mk] lemma ext_iff {f g : α →ₘ[μ] β} : f = g ↔ f =ᵐ[μ] g := ⟨λ h, by rw h, λ h, ext h⟩ lemma coe_fn_mk (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β) =ᵐ[μ] f := begin apply (ae_measurable.ae_eq_mk _).symm.trans, exact @quotient.mk_out' _ (μ.ae_eq_setoid β) (⟨f, hf⟩ : {f // ae_measurable f μ}) end @[elab_as_eliminator] lemma induction_on (f : α →ₘ[μ] β) {p : (α →ₘ[μ] β) → Prop} (H : ∀ f hf, p (mk f hf)) : p f := quotient.induction_on' f $ subtype.forall.2 H @[elab_as_eliminator] lemma induction_on₂ {α' β' : Type*} [measurable_space α'] [measurable_space β'] {μ' : measure α'} (f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') {p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → Prop} (H : ∀ f hf f' hf', p (mk f hf) (mk f' hf')) : p f f' := induction_on f $ λ f hf, induction_on f' $ H f hf @[elab_as_eliminator] lemma induction_on₃ {α' β' : Type*} [measurable_space α'] [measurable_space β'] {μ' : measure α'} {α'' β'' : Type*} [measurable_space α''] [measurable_space β''] {μ'' : measure α''} (f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') (f'' : α'' →ₘ[μ''] β'') {p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → (α'' →ₘ[μ''] β'') → Prop} (H : ∀ f hf f' hf' f'' hf'', p (mk f hf) (mk f' hf') (mk f'' hf'')) : p f f' f'' := induction_on f $ λ f hf, induction_on₂ f' f'' $ H f hf /-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`, return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function `[g ∘ f] : α →ₘ γ`. -/ def comp (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : α →ₘ[μ] γ := quotient.lift_on' f (λ f, mk (g ∘ (f : α → β)) (hg.comp_ae_measurable f.2)) $ λ f f' H, mk_eq_mk.2 $ H.fun_comp g @[simp] lemma comp_mk (g : β → γ) (hg : measurable g) (f : α → β) (hf) : comp g hg (mk f hf : α →ₘ[μ] β) = mk (g ∘ f) (hg.comp_ae_measurable hf) := rfl lemma comp_eq_mk (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : comp g hg f = mk (g ∘ f) (hg.comp_ae_measurable f.ae_measurable) := by rw [← comp_mk g hg f f.ae_measurable, mk_coe_fn] lemma coe_fn_comp (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : comp g hg f =ᵐ[μ] g ∘ f := by { rw [comp_eq_mk], apply coe_fn_mk } /-- The class of `x ↦ (f x, g x)`. -/ def pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : α →ₘ[μ] β × γ := quotient.lift_on₂' f g (λ f g, mk (λ x, (f.1 x, g.1 x)) (f.2.prod_mk g.2)) $ λ f g f' g' Hf Hg, mk_eq_mk.2 $ Hf.prod_mk Hg @[simp] lemma pair_mk_mk (f : α → β) (hf) (g : α → γ) (hg) : (mk f hf : α →ₘ[μ] β).pair (mk g hg) = mk (λ x, (f x, g x)) (hf.prod_mk hg) := rfl lemma pair_eq_mk (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : f.pair g = mk (λ x, (f x, g x)) (f.ae_measurable.prod_mk g.ae_measurable) := by simp only [← pair_mk_mk, mk_coe_fn] lemma coe_fn_pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : f.pair g =ᵐ[μ] (λ x, (f x, g x)) := by { rw pair_eq_mk, apply coe_fn_mk } /-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions `[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function `λa, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function `[λa, g (f₁ a) (f₂ a)] : α →ₘ γ` -/ def comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : α →ₘ[μ] δ := comp _ hg (f₁.pair f₂) @[simp] lemma comp₂_mk_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) : comp₂ g hg (mk f₁ hf₁ : α →ₘ[μ] β) (mk f₂ hf₂) = mk (λa, g (f₁ a) (f₂ a)) (hg.comp_ae_measurable (hf₁.prod_mk hf₂)) := rfl lemma comp₂_eq_pair {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : comp₂ g hg f₁ f₂ = comp _ hg (f₁.pair f₂) := rfl lemma comp₂_eq_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : comp₂ g hg f₁ f₂ = mk (λ a, g (f₁ a) (f₂ a)) (hg.comp_ae_measurable (f₁.ae_measurable.prod_mk f₂.ae_measurable)) := by rw [comp₂_eq_pair, pair_eq_mk, comp_mk]; refl lemma coe_fn_comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : comp₂ g hg f₁ f₂ =ᵐ[μ] λ a, g (f₁ a) (f₂ a) := by { rw comp₂_eq_mk, apply coe_fn_mk } /-- Interpret `f : α →ₘ[μ] β` as a germ at `μ.ae` forgetting that `f` is almost everywhere measurable. -/ def to_germ (f : α →ₘ[μ] β) : germ μ.ae β := quotient.lift_on' f (λ f, ((f : α → β) : germ μ.ae β)) $ λ f g H, germ.coe_eq.2 H @[simp] lemma mk_to_germ (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β).to_germ = f := rfl lemma to_germ_eq (f : α →ₘ[μ] β) : f.to_germ = (f : α → β) := by rw [← mk_to_germ, mk_coe_fn] lemma to_germ_injective : injective (to_germ : (α →ₘ[μ] β) → germ μ.ae β) := λ f g H, ext $ germ.coe_eq.1 $ by rwa [← to_germ_eq, ← to_germ_eq] lemma comp_to_germ (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : (comp g hg f).to_germ = f.to_germ.map g := induction_on f $ λ f hf, by simp lemma comp₂_to_germ (g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : (comp₂ g hg f₁ f₂).to_germ = f₁.to_germ.map₂ g f₂.to_germ := induction_on₂ f₁ f₂ $ λ f₁ hf₁ f₂ hf₂, by simp /-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a` for almost all `a` -/ def lift_pred (p : β → Prop) (f : α →ₘ[μ] β) : Prop := f.to_germ.lift_pred p /-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of `(f a, g a)` for almost all `a` -/ def lift_rel (r : β → γ → Prop) (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : Prop := f.to_germ.lift_rel r g.to_germ lemma lift_rel_mk_mk {r : β → γ → Prop} {f : α → β} {g : α → γ} {hf hg} : lift_rel r (mk f hf : α →ₘ[μ] β) (mk g hg) ↔ ∀ᵐ a ∂μ, r (f a) (g a) := iff.rfl lemma lift_rel_iff_coe_fn {r : β → γ → Prop} {f : α →ₘ[μ] β} {g : α →ₘ[μ] γ} : lift_rel r f g ↔ ∀ᵐ a ∂μ, r (f a) (g a) := by rw [← lift_rel_mk_mk, mk_coe_fn, mk_coe_fn] section order instance [preorder β] : preorder (α →ₘ[μ] β) := preorder.lift to_germ @[simp] lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) : (mk f hf : α →ₘ[μ] β) ≤ mk g hg ↔ f ≤ᵐ[μ] g := iff.rfl @[simp, norm_cast] lemma coe_fn_le [preorder β] {f g : α →ₘ[μ] β} : (f : α → β) ≤ᵐ[μ] g ↔ f ≤ g := lift_rel_iff_coe_fn.symm instance [partial_order β] : partial_order (α →ₘ[μ] β) := partial_order.lift to_germ to_germ_injective /- TODO: Prove `L⁰` space is a lattice if β is linear order. What if β is only a lattice? -/ -- instance [linear_order β] : semilattice_sup (α →ₘ β) := -- { sup := comp₂ (⊔) (_), -- .. ae_eq_fun.partial_order } end order variable (α) /-- The equivalence class of a constant function: `[λa:α, b]`, based on the equivalence relation of being almost everywhere equal -/ def const (b : β) : α →ₘ[μ] β := mk (λa:α, b) ae_measurable_const lemma coe_fn_const (b : β) : (const α b : α →ₘ[μ] β) =ᵐ[μ] function.const α b := coe_fn_mk _ _ variable {α} instance [inhabited β] : inhabited (α →ₘ[μ] β) := ⟨const α (default β)⟩ @[to_additive] instance [has_one β] : has_one (α →ₘ[μ] β) := ⟨const α 1⟩ @[to_additive] lemma one_def [has_one β] : (1 : α →ₘ[μ] β) = mk (λa:α, 1) ae_measurable_const := rfl @[to_additive] lemma coe_fn_one [has_one β] : ⇑(1 : α →ₘ[μ] β) =ᵐ[μ] 1 := coe_fn_const _ _ @[simp, to_additive] lemma one_to_germ [has_one β] : (1 : α →ₘ[μ] β).to_germ = 1 := rfl section monoid variables [topological_space γ] [second_countable_topology γ] [borel_space γ] [monoid γ] [has_continuous_mul γ] @[to_additive] instance : has_mul (α →ₘ[μ] γ) := ⟨comp₂ (*) measurable_mul⟩ @[simp, to_additive] lemma mk_mul_mk (f g : α → γ) (hf hg) : (mk f hf : α →ₘ[μ] γ) * (mk g hg) = mk (f * g) (hf.mul hg) := rfl @[to_additive] lemma coe_fn_mul (f g : α →ₘ[μ] γ) : ⇑(f * g) =ᵐ[μ] f * g := coe_fn_comp₂ _ _ _ _ @[simp, to_additive] lemma mul_to_germ (f g : α →ₘ[μ] γ) : (f * g).to_germ = f.to_germ * g.to_germ := comp₂_to_germ _ _ _ _ @[to_additive] instance : monoid (α →ₘ[μ] γ) := to_germ_injective.monoid to_germ one_to_germ mul_to_germ end monoid @[to_additive] instance comm_monoid [topological_space γ] [second_countable_topology γ] [borel_space γ] [comm_monoid γ] [has_continuous_mul γ] : comm_monoid (α →ₘ[μ] γ) := to_germ_injective.comm_monoid to_germ one_to_germ mul_to_germ section group variables [topological_space γ] [borel_space γ] [group γ] [topological_group γ] @[to_additive] instance : has_inv (α →ₘ[μ] γ) := ⟨comp has_inv.inv measurable_inv⟩ @[simp, to_additive] lemma inv_mk (f : α → γ) (hf) : (mk f hf : α →ₘ[μ] γ)⁻¹ = mk f⁻¹ hf.inv := rfl @[to_additive] lemma coe_fn_inv (f : α →ₘ[μ] γ) : ⇑(f⁻¹) =ᵐ[μ] f⁻¹ := coe_fn_comp _ _ _ @[to_additive] lemma inv_to_germ (f : α →ₘ[μ] γ) : (f⁻¹).to_germ = f.to_germ⁻¹ := comp_to_germ _ _ _ variables [second_countable_topology γ] @[to_additive] instance : has_div (α →ₘ[μ] γ) := ⟨comp₂ has_div.div measurable_div⟩ @[to_additive, simp] lemma mk_div (f g : α → γ) (hf hg) : mk (f / g) (ae_measurable.div hf hg) = (mk f hf : α →ₘ[μ] γ) / (mk g hg) := rfl @[to_additive] lemma coe_fn_div (f g : α →ₘ[μ] γ) : ⇑(f / g) =ᵐ[μ] f / g := coe_fn_comp₂ _ _ _ _ @[to_additive] lemma div_to_germ (f g : α →ₘ[μ] γ) : (f / g).to_germ = f.to_germ / g.to_germ := comp₂_to_germ _ _ _ _ @[to_additive] instance : group (α →ₘ[μ] γ) := to_germ_injective.group _ one_to_germ mul_to_germ inv_to_germ div_to_germ end group @[to_additive] instance [topological_space γ] [borel_space γ] [comm_group γ] [topological_group γ] [second_countable_topology γ] : comm_group (α →ₘ[μ] γ) := { .. ae_eq_fun.group, .. ae_eq_fun.comm_monoid } section semimodule variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜] [measurable_space 𝕜] [opens_measurable_space 𝕜] variables [topological_space γ] [borel_space γ] [add_comm_monoid γ] [semimodule 𝕜 γ] [has_continuous_smul 𝕜 γ] instance : has_scalar 𝕜 (α →ₘ[μ] γ) := ⟨λ c f, comp ((•) c) (measurable_id.const_smul c) f⟩ @[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf) : c • (mk f hf : α →ₘ[μ] γ) = mk (c • f) (hf.const_smul _) := rfl lemma coe_fn_smul (c : 𝕜) (f : α →ₘ[μ] γ) : ⇑(c • f) =ᵐ[μ] c • f := coe_fn_comp _ _ _ lemma smul_to_germ (c : 𝕜) (f : α →ₘ[μ] γ) : (c • f).to_germ = c • f.to_germ := comp_to_germ _ _ _ variables [second_countable_topology γ] [has_continuous_add γ] instance : semimodule 𝕜 (α →ₘ[μ] γ) := to_germ_injective.semimodule 𝕜 ⟨@to_germ α γ _ μ _, zero_to_germ, add_to_germ⟩ smul_to_germ end semimodule open ennreal /-- For `f : α → ℝ≥0∞`, define `∫ [f]` to be `∫ f` -/ def lintegral (f : α →ₘ[μ] ℝ≥0∞) : ℝ≥0∞ := quotient.lift_on' f (λf, ∫⁻ a, (f : α → ℝ≥0∞) a ∂μ) (assume f g, lintegral_congr_ae) @[simp] lemma lintegral_mk (f : α → ℝ≥0∞) (hf) : (mk f hf : α →ₘ[μ] ℝ≥0∞).lintegral = ∫⁻ a, f a ∂μ := rfl lemma lintegral_coe_fn (f : α →ₘ[μ] ℝ≥0∞) : ∫⁻ a, f a ∂μ = f.lintegral := by rw [← lintegral_mk, mk_coe_fn] @[simp] lemma lintegral_zero : lintegral (0 : α →ₘ[μ] ℝ≥0∞) = 0 := lintegral_zero @[simp] lemma lintegral_eq_zero_iff {f : α →ₘ[μ] ℝ≥0∞} : lintegral f = 0 ↔ f = 0 := induction_on f $ λ f hf, (lintegral_eq_zero_iff' hf).trans mk_eq_mk.symm lemma lintegral_add (f g : α →ₘ[μ] ℝ≥0∞) : lintegral (f + g) = lintegral f + lintegral g := induction_on₂ f g $ λ f hf g hg, by simp [lintegral_add' hf hg] lemma lintegral_mono {f g : α →ₘ[μ] ℝ≥0∞} : f ≤ g → lintegral f ≤ lintegral g := induction_on₂ f g $ λ f hf g hg hfg, lintegral_mono_ae hfg section pos_part variables [topological_space γ] [linear_order γ] [order_closed_topology γ] [second_countable_topology γ] [has_zero γ] [opens_measurable_space γ] /-- Positive part of an `ae_eq_fun`. -/ def pos_part (f : α →ₘ[μ] γ) : α →ₘ[μ] γ := comp (λ x, max x 0) (measurable_id.max measurable_const) f @[simp] lemma pos_part_mk (f : α → γ) (hf) : pos_part (mk f hf : α →ₘ[μ] γ) = mk (λ x, max (f x) 0) (hf.max ae_measurable_const) := rfl lemma coe_fn_pos_part (f : α →ₘ[μ] γ) : ⇑(pos_part f) =ᵐ[μ] (λ a, max (f a) 0) := coe_fn_comp _ _ _ end pos_part end ae_eq_fun end measure_theory namespace continuous_map open measure_theory variables [topological_space α] [borel_space α] (μ) variables [topological_space β] [measurable_space β] [borel_space β] /-- The equivalence class of `μ`-almost-everywhere measurable functions associated to a continuous map. -/ def to_ae_eq_fun (f : C(α, β)) : α →ₘ[μ] β := ae_eq_fun.mk f f.continuous.measurable.ae_measurable lemma coe_fn_to_ae_eq_fun (f : C(α, β)) : f.to_ae_eq_fun μ =ᵐ[μ] f := ae_eq_fun.coe_fn_mk f _ variables [group β] [topological_group β] [second_countable_topology β] /-- The `mul_hom` from the group of continuous maps from `α` to `β` to the group of equivalence classes of `μ`-almost-everywhere measurable functions. -/ @[to_additive "The `add_hom` from the group of continuous maps from `α` to `β` to the group of equivalence classes of `μ`-almost-everywhere measurable functions."] def to_ae_eq_fun_mul_hom : C(α, β) →* α →ₘ[μ] β := { to_fun := continuous_map.to_ae_eq_fun μ, map_one' := rfl, map_mul' := λ f g, ae_eq_fun.mk_mul_mk f g f.continuous.measurable.ae_measurable g.continuous.measurable.ae_measurable } variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜] [measurable_space 𝕜] [opens_measurable_space 𝕜] variables [topological_space γ] [measurable_space γ] [borel_space γ] [add_comm_group γ] [semimodule 𝕜 γ] [topological_add_group γ] [has_continuous_smul 𝕜 γ] [second_countable_topology γ] /-- The linear map from the group of continuous maps from `α` to `β` to the group of equivalence classes of `μ`-almost-everywhere measurable functions. -/ def to_ae_eq_fun_linear_map : C(α, γ) →ₗ[𝕜] α →ₘ[μ] γ := { map_smul' := λ c f, ae_eq_fun.smul_mk c f f.continuous.measurable.ae_measurable, .. to_ae_eq_fun_add_hom μ } end continuous_map
864f4137a67995061899c4930d69065b28d33aac
59b654f4ee2fef898a3487dc03554a569051b63a
/src/old/generic_cube_graph.lean
72058cd72d17dfccccadd2b4cb423ea665f4b672
[]
no_license
gunpinyo/twisted_cube_formalisation
180c9157478b66ec2b11ca47c8ff998a3e978a88
f78206ac495e84bd43a9b820fa10b6c94722e0ec
refs/heads/master
1,624,501,222,992
1,607,081,624,000
1,607,081,624,000
166,885,106
0
0
null
null
null
null
UTF-8
Lean
false
false
19,707
lean
import graph section variable tw : bool variable G : graph def prism_graph.nodes := bool × G.nodes def prism_graph.edges := (bool × G.edges) ⊕ G.nodes def prism_graph.srctrg (b : bool) : prism_graph.edges G → prism_graph.nodes G | (sum.inl (b', e)) := (b', G.srctrg (bxor (band b' tw) b) e) | (sum.inr v) := (b, v) lemma prism_graph.edge_ext : ∀ (tw : bool) (G : graph) (e e' : prism_graph.edges G), (∀ b, prism_graph.srctrg tw G b e = prism_graph.srctrg tw G b e') → e = e' | tw G (sum.inl (ff, e)) (sum.inl (ff, e')) p := begin congr, apply G.edge_ext e e', cases tw, all_goals { simp [prism_graph.srctrg] at p, assumption,}, end | tw G (sum.inl (ff, e)) (sum.inl (tt, e')) p := begin simp [prism_graph.srctrg] at p, contradiction, end | tw G (sum.inl (tt, e)) (sum.inl (ff, e')) p := begin simp [prism_graph.srctrg] at p, contradiction, end | tw G (sum.inl (tt, e)) (sum.inl (tt, e')) p := begin congr, apply G.edge_ext e e', cases tw, { simp [prism_graph.srctrg] at p, assumption,}, simp [prism_graph.srctrg] at p, intro b, cases b, exact p tt, exact p ff, end | tw G (sum.inl (b, e)) (sum.inr v') p := begin let pnb := p (not b), cases b, all_goals { simp [prism_graph.srctrg] at pnb, contradiction}, end | tw G (sum.inr v) (sum.inl (b', e')) p := begin let pnb := p (not b'), cases b', all_goals { simp [prism_graph.srctrg] at pnb, contradiction}, end | tw G (sum.inr v) (sum.inr v') p := begin simp [prism_graph.srctrg] at p, congr, assumption, end def prism_graph : graph := { nodes := prism_graph.nodes G , edges := prism_graph.edges G , srctrg := prism_graph.srctrg tw G , edge_ext := prism_graph.edge_ext tw G } end def cube_graph (tw : bool) : ℕ → graph | 0 := graph.singleton_reflexive | (n +1) := prism_graph tw (cube_graph n) section variable tw : bool variable n : ℕ def cube_graph_alt.nodes := bitvec n def cube_graph_alt.edges := bitvec n ⊕ (fin n × bitvec (nat.pred n)) def cube_graph_alt.num_zeros_is_odd : Π {n : ℕ} (i : fin (n +1)) (v : bitvec n), bool | 0 _ _ := ff | (n +1) i v := fin.maybe_pred_rec ff (λ i', bxor (v.head) (cube_graph_alt.num_zeros_is_odd i' v.tail)) i def cube_graph_alt.srctrg (b : bool) : cube_graph_alt.edges n → cube_graph_alt.nodes n | (sum.inl v) := v | (sum.inr (i, v)) := match n, i, v with | 0, i, v := i.elim0 | (_ +1), i, v := let tw_bit := cube_graph_alt.num_zeros_is_odd i v in vector.insert_nth (bxor (band tw tw_bit) b) i v end private lemma cube_graph_alt.edge_ext_helper : ∀ (n : ℕ) (i : fin (n +1)) (v : bitvec n) (v' : bitvec (n +1)), (∀ b, v.insert_nth b i = v') → false | 0 i v v' p := begin replace p := p (bnot v'.head), cases i, cases i_val, swap, { exact nat.not_succ_le_zero i_val (nat.le_of_lt_succ i_is_lt),}, rw [fin.to_zero, vector.insert_nth_zero] at p, replace p := (vector.cons_injection p).1, simp at p, exact bnot_self p, end | (n +1) ⟨0, pz⟩ v v' p := begin replace p := p (bnot v'.head), simp [fin.to_zero, vector.insert_nth_zero] at p, replace p := (vector.cons_injection p).1, simp at p, exact bnot_self p, end | (n +1) ⟨i +1, psi⟩ v v' p := begin let fin_i := fin.mk_from_succ i psi, refine cube_graph_alt.edge_ext_helper n fin_i v.tail v'.tail _, intro b, replace p := congr_arg vector.tail (p b), rwa [fin.to_succ, vector.insert_nth_succ] at p, end lemma cube_graph_alt.edge_ext : ∀ (tw : bool) (n : ℕ) (e e' : cube_graph_alt.edges n), (∀ b, cube_graph_alt.srctrg tw n b e = cube_graph_alt.srctrg tw n b e') → e = e' | tw n (sum.inl v) (sum.inl v') p := begin simp [cube_graph_alt.srctrg] at p, congr, assumption, end | tw (n +1) (sum.inl v) (sum.inr (i', v')) p := begin exfalso, simp [cube_graph_alt.srctrg] at p, refine cube_graph_alt.edge_ext_helper n i' v' v _, intro b, symmetry, replace p := p (bxor(band tw (cube_graph_alt.num_zeros_is_odd i' v'))b), rwa [bxor_comm, bxor_bxor_id] at p, end | tw (n +1) (sum.inr (i, v)) (sum.inl v') p := begin exfalso, simp [cube_graph_alt.srctrg] at p, refine cube_graph_alt.edge_ext_helper n i v v' _, intro b, replace p := p (bxor (band tw (cube_graph_alt.num_zeros_is_odd i v)) b), rwa [bxor_comm, bxor_bxor_id] at p, end | tw (n +1) (sum.inr (⟨0, pi⟩, v)) (sum.inr (⟨0, pi'⟩, v')) p := begin simp [cube_graph_alt.srctrg, vector.insert_nth, list.insert_nth] at p, congr, exact subtype.eq (p tt).2 end | tw 1 (sum.inr (⟨0, pz⟩, v)) (sum.inr (⟨i' +1, psi'⟩, v')) p := begin exfalso, exact nat.not_lt_zero i' (nat.pred_le_pred psi') end | tw 1 (sum.inr (⟨i +1, psi⟩, v)) (sum.inr (⟨0, pz'⟩, v')) p := begin exfalso, exact nat.not_lt_zero i (nat.pred_le_pred psi) end | tw 1 (sum.inr (⟨i +1, psi⟩, v)) (sum.inr (⟨i' +1, psi'⟩, v')) p := begin exfalso, exact nat.not_lt_zero i (nat.pred_le_pred psi) end | tw (n +2) (sum.inr (⟨0, pz⟩, v)) (sum.inr (⟨i' +1, psi'⟩, v')) p := begin exfalso, replace p := p (bnot v'.head), simp [cube_graph_alt.srctrg, fin.to_succ, fin.to_zero] at p, rw [vector.insert_nth_succ, vector.insert_nth_zero] at p, simp [vector.insert_nth, list.insert_nth] at p, replace p := (vector.cons_injection p).1, simp [fin.zero, cube_graph_alt.num_zeros_is_odd] at p, exact bnot_self p, end | tw (n +2) (sum.inr (⟨i +1, psi⟩, v)) (sum.inr (⟨0, pz'⟩, v')) p := begin exfalso, replace p := p (bnot v.head), simp [cube_graph_alt.srctrg, fin.to_succ, fin.to_zero] at p, rw [vector.insert_nth_succ, vector.insert_nth_zero] at p, simp [vector.insert_nth, list.insert_nth] at p, replace p := (vector.cons_injection p).1, simp [fin.zero, cube_graph_alt.num_zeros_is_odd] at p, exact bnot_self (eq.symm p), end | tw (n +2) (sum.inr (⟨i +1, psi⟩, v)) (sum.inr (⟨i' +1, psi'⟩, v')) p := begin let fin_i := fin.mk_from_succ i psi, let fin_i' := fin.mk_from_succ i' psi', simp [fin.to_succ] at p, suffices : ∀ b, v.head = v'.head ∧ cube_graph_alt.srctrg tw (n + 1) b (sum.inr (fin_i, v.tail)) = cube_graph_alt.srctrg tw (n + 1) b (sum.inr (fin_i', v'.tail)), { let e_eq := cube_graph_alt.edge_ext tw (n + 1) (sum.inr (fin_i, v.tail)) (sum.inr (fin_i', v'.tail)) (λ b, (this b).2), injection e_eq with e_eq', injection e_eq' with i_i'_fin_eq v_v'_tail_eq, congr, {injection i_i'_fin_eq,}, rw [←v.cons_head_tail, ←v'.cons_head_tail], rw [(this tt).1, v_v'_tail_eq],}, suffices : ∀ (fin_i : fin (n +1)) (v : bitvec (n +1)) (b : bool), cube_graph_alt.srctrg tw (n + 2) b (sum.inr (fin_i.succ, v)) = v.head :: cube_graph_alt.srctrg tw (n + 1) (bxor (band tw v.head) b) (sum.inr (fin_i, v.tail)), { intro b, replace p := p (bxor (band tw v.head) b), rw [this, this] at p, let p' := vector.cons_injection p, simp at p', rw [←p'.1, bxor_bxor_id] at p, rw [←p'.1] at |-, exact vector.cons_injection p,}, clear p fin_i fin_i' psi psi' i i' v v', intros fin_i v b, simp [cube_graph_alt.srctrg], rw ←vector.insert_nth_succ, cases tw, {simp,}, simp, suffices : cube_graph_alt.num_zeros_is_odd fin_i.succ v = bxor (vector.head v) (cube_graph_alt.num_zeros_is_odd fin_i (vector.tail v)), {rw this,}, rw ←vector.cons_head_tail v, cases fin_i with i pi, simp [fin.succ, cube_graph_alt.num_zeros_is_odd], refl, end def cube_graph_alt : graph := { nodes := cube_graph_alt.nodes n , edges := cube_graph_alt.edges n , srctrg := cube_graph_alt.srctrg tw n , edge_ext := cube_graph_alt.edge_ext tw n } end namespace cg_to_cg' section variable tw : bool def nodes_map : Π (n : ℕ), (cube_graph tw n).nodes → (cube_graph_alt tw n).nodes | 0 _ := vector.nil | (n +1) (b, v) := b :: (nodes_map n v) def edges_map : Π (n : ℕ), (cube_graph tw n).edges → (cube_graph_alt tw n).edges | 0 _ := sum.inl vector.nil | (n +1) (sum.inl (b, e)) := match edges_map n e with | sum.inl v := sum.inl (b :: v) | sum.inr (i, v) := match n, i, v with | 0, i, v := i.elim0 | (_ +1), i, v := sum.inr (i.succ, b :: v) end end | (n +1) (sum.inr v) := sum.inr (fin.zero, nodes_map tw n v) lemma srctrg_map (n : ℕ) (b : bool) (e : (cube_graph tw n).edges) : nodes_map tw n ((cube_graph tw n).srctrg b e) = (cube_graph_alt tw n).srctrg b (edges_map tw n e) := begin revert b, induction n with n IH, { intro, refl,}, intro b, cases e with be v, { cases be with b' e, dsimp [cube_graph, prism_graph, prism_graph.srctrg, nodes_map, edges_map], rw [IH], dsimp [cube_graph_alt], cases edges_map tw n e with v iv, { dsimp [edges_map._match_1, cube_graph_alt.srctrg], refl,}, { cases n, { cases iv with i, exact i.elim0,}, cases iv with i v, dsimp [edges_map._match_1, edges_map._match_2, cube_graph_alt.srctrg], rw vector.insert_nth_succ, cases tw, {simp,}, simp, suffices : cube_graph_alt.num_zeros_is_odd i.succ (b' :: v) = bxor b' (cube_graph_alt.num_zeros_is_odd i v), rw this, cases i with i_val i_p, cases v with v_l v_p, simp [fin.succ, vector.cons, cube_graph_alt.num_zeros_is_odd], refl,},}, { transitivity (b :: nodes_map tw n v), refl, have : (edges_map tw (n +1) (sum.inr v) : (cube_graph_alt tw (n +1)).edges) = (sum.inr (fin.zero, nodes_map tw n v)), refl, rw this, transitivity cube_graph_alt.srctrg tw (n +1) b (sum.inr (fin.zero, nodes_map tw n v)), swap, {refl,}, simp [cube_graph_alt.srctrg], rw [vector.insert_nth_zero], congr, induction n with n IH, {simp [cube_graph_alt.num_zeros_is_odd],}, simp [fin.zero, cube_graph_alt.num_zeros_is_odd],}, end end end cg_to_cg' def cg_to_cg' (tw : bool) (n : ℕ) : graph_cat.hom (cube_graph tw n) (cube_graph_alt tw n) := { nodes_map := cg_to_cg'.nodes_map tw n , edges_map := cg_to_cg'.edges_map tw n , srctrg_map := cg_to_cg'.srctrg_map tw n } namespace cg'_to_cg section variable tw : bool def nodes_map : Π (n : ℕ), (cube_graph_alt tw n).nodes → (cube_graph tw n).nodes | 0 _ := unit.star | (n +1) v := (v.head, nodes_map n v.tail) def edges_map : Π (n : ℕ), (cube_graph_alt tw n).edges → (cube_graph tw n).edges | 0 _ := unit.star | (n +1) (sum.inl v) := sum.inl (v.head, edges_map n (sum.inl v.tail)) | (n +1) (sum.inr (i, v)) := fin.maybe_pred_rec (sum.inr (nodes_map tw n v)) (λ i' : fin n, sum.inl (match n, i', v with | 0, i', _ := i'.elim0 | (_ +1), _, v := v.head end, edges_map n (sum.inr (i', v.tail)))) i lemma srctrg_map : ∀ (n : ℕ) (b : bool) (e : (cube_graph_alt tw n).edges), nodes_map tw n ((cube_graph_alt tw n).srctrg b e) = (cube_graph tw n).srctrg b (edges_map tw n e) | 0 b e := rfl | (n +1) b (sum.inl v) := begin dsimp [cube_graph_alt, cube_graph_alt.srctrg], cases v with b'l p, cases b'l with b' l, {simp at p, contradiction,}, simp [nodes_map, edges_map, vector.head, vector.tail], dunfold cube_graph, dunfold prism_graph, simp [prism_graph.srctrg], rw ←srctrg_map, congr, end | 1 b (sum.inr (i, v)) := begin cases i with i_val i_is_lt, cases i_val with i'_val, swap, { exfalso, exact nat.not_succ_le_zero i'_val (nat.le_of_lt_succ i_is_lt),}, dsimp [cube_graph_alt, cube_graph_alt.srctrg], rw [vector.eq_nil v, fin.to_zero, vector.insert_nth_zero], simp [nodes_map, fin.zero, cube_graph_alt.num_zeros_is_odd], simp [edges_map, fin.zero], dsimp [cube_graph, prism_graph, prism_graph.srctrg, nodes_map], refl, end | (n +2) b (sum.inr (⟨0, pz⟩, v)) := begin dsimp [cube_graph_alt, cube_graph_alt.srctrg], rw [fin.to_zero, vector.insert_nth_zero], simp [nodes_map, fin.zero, cube_graph_alt.num_zeros_is_odd], unfold1 edges_map, simp [fin.zero, edges_map._match_1], dsimp [cube_graph, prism_graph, prism_graph.srctrg, nodes_map], refl, end | (n +2) b (sum.inr (⟨i +1, psi⟩, v)) := begin dsimp [cube_graph_alt, cube_graph_alt.srctrg], rw [fin.to_succ, vector.insert_nth_succ], unfold1 nodes_map, simp [vector.head, fin.succ], simp [cube_graph_alt.num_zeros_is_odd], symmetry, unfold1 edges_map, simp [edges_map._match_1], dsimp [cube_graph, prism_graph, prism_graph.srctrg], congr, transitivity (cube_graph tw (n +1)).srctrg (bxor (vector.head v && tw) b) (edges_map tw (n + 1) (sum.inr (⟨i, _⟩, vector.tail v))), refl, rw ←srctrg_map, dsimp [cube_graph_alt, cube_graph_alt.srctrg], simp, have : ∀ a b c, bxor (band a b) (band a c) = band a (bxor b c), { intros a b c, cases a, refl, simp,}, rw this, end end end cg'_to_cg def cg'_to_cg (tw : bool) (n : ℕ) : graph_cat.hom (cube_graph_alt tw n) (cube_graph tw n) := { nodes_map := cg'_to_cg.nodes_map tw n , edges_map := cg'_to_cg.edges_map tw n , srctrg_map := cg'_to_cg.srctrg_map tw n } section variable tw : bool lemma cg_cg'_cg_eq_id.nodes_map_eq : ∀ (n : ℕ) (v : (cube_graph tw n).nodes), cg'_to_cg.nodes_map tw n (cg_to_cg'.nodes_map tw n v) = v | 0 v := begin cases v, refl end | (n +1) (b, v) := begin simp [cg_to_cg'.nodes_map, cg'_to_cg.nodes_map], exact cg_cg'_cg_eq_id.nodes_map_eq n v end lemma cg'_cg_cg'_eq_id.nodes_map_eq : ∀ (n : ℕ)(v : (cube_graph_alt tw n).nodes), cg_to_cg'.nodes_map tw n (cg'_to_cg.nodes_map tw n v) = v | 0 v := begin change vector bool 0 at v, rw vector.eq_nil v, simp [cg'_to_cg.nodes_map, cg_to_cg'.nodes_map], end | (n +1) v := begin simp [cg'_to_cg.nodes_map, cg_to_cg'.nodes_map], rw cg'_cg_cg'_eq_id.nodes_map_eq, simp, end lemma cg_cg'_cg_eq_id.edges_map_eq : ∀ (n : ℕ) (e : (cube_graph tw n).edges), cg'_to_cg.edges_map tw n (cg_to_cg'.edges_map tw n e) = e | 0 e := begin cases e, refl end | (n +1) (sum.inl (b, e)) := begin transitivity sum.inl (b, cg'_to_cg.edges_map tw n (cg_to_cg'.edges_map tw n e)), swap, { congr, exact cg_cg'_cg_eq_id.edges_map_eq n e,}, set e' := cg_to_cg'.edges_map tw n e with ←e'_prop, unfold cg_to_cg'.edges_map, rcases cg_to_cg'.edges_map tw n e with ⟨v⟩ | ⟨i, v⟩, { intro e'_prop, unfold cg_to_cg'.edges_map._match_1, unfold cg'_to_cg.edges_map, rw [vector.head_cons, vector.tail_cons], congr, assumption,}, intro e'_prop, unfold cg_to_cg'.edges_map._match_1, cases n with n, {exact i.elim0,}, unfold cg_to_cg'.edges_map._match_2, cases i, unfold fin.succ, unfold1 cg'_to_cg.edges_map, unfold fin.maybe_pred_rec, congr, { unfold cg'_to_cg.edges_map._match_1, simp,}, simpa, end | (n +1) (sum.inr v) := begin simp [cg_to_cg'.edges_map, cg'_to_cg.edges_map, fin.zero], exact cg_cg'_cg_eq_id.nodes_map_eq tw n v, end lemma cg'_cg_cg'_eq_id.edges_map_eq (n : ℕ) (e : (cube_graph_alt tw n).edges) : cg_to_cg'.edges_map tw n (cg'_to_cg.edges_map tw n e) = e := begin induction n with n IH, { dsimp [cg'_to_cg.edges_map, cg_to_cg'.edges_map], rcases e with ⟨⟩ | ⟨i, v⟩, {congr,}, exact i.elim0,}, rcases e with ⟨v⟩ | ⟨i, v⟩, { rcases v with ⟨bl, p⟩, rcases bl with ⟨⟩ | ⟨b, l⟩, {contradiction,}, dsimp [cg'_to_cg.edges_map, vector.head, vector.tail, cg_to_cg'.edges_map], rw IH, unfold cg_to_cg'.edges_map._match_1, refl,}, cases i, rcases i_val with ⟨⟩ | ⟨i'_val⟩, { dsimp [cg'_to_cg.edges_map, fin.maybe_pred_rec, cg_to_cg'.edges_map], congr, apply cg'_cg_cg'_eq_id.nodes_map_eq,}, cases n, { exfalso, exact nat.not_succ_le_zero i'_val (nat.le_of_lt_succ i_is_lt)}, rcases v with ⟨bl, p⟩, rcases bl with ⟨⟩ | ⟨b, l⟩, {contradiction,}, unfold1 cg'_to_cg.edges_map, unfold1 cg'_to_cg.edges_map._match_1, unfold1 fin.maybe_pred_rec, simp [vector.head, vector.tail, cg_to_cg'.edges_map], rw IH, simp [cg_to_cg'.edges_map._match_1, cg_to_cg'.edges_map._match_2], split, {refl,}, refl, end lemma cg_cg'_cg_eq_id (n : ℕ) : graph_cat.comp (cg_to_cg' tw n) (cg'_to_cg tw n) = graph_cat.id (cube_graph tw n) := graph_cat.hom.eq (funext (cg_cg'_cg_eq_id.nodes_map_eq tw n)) (funext (cg_cg'_cg_eq_id.edges_map_eq tw n)) lemma cg'_cg_cg'_eq_id (n : ℕ) : graph_cat.comp (cg'_to_cg tw n) (cg_to_cg' tw n) = graph_cat.id (cube_graph_alt tw n) := graph_cat.hom.eq (funext (cg'_cg_cg'_eq_id.nodes_map_eq tw n)) (funext (cg'_cg_cg'_eq_id.edges_map_eq tw n)) def cg_iso_cg' (n : ℕ) : graph_cat.iso (cube_graph tw n) (cube_graph_alt tw n) := { dir := cg_to_cg' tw n , inv := cg'_to_cg tw n , dir_inv := cg_cg'_cg_eq_id tw n , inv_dir := cg'_cg_cg'_eq_id tw n } def cube_graph_cat : category := { obj := ℕ , hom := λ m n, graph_cat.hom (cube_graph tw m) (cube_graph tw n) , id := λ n, graph_cat.id (cube_graph tw n) , comp := λ {n n' n''}, @graph_cat.comp (cube_graph tw n) (cube_graph tw n') (cube_graph tw n'') , id_l := λ {m n}, @graph_cat.id_l (cube_graph tw m) (cube_graph tw n) , id_r := λ {m n}, @graph_cat.id_r (cube_graph tw m) (cube_graph tw n) , assoc := λ {n n' n'' n'''}, @graph_cat.assoc (cube_graph tw n) (cube_graph tw n') (cube_graph tw n'') (cube_graph tw n''') } end
9ed5d7f0a5fab8e519a7e73a6a7d3875a68ace58
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/final/imp.lean
caeef0e3215083e71f7d127a5e678132120f8441
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
3,005
lean
import .arith_expr import .bool_expr /- Syntax of our little language (OLL). OLL supports mutable variables and values of types arithmetic (bool) and arithmetic (nat). It has an assignment command for each of these two types. It also supports sequential composition of smaller programs into larger ones. -/ inductive cmd : Type | skip | a_assn (v : var nat) (e : arith_expr) | b_assn (v : var bool) (e : bool_expr) | seq (c1 c2 : cmd) : cmd | ifelse (b : bool_expr) (c1 c2 : cmd) | while (b : bool_expr) (c : cmd) open cmd notation v = e := b_assn v e notation v = a := a_assn v a notation c1 ; c2 := seq c1 c2 notation `IF ` b ` THEN ` c1 ` ELSE ` c2 := ifelse b c1 c2 notation `WHILE ` b ` DO ` c ` END`:= while b c /- Computational semantics -/ meta def c_eval : cmd → env → env | skip st := st | (b_assn v e) st := override_bool st v e | (a_assn v e) st := override_nat st v e | (c1 ; c2) st := c_eval c2 (c_eval c1 st) | (IF b THEN c1 ELSE c2) st := if (bool_eval b st) then c_eval c1 st else c_eval c2 st | (WHILE b DO c END) st := if (bool_eval b st) then c_eval (c; WHILE b DO c END) st else st /- -- run c; repeat loop. -- Unroll loop by one run of c -- Running c can but needn't make b false -- side effects via big shared memory (BSM) -/ /- Logical semantics The rules are the axioms you can then use to prove c_sem relations. -/ inductive c_sem : cmd → env → env → Prop -- c_sem skip pre pre | c_sem_skip : ∀ (st : env), c_sem skip st st -- c_sem (v =a e) pre post -- arith assignment | c_sem_arith_assn : ∀ (pre post : env) (v : var nat) (e : arith_expr), (override_nat pre v e = post) → c_sem (a_assn v e) pre post -- c_sem (v =b e) pre post -- bool assignment | c_sem_bool_assn : ∀ (pre post : env) (v : var bool) (e : bool_expr), (override_bool pre v e = post) → c_sem (b_assn v e) pre post -- c_sem (c1 ; c2) pre post | c_sem_seq : ∀ (pre is post : env) (c1 c2 : cmd), c_sem c1 pre is → c_sem c2 is post → c_sem (c1 ; c2) pre post -- c_sem if false c1 c2 | c_sem_if_false : ∀ (pre is post : env) (b : bool_expr) (c1 c2 : cmd), bool_eval b pre = ff → c_sem c2 pre post → c_sem (IF b THEN c1 ELSE c2) pre post -- c_sem if true c1 c2 | c_sem_if_true : ∀ (pre is post : env) (b : bool_expr) (c1 c2 : cmd), bool_eval b pre = tt → c_sem c1 pre post → c_sem (IF b THEN c1 ELSE c2) pre post -- c_sem (while false do c) pre post | c_sem_while_false : ∀ (pre : env) (b : bool_expr) (c : cmd), bool_eval b pre = ff → c_sem (WHILE b DO c END) pre pre -- c_sem (while true do c) pre post | c_sem_while_true : ∀ (pre is post : env) (b : bool_expr) (c : cmd), bool_eval b pre = tt → c_sem c pre is → -- one iteration of c: pre->is c_sem (WHILE b DO c END) is post → c_sem (WHILE b DO c END) pre post
919c70ca6a77e2a2eb7d02c59210c1b948e41034
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/valuation/basic.lean
c2e61a27fa121806a7dd9b0a568babe8cb72c60b
[ "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
14,493
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Johan Commelin, Patrick Massot -/ import algebra.linear_ordered_comm_group_with_zero import algebra.group_power import ring_theory.ideal_operations import ring_theory.subring import algebra.punit_instances /-! # The basics of valuation theory. The basic theory of valuations (non-archimedean norms) on a commutative ring, following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]). The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic]. A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered commutative group with zero, that in addition satisfies the following two axioms: * `v 0 = 0` * `∀ x y, v (x + y) ≤ max (v x) (v y)` `valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying function. If `v` is a valuation from `R` to `Γ₀` then the induced group homomorphism `units(R) → Γ₀` is called `unit_map v`. The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might not have the same type. This corresponds in ZFC to the set-theoretic difficulty that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set. The "relation" is however reflexive, symmetric and transitive in the obvious sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence. The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R` with `h : J ⊆ supp v` then the induced valuation on R / J = `ideal.quotient J` is `on_quot v h`. ## Main definitions * `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀` * `valuation.is_equiv`, the heterogeneous equivalence relation on valuations * `valuation.supp`, the support of a valuation -/ open_locale classical noncomputable theory local attribute [instance, priority 0] classical.DLO open function ideal -- universes u u₀ u₁ u₂ -- v is used for valuations variables {R : Type*} -- This will be a ring, assumed commutative in some sections variables {Γ₀ : Type*} [linear_ordered_comm_group_with_zero Γ₀] variables {Γ'₀ : Type*} [linear_ordered_comm_group_with_zero Γ'₀] variables {Γ''₀ : Type*} [linear_ordered_comm_group_with_zero Γ''₀] set_option old_structure_cmd true section variables (R) (Γ₀) [ring R] /-- The type of Γ₀-valued valuations on R. -/ @[nolint has_inhabited_instance] structure valuation extends R →* Γ₀ := (map_zero' : to_fun 0 = 0) (map_add' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y)) run_cmd tactic.add_doc_string `valuation.to_monoid_hom "The `monoid_hom` underlying a valuation." end namespace valuation section basic variables (R) (Γ₀) [ring R] /-- A valuation is coerced to the underlying function R → Γ₀. -/ instance : has_coe_to_fun (valuation R Γ₀) := { F := λ _, R → Γ₀, coe := valuation.to_fun } /-- A valuation is coerced to a monoid morphism R → Γ₀. -/ instance : has_coe (valuation R Γ₀) (R →* Γ₀) := ⟨valuation.to_monoid_hom⟩ variables {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp, norm_cast] lemma coe_coe : ((v : R →* Γ₀) : R → Γ₀) = v := rfl @[simp] lemma map_zero : v 0 = 0 := v.map_zero' @[simp] lemma map_one : v 1 = 1 := v.map_one' @[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul' @[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add' @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n := v.to_monoid_hom.map_pow @[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := by { cases v₁, cases v₂, congr, funext r, exact h r } lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := ⟨λ h r, congr_arg _ h, ext⟩ -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/ @[simp] lemma zero_iff {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 := begin split ; intro h, { contrapose! h, exact ((is_unit.mk0 _ h).map (v : K →* Γ₀)).ne_zero }, { exact h.symm ▸ v.map_zero }, end lemma ne_zero_iff {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 := not_iff_not_of_iff v.zero_iff @[simp] lemma map_inv {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ := begin by_cases h : x = 0, { subst h, rw [inv_zero, v.map_zero, inv_zero] }, { apply eq_inv_of_mul_right_eq_one, rw [← v.map_mul, mul_inv_cancel h, v.map_one] } end lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = (v x)⁻¹ := eq_inv_of_mul_right_eq_one $ by rw [← v.map_mul, units.mul_inv, v.map_one] @[simp] theorem unit_map_eq (u : units R) : (units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl theorem map_neg_one : v (-1) = 1 := begin apply eq_one_of_pow_eq_one (nat.succ_ne_zero 1) (_ : _ ^ 2 = _), rw [pow_two, ← v.map_mul, neg_one_mul, neg_neg, v.map_one], end @[simp] lemma map_neg (x : R) : v (-x) = v x := calc v (-x) = v (-1 * x) : by rw [neg_one_mul] ... = v (-1) * v x : map_mul _ _ _ ... = v x : by rw [v.map_neg_one, one_mul] lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := calc v (x - y) = v (-(y - x)) : by rw show x - y = -(y-x), by abel ... = _ : map_neg _ _ lemma map_sub_le_max (x y : R) : v (x - y) ≤ max (v x) (v y) := calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg] ... ≤ max (v x) (v $ -y) : v.map_add _ _ ... = max (v x) (v y) : by rw map_neg lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) := begin suffices : ¬v (x + y) < max (v x) (v y), from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this, intro h', wlog vyx : v y < v x using x y, { apply lt_or_gt_of_ne h.symm }, { rw max_eq_left_of_lt vyx at h', apply lt_irrefl (v x), calc v x = v ((x+y) - y) : by simp ... ≤ max (v $ x + y) (v y) : map_sub_le_max _ _ _ ... < v x : max_lt h' vyx }, { apply this h.symm, rwa [add_comm, max_comm] at h' } end lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x := begin have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm, rw max_eq_right (le_of_lt h) at this, simpa using this end /-- A ring homomorphism S → R induces a map valuation R Γ₀ → valuation S Γ₀ -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) : valuation S Γ₀ := by refine_struct { to_fun := v ∘ f, .. }; intros; simp only [comp_app, map_one, map_mul, map_zero, map_add, f.map_one, f.map_mul, f.map_zero, f.map_add] @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := ext $ λ r, rfl /-- A ≤-preserving group homomorphism Γ₀ → Γ'₀ induces a map valuation R Γ₀ → valuation R Γ'₀. -/ def map (f : Γ₀ →* Γ'₀) (h₀ : f 0 = 0) (hf : monotone f) (v : valuation R Γ₀) : valuation R Γ'₀ := { to_fun := f ∘ v, map_zero' := show f (v 0) = 0, by rw [v.map_zero, h₀], map_add' := λ r s, calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s) ... = max (f (v r)) (f (v s)) : hf.map_max, .. monoid_hom.comp f (v : R →* Γ₀) } /-- Two valuations on R are defined to be equivalent if they induce the same preorder on R. -/ def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop := ∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s end basic -- end of section namespace is_equiv variables [ring R] variables {v : valuation R Γ₀} variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := λ _ _, iff.refl _ @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := λ _ _, iff.symm (h _ _) @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _) lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' := by { subst h } lemma map {v' : valuation R Γ₀} (f : Γ₀ →* Γ'₀) (h₀ : f 0 = 0) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f h₀ hf).is_equiv (v'.map f h₀ hf) := let H : strict_mono f := strict_mono_of_monotone_of_injective hf inf in λ r s, calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le ... ↔ v' r ≤ v' s : h r s ... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := λ r s, h (f r) (f s) lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r) lemma ne_zero (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ 0 ↔ v₂ r ≠ 0 := begin have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq, rwa [v₁.map_zero, v₂.map_zero] at this, end end is_equiv -- end of namespace lemma is_equiv_of_map_strict_mono [ring R] {v : valuation R Γ₀} (f : Γ₀ →* Γ'₀) (h₀ : f 0 = 0) (H : strict_mono f) : is_equiv (v.map f h₀ (H.monotone)) v := λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩ lemma is_equiv_of_val_le_one {K : Type*} [division_ring K] (v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) : v.is_equiv v' := begin intros x y, by_cases hy : y = 0, { simp [hy, zero_iff], }, rw show y = 1 * y, by rw one_mul, rw [← (inv_mul_cancel_right' hy x)], iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]}, rw [v.map_one, v'.map_one], split; intro H, { apply mul_le_mul_right', replace hy := v.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h at H, }, { apply mul_le_mul_right', replace hy := v'.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h, }, end section supp variables [comm_ring R] variables (v : valuation R Γ₀) /-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/ def supp : ideal R := { carrier := {x | v x = 0}, zero_mem' := map_zero v, add_mem' := λ x y hx hy, le_zero_iff.mp $ calc v (x + y) ≤ max (v x) (v y) : v.map_add x y ... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy), smul_mem' := λ c x hx, calc v (c * x) = v c * v x : map_mul v c x ... = v c * 0 : congr_arg _ hx ... = 0 : mul_zero _ } @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl -- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl /-- The support of a valuation is a prime ideal. -/ instance : ideal.is_prime (supp v) := ⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0, from calc 1 = v 1 : v.map_one.symm ... = 0 : show (1:R) ∈ supp v, by { rw h, trivial }, λ x y hxy, begin show v x = 0 ∨ v y = 0, change v (x * y) = 0 at hxy, rw [v.map_mul x y] at hxy, exact eq_zero_or_eq_zero_of_mul_eq_zero hxy end⟩ lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := begin have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a, { intros a' s' h', refine le_trans (v.map_add a' s') (max_le (le_refl _) _), simp [h'], }, apply le_antisymm (aux a s h), calc v a = v (a + s + -s) : by simp ... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h) end /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := λ q, quotient.lift_on' q v $ λ a b h, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : valuation J.quotient Γ₀ := { to_fun := v.on_quot_val hJ, map_zero' := v.map_zero, map_one' := v.map_one, map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar, map_add' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar } @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := ext $ λ r, begin refine @quotient.lift_on_beta _ _ (J.quotient_rel) v (λ a b h, _) _, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) end lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := ideal.ext $ λ x, begin rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff], refl, end lemma self_le_supp_comap (J : ideal R) (v : valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp } @[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := ext $ by { rintro ⟨x⟩, refl } /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := begin apply le_antisymm, { rintro ⟨x⟩ hx, apply ideal.subset_span, exact ⟨x, hx, rfl⟩ }, { rw ideal.map_le_iff_le_comap, intros x hx, exact hx } end lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := by { rw supp_quot, exact ideal.map_quotient_self _ } end supp -- end of section end valuation
205a813e7dbdc48022fa2e25a7d4c4c47adaf22e
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/group_power/lemmas.lean
34d7bfe326083946cd2e0e82c14044f41710ebd6
[ "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
32,819
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.group_power.basic import algebra.invertible import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import data.equiv.mul_add import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n • (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { rw pow_zero, refl }, { rw [list.repeat_succ, list.prod_cons, ih, pow_succ] } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative A) _ @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n instance invertible_pow (m : M) [invertible m] (n : ℕ) : invertible (m ^ n) := { inv_of := ⅟ m ^ n, inv_of_mul_self := by rw [← (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow], mul_inv_of_self := by rw [← (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] } lemma inv_of_pow (m : M) [invertible m] (n : ℕ) [invertible (m ^ n)] : ⅟(m ^ n) = ⅟m ^ n := @invertible_unique M _ (m ^ n) (m ^ n) rfl ‹_› (invertible_pow m n) lemma is_unit.pow {m : M} (n : ℕ) : is_unit m → is_unit (m ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ /-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/ def invertible_of_pow_succ_eq_one (x : M) (n : ℕ) (hx : x ^ n.succ = 1) : invertible x := ⟨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hx⟩ /-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/ def invertible_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : invertible x := begin apply invertible_of_pow_succ_eq_one x (n - 1), convert hx, exact nat.sub_add_cancel (nat.succ_le_of_lt hn), end lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin haveI := invertible_of_pow_eq_one x n hx hn, exact is_unit_of_invertible x end end monoid theorem nat.nsmul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem gsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n := by cases n; simp lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) • a = i • a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) • a = m • a - n • a := by simpa only [sub_eq_add_neg] using @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) • a = a + i • a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j : ℤ), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), (m * n) • a = n • (m • a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem mul_gsmul (a : A) (m n : ℤ) : (m * n) • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n • a = n • a + n • a := @gpow_bit0 (multiplicative A) _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add, gpow_bit0, gpow_one] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative A) _ @[simp] theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; simp @[simp] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n • a) = n • f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.order` with their friends) because they require facts from `data.int.basic`-/ open int lemma gsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k • a := begin lift k to ℕ using int.le_of_lt hk, rw gsmul_coe_nat, apply nsmul_pos ha, exact coe_nat_pos.mp hk, end theorem gsmul_le_gsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + (m - n) • a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m • a : by { rw [← add_gsmul], simp } theorem gsmul_lt_gsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n • a < m • a := calc n • a = n • a + 0 : (add_zero _).symm ... < n • a + (m - n) • a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _ ... = m • a : by { rw [← add_gsmul], simp } lemma abs_nsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℕ) (a : α) : abs (n • a) = n • abs a := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_gsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℤ) (a : α) : abs (n • a) = (abs n) • abs a := begin by_cases n0 : 0 ≤ n, { lift n to ℕ using n0, simp only [abs_nsmul, coe_nat_abs, gsmul_coe_nat] }, { lift (- n) to ℕ using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h, rw [← abs_neg (n • a), ← neg_gsmul, ← abs_neg n, ← h, gsmul_coe_nat, coe_nat_abs, gsmul_coe_nat], exact abs_nsmul m _ }, end lemma abs_add_eq_add_abs_le {α : Type*} [linear_ordered_add_comm_group α] {a b : α} (hle : a ≤ b) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases a0 : 0 ≤ a; by_cases b0 : 0 ≤ b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : α) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim }, any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] }, obtain F := (not_le.mp a0), have : (abs (a + b) = -a + b ↔ b ≤ 0) ↔ (abs (a + b) = abs a + abs b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0), { simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] }, refine this.mp ⟨λ h, _, λ h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]⟩, by_cases ba : a + b ≤ 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : α) _).elim, rw [abs_of_pos (not_le.mp ba), add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at F } end lemma abs_add_eq_add_abs_iff {α : Type*} [linear_ordered_add_comm_group α] (a b : α) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases ab : a ≤ b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm, @and.comm (b ≤ 0 ) _] } end end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem gsmul_le_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n • a ≤ m • a ↔ n ≤ m := begin refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h) end theorem gsmul_lt_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n • a < m • a ↔ n < m := begin refine ⟨λ h, _, gsmul_lt_gsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h) end theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n • a ≤ m • a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n • a < m • a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((n • a : A) : with_bot A) = n • a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n • a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n • (a * b) = n • a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero], exact nat.cast_one }, { rw [pow_succ', pow_succ', nat.cast_mul, ih] } end @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = (2 : ℤ) • (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = (2 : ℤ) • (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = (2 : ℤ) • (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = (2 : ℤ) • (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ (n : ℤ), n • a = n * a | (n : ℕ) := by { rw [gsmul_coe_nat, nsmul_eq_mul], refl } | -[1+ n] := by simp [nat.cast_succ, neg_add_rev, int.cast_neg_succ_of_nat, add_mul] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n • a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n • (a * b) = a * (n • b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n • (a * b) = n • a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] lemma gsmul_int_int (a b : ℤ) : a • b = a * b := by simp lemma gsmul_int_one (n : ℤ) : n • 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero, int.cast_one] }, { rw [pow_succ, pow_succ, int.cast_mul, ih] } end lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [sq] section ordered_semiring variable [ordered_semiring R] /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' {a : R} (Hsq : 0 ≤ a * a) (Hsq' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsq H)) Hsq, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsq' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin rw [←one_mul (a^i), add_zero, pow_succ], exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw [←one_mul (a^i), pow_succ], apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by { rw [←add_assoc, ←one_mul (a^i), pow_succ], exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one } lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_lt_pow_iff_of_lt_one {a : R} {n m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := by rw [pow_zero] | (n+1) h0 h1 := by { rw [pow_succ], exact mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) } end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : ℕ} @[simp] lemma abs_pow (a : R) (n : ℕ) : abs (a ^ n) = abs a ^ n := (pow_abs a n).symm @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ h, by { rw [bit1, pow_succ], exact mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)}⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff theorem pow_even_nonneg (a : R) (hn : even n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k theorem pow_even_pos (ha : a ≠ 0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k theorem pow_odd_nonneg (ha : 0 ≤ a) (hn : odd n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonneg_iff.mpr ha theorem pow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_pos_iff.mpr ha theorem pow_odd_nonpos (ha : a ≤ 0) (hn : odd n) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha theorem pow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma pow_even_abs (a : R) {p : ℕ} (hp : even p) : abs a ^ p = a ^ p := begin rw [←abs_pow, abs_eq_self], exact pow_even_nonneg _ hp end @[simp] lemma pow_bit0_abs (a : R) (p : ℕ) : abs a ^ bit0 p = a ^ bit0 p := pow_even_abs _ (even_bit0 _) lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_sq (u : units ℤ) : u ^ 2 = 1 := (sq u).symm ▸ units_mul_self u alias int.units_sq ← int.units_pow_two lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_sq, one_pow, mul_one] @[simp] lemma nat_abs_sq (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [sq, int.nat_abs_mul_self', sq] alias int.nat_abs_sq ← int.nat_abs_pow_two lemma abs_le_self_sq (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_sq a, sq], norm_cast, apply nat.le_mul_self } alias int.abs_le_self_sq ← int.abs_le_self_pow_two lemma le_self_sq (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_sq _) alias int.le_self_sq ← int.le_self_pow_two end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, by { convert pow_zero x, exact to_add_one }, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : gpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n • x := rfl @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : gmultiples_hom A x n = n • x := rfl @[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (gmultiples_hom A).symm f = f 1 := rfl lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← gpowers_hom_symm_apply, ← gpowers_hom_apply, equiv.apply_symm_apply] /-! `monoid_hom.ext_mint` is defined in `data.int.cast` -/ lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n • (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n • (f 1) := by rw [← gmultiples_hom_symm_apply, ← gmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/ def gpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_gpow], ..gpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/ def gmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [gsmul_add], ..gmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : gpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n • x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : gmultiples_add_hom A x n = n • x := rfl @[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (gmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
1471d6c20d8f1803536121adc5094005a7e6e2e7
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/tools/super/clause.lean
a7180232884c910c0f1725cefa8f59685a612501
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
8,662
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import init.meta.tactic .utils .trim open expr list tactic monad decidable namespace super meta def is_local_not (local_false : expr) (e : expr) : option expr := match e with | (pi _ _ a b) := if b = local_false then some a else none | _ := if local_false = ```(false) then is_not e else none end meta structure clause := (num_quants : ℕ) (num_lits : ℕ) (proof : expr) (type : expr) (local_false : expr) namespace clause meta def num_binders (c : clause) : ℕ := num_quants c + num_lits c meta def inst (c : clause) (e : expr) : clause := (if num_quants c > 0 then mk (num_quants c - 1) (num_lits c) else mk 0 (num_lits c - 1)) (app (proof c) e) (instantiate_var (binding_body (type c)) e) c.local_false meta def instn (c : clause) (es : list expr) : clause := foldr (λe c', inst c' e) c es meta def open_const (c : clause) : tactic (clause × expr) := do n ← mk_fresh_name, b ← return $ local_const n (binding_name (type c)) (binding_info (type c)) (binding_domain (type c)), return (inst c b, b) meta def open_meta (c : clause) : tactic (clause × expr) := do b ← mk_meta_var (binding_domain (type c)), return (inst c b, b) meta def close_const (c : clause) (e : expr) : clause := match e with | local_const uniq pp info t := let abst_type' := abstract_local (type c) (local_uniq_name e) in let type' := pi pp binder_info.default t (abstract_local (type c) uniq) in let abs_prf := abstract_local (proof c) uniq in let proof' := lambdas [e] c.proof in if num_quants c > 0 ∨ has_var abst_type' then { c with num_quants := c.num_quants + 1, proof := proof', type := type' } else { c with num_lits := c.num_lits + 1, proof := proof', type := type' } | _ := ⟨0, 0, default expr, default expr, default expr⟩ end meta def open_constn : clause → ℕ → tactic (clause × list expr) | c 0 := return (c, nil) | c (n+1) := do (c', b) ← open_const c, (c'', bs) ← open_constn c' n, return (c'', b::bs) meta def open_metan : clause → ℕ → tactic (clause × list expr) | c 0 := return (c, nil) | c (n+1) := do (c', b) ← open_meta c, (c'', bs) ← open_metan c' n, return (c'', b::bs) meta def close_constn : clause → list expr → clause | c [] := c | c (b::bs') := close_const (close_constn c bs') b private meta def parse_clause (local_false : expr) : expr → expr → tactic clause | proof (pi n bi d b) := do lc_n ← mk_fresh_name, lc ← return $ local_const lc_n n bi d, c ← parse_clause (app proof lc) (instantiate_var b lc), return $ c.close_const $ local_const lc_n n binder_info.default d | proof ```(not %%formula) := parse_clause proof ```(%%formula → false) | proof type := if type = local_false then do return { num_quants := 0, num_lits := 0, proof := proof, type := type, local_false := local_false } else do univ ← infer_univ type, not_type ← return $ imp type local_false, parse_clause (lam `H binder_info.default not_type $ app (mk_var 0) proof) (imp not_type local_false) meta def of_proof_and_type (local_false proof type : expr) : tactic clause := parse_clause local_false proof type meta def of_proof (local_false proof : expr) : tactic clause := do type ← infer_type proof, of_proof_and_type local_false proof type meta def of_classical_proof (proof : expr) : tactic clause := of_proof ```(false) proof meta def inst_mvars (c : clause) : tactic clause := do proof' ← instantiate_mvars (proof c), type' ← instantiate_mvars (type c), return { c with proof := proof', type := type' } meta inductive literal | left : expr → literal | right : expr → literal namespace literal meta instance : decidable_eq literal := by mk_dec_eq_instance meta def formula : literal → expr | (left f) := f | (right f) := f meta def is_neg : literal → bool | (left _) := tt | (right _) := ff meta def is_pos (l : literal) : bool := bnot l.is_neg meta def to_formula (l : literal) : expr := if l.is_neg then app (const ``not []) l.formula else formula l meta def type_str : literal → string | (literal.left _) := "left" | (literal.right _) := "right" meta instance : has_to_tactic_format literal := ⟨λl, do pp_f ← pp l.formula, return $ to_fmt l.type_str ++ " (" ++ pp_f ++ ")"⟩ end literal private meta def get_binding_body : expr → ℕ → expr | e 0 := e | e (i+1) := get_binding_body e.binding_body i meta def get_binder (e : expr) (i : nat) := binding_domain (get_binding_body e i) meta def validate (c : clause) : tactic unit := do concl ← return $ get_binding_body c.type c.num_binders, unify concl c.local_false <|> (do pp_concl ← pp concl, pp_lf ← pp c.local_false, fail $ to_fmt "wrong local false: " ++ pp_concl ++ " =!= " ++ pp_lf), type' ← infer_type c.proof, unify c.type type' <|> (do pp_ty ← pp c.type, pp_ty' ← pp type', fail (to_fmt "wrong type: " ++ pp_ty ++ " =!= " ++ pp_ty')) meta def get_lit (c : clause) (i : nat) : literal := let bind := get_binder (type c) (num_quants c + i) in match is_local_not c.local_false bind with | some formula := literal.right formula | none := literal.left bind end meta def lits_where (c : clause) (p : literal → bool) : list nat := list.filter (λl, p (get_lit c l)) (range (num_lits c)) meta def get_lits (c : clause) : list literal := list.map (get_lit c) (range c.num_lits) private meta def tactic_format (c : clause) : tactic format := do c ← c.open_metan c.num_quants, pp (do l ← c.1.get_lits, [l.to_formula]) meta instance : has_to_tactic_format clause := ⟨tactic_format⟩ meta def is_maximal (gt : expr → expr → bool) (c : clause) (i : nat) : bool := list.empty (list.filter (λj, gt (get_lit c j).formula (get_lit c i).formula) (range c.num_lits)) meta def normalize (c : clause) : tactic clause := do opened ← open_constn c (num_binders c), lconsts_in_types ← return $ contained_lconsts_list (list.map local_type opened.2), quants' ← return $ list.filter (λlc, rb_map.contains lconsts_in_types (local_uniq_name lc)) opened.2, lits' ← return $ list.filter (λlc, ¬rb_map.contains lconsts_in_types (local_uniq_name lc)) opened.2, return $ close_constn opened.1 (quants' ++ lits') meta def whnf_head_lit (c : clause) : tactic clause := do atom' ← whnf $ literal.formula $ get_lit c 0, return $ if literal.is_neg (get_lit c 0) then { c with type := ```(%%atom' → %%(binding_body c.type)) } else { c with type := ```(not %%atom' → %%(c.type.binding_body)) } end clause meta def unify_lit (l1 l2 : clause.literal) : tactic unit := if clause.literal.is_pos l1 = clause.literal.is_pos l2 then unify (clause.literal.formula l1) (clause.literal.formula l2) transparency.none else fail "cannot unify literals" -- FIXME: this is most definitely broken with meta-variables that were already in the goal meta def sort_and_constify_metas : list expr → tactic (list expr) | exprs_with_metas := do inst_exprs ← mapm instantiate_mvars exprs_with_metas, metas ← return $ inst_exprs >>= get_metas, match list.filter (λm, ¬has_meta_var (get_meta_type m)) metas with | [] := if metas.empty then return [] else do for' metas (λm, do trace (expr.to_string m), t ← infer_type m, trace (expr.to_string t)), fail "could not sort metas" | ((mvar n t) :: _) := do c ← infer_type (mvar n t) >>= mk_local_def `x, unify c (mvar n t), rest ← sort_and_constify_metas metas, c ← instantiate_mvars c, return ([c] ++ rest) | _ := failed end namespace clause meta def meta_closure (metas : list expr) (qf : clause) : tactic clause := do bs ← sort_and_constify_metas metas, qf' ← clause.inst_mvars qf, clause.inst_mvars $ clause.close_constn qf' bs private meta def distinct' (local_false : expr) : list expr → expr → clause | [] proof := ⟨ 0, 0, proof, local_false, local_false ⟩ | (h::hs) proof := let (dups, rest) := partition (λh' : expr, h.local_type = h'.local_type) hs, proof_wo_dups := foldl (λproof (h' : expr), instantiate_var (abstract_local proof h'.local_uniq_name) h) proof dups in (distinct' rest proof_wo_dups).close_const h meta def distinct (c : clause) : tactic clause := do (qf, vs) ← c.open_constn c.num_quants, (fls, hs) ← qf.open_constn qf.num_lits, return $ (distinct' c.local_false hs fls.proof).close_constn vs end clause end super
a79ff831cf3a672e62fdb388d9b148f0edb7f753
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/eq3.lean
a8c4741ae415676ca3d529047742f048a8ff7109
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
199
lean
import heq variable Vector : Nat -> Type variable n : Nat variable v1 : Vector n variable v2 : Vector (n + 0) variable v3 : Vector (0 + n) axiom H1 : v1 == v2 axiom H2 : v2 == v3 check htrans H1 H2
bc4f924e5b06c12cccd9664de641f7b430578c0f
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/number_theory/arithmetic_function.lean
0019a5e08fb337dd6ef6ff1226c05d5bfe2a7db9
[ "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
32,509
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.ring import number_theory.divisors import algebra.squarefree import algebra.invertible /-! # Arithmetic Functions and Dirichlet Convolution This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition, to form the Dirichlet ring. ## Main Definitions * `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`. * An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`. * The pointwise operations `pmul` and `ppow` differ from the multiplication and power instances on `arithmetic_function R`, which use Dirichlet multiplication. * `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`. * `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`. * `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`. * `id` is the identity arithmetic function on `ℕ`. * `ω n` is the number of distinct prime factors of `n`. * `Ω n` is the number of prime factors of `n` counted with multiplicity. * `μ` is the Möbius function. ## Main Results * Several forms of Möbius inversion: * `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring` * `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group` * `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group` * `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero` ## Notation The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in the namespace `arithmetic_function`. ## Tags arithmetic functions, dirichlet convolution, divisors -/ open finset open_locale big_operators namespace nat variable (R : Type*) /-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by Dirichlet convolution. -/ @[derive [has_coe_to_fun, has_zero, inhabited]] def arithmetic_function [has_zero R] := zero_hom ℕ R variable {R} namespace arithmetic_function section has_zero variable [has_zero R] @[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl @[simp] lemma map_zero {f : arithmetic_function R} : f 0 = 0 := zero_hom.map_zero' f theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g := ⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩ @[simp] lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 := zero_hom.zero_apply x @[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g := zero_hom.ext h theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x := zero_hom.ext_iff section has_one variable [has_one R] instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩ @[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl @[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h end has_one end has_zero instance nat_coe [has_zero R] [has_one R] [has_add R] : has_coe (arithmetic_function ℕ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma nat_coe_nat (f : arithmetic_function ℕ) : (↑f : arithmetic_function ℕ) = f := ext $ λ _, cast_id _ @[simp] lemma nat_coe_apply [has_zero R] [has_one R] [has_add R] {f : arithmetic_function ℕ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl instance int_coe [has_zero R] [has_one R] [has_add R] [has_neg R] : has_coe (arithmetic_function ℤ) (arithmetic_function R) := ⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩ @[simp] lemma int_coe_int (f : arithmetic_function ℤ) : (↑f : arithmetic_function ℤ) = f := ext $ λ _, int.cast_id _ @[simp] lemma int_coe_apply [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℤ} {x : ℕ} : (f : arithmetic_function R) x = f x := rfl @[simp] lemma coe_coe [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℕ} : ((f : arithmetic_function ℤ) : arithmetic_function R) = f := by { ext, simp, } section add_monoid variable [add_monoid R] instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩ @[simp] lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl instance : add_monoid (arithmetic_function R) := { add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _), zero_add := λ _, ext (λ _, zero_add _), add_zero := λ _, ext (λ _, add_zero _), .. arithmetic_function.has_zero R, .. arithmetic_function.has_add } end add_monoid instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) := { add_comm := λ _ _, ext (λ _, add_comm _ _), .. arithmetic_function.add_monoid } instance [add_group R] : add_group (arithmetic_function R) := { neg := λ f, ⟨λ n, - f n, by simp⟩, add_left_neg := λ _, ext (λ _, add_left_neg _), .. arithmetic_function.add_monoid } instance [add_comm_group R] : add_comm_group (arithmetic_function R) := { .. arithmetic_function.add_comm_monoid, .. arithmetic_function.add_group } section has_scalar variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M] /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance : has_scalar (arithmetic_function R) (arithmetic_function M) := ⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩ @[simp] lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} : (f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl end has_scalar /-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/ instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩ @[simp] lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} : (f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl section module variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M] lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) : (f * g) • h = f • g • h := begin ext n, simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'], apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩, refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨i0.2, n0.2⟩, }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_divisors_antidiagonal, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, rintros rfl h2 rfl rfl, exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩, { simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢, rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩, refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩, rw mul_ne_zero_iff at *, exact ⟨n0.1, j0.1⟩ }, { simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true, ne.def, mem_sigma, heq_iff_eq] at H ⊢, rw H.2.1 } } end lemma one_smul' (b : arithmetic_function M) : (1 : arithmetic_function R) • b = b := begin ext, rw smul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y1ne : y.fst ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y1ne], end end module section semiring variable [semiring R] instance : monoid (arithmetic_function R) := { one_mul := one_smul', mul_one := λ f, begin ext, rw mul_apply, by_cases x0 : x = 0, {simp [x0]}, have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0], rw ← sum_subset h, {simp}, intros y ymem ynmem, have y2ne : y.snd ≠ 1, { intro con, simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem, simp only [mem_singleton, prod.ext_iff] at ynmem, tauto }, simp [y2ne], end, mul_assoc := mul_smul', .. arithmetic_function.has_one, .. arithmetic_function.has_mul } instance : semiring (arithmetic_function R) := { zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] }, mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] }, left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] }, right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] }, .. arithmetic_function.has_zero R, .. arithmetic_function.has_mul, .. arithmetic_function.has_add, .. arithmetic_function.add_comm_monoid, .. arithmetic_function.monoid } end semiring instance [comm_semiring R] : comm_semiring (arithmetic_function R) := { mul_comm := λ f g, by { ext, rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map], simp [mul_comm] }, .. arithmetic_function.semiring } instance [comm_ring R] : comm_ring (arithmetic_function R) := { .. arithmetic_function.add_comm_group, .. arithmetic_function.comm_semiring } instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] : module (arithmetic_function R) (arithmetic_function M) := { one_smul := one_smul', mul_smul := mul_smul', smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] }, smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] }, add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] }, zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, } section zeta /-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/ def zeta : arithmetic_function ℕ := ⟨λ x, ite (x = 0) 0 1, rfl⟩ localized "notation `ζ` := zeta" in arithmetic_function @[simp] lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h @[simp] theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (↑ζ * f) x = ∑ i in divisors x, f i := begin rw mul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M] {f : arithmetic_function M} {x : ℕ} : ((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i := begin rw smul_apply, transitivity ∑ i in divisors_antidiagonal x, f i.snd, { apply sum_congr rfl, intros i hi, rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩, rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] }, { apply sum_bij (λ i h, prod.snd i), { rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] }, { rintros ⟨a, b⟩ h, refl }, { rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h, dsimp at h, rw h at *, rw mem_divisors_antidiagonal at *, ext, swap, {refl}, simp only [prod.fst, prod.snd] at *, apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm), rcases h1 with ⟨rfl, h⟩, apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) }, { intros a ha, rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩, use (b, a), simp [ne0, mul_comm] } } end @[simp] theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := begin apply opposite.op_injective, rw [op_sum], convert @coe_zeta_mul_apply Rᵒᵖ _ { to_fun := opposite.op ∘ f, map_zero' := by simp} x, rw [mul_apply, mul_apply, op_sum], conv_lhs { rw ← map_swap_divisors_antidiagonal, }, rw sum_map, apply sum_congr rfl, intros y hy, by_cases h1 : y.fst = 0, { simp [function.comp_apply, h1] }, { simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap, if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] } end theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} : (ζ * f) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_zeta_mul_apply] theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} : (f * ζ) x = ∑ i in divisors x, f i := by rw [← nat_coe_nat ζ, coe_mul_zeta_apply] end zeta open_locale arithmetic_function section pmul /-- This is the pointwise product of `arithmetic_function`s. -/ def pmul [mul_zero_class R] (f g : arithmetic_function R) : arithmetic_function R := ⟨λ x, f x * g x, by simp⟩ @[simp] lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} : f.pmul g x = f x * g x := rfl lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) : f.pmul g = g.pmul f := by { ext, simp [mul_comm] } variable [semiring R] @[simp] lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f := begin ext x, cases x; simp [nat.succ_ne_zero], end @[simp] lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f := begin ext x, cases x; simp [nat.succ_ne_zero], end /-- This is the pointwise power of `arithmetic_function`s. -/ def ppow (f : arithmetic_function R) (k : ℕ) : arithmetic_function R := if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k, by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩ @[simp] lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ := by rw [ppow, dif_pos rfl] @[simp] lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) : f.ppow k x = (f x) ^ k := by { rw [ppow, dif_neg (ne_of_gt kpos)], refl } lemma ppow_succ {f : arithmetic_function R} {k : ℕ} : f.ppow (k + 1) = f.pmul (f.ppow k) := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ], induction k; simp, end lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} : f.ppow (k + 1) = (f.ppow k).pmul f := begin ext x, rw [ppow_apply (nat.succ_pos k), pow_succ'], induction k; simp, end end pmul /-- Multiplicative functions -/ def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop := f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n) namespace is_multiplicative section monoid_with_zero variable [monoid_with_zero R] @[simp] lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 := h.1 @[simp] lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative) {m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n := hf.2 h end monoid_with_zero lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) : is_multiplicative (f : arithmetic_function R) := ⟨by simp [h], λ m n cop, by simp [cop, h]⟩ lemma mul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f * g) := ⟨by { simp [hf, hg], }, begin simp only [mul_apply], intros m n cop, rw sum_mul_sum, symmetry, apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)), { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def], split, {ring}, rw nat.mul_eq_zero at *, apply not_or ha hb }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, dsimp only, rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right, hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right], ring, }, { rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab, rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd, simp only [prod.mk.inj_iff] at h, ext; dsimp only, { transitivity nat.gcd (a1 * a2) (a1 * b1), { rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.1, nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (a1 * a2) (a2 * b2), { rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a1 * b1), { rw [mul_comm, nat.gcd_mul_right, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } }, { transitivity nat.gcd (b1 * b2) (a2 * b2), { rw [nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] }, { rw [← hcd.1.1, ← hcd.2.1] at cop, rw [← hcd.2.1, h.2, nat.gcd_mul_right, cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } }, { rintros ⟨b1, b2⟩ h, simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h, use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)), simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal], rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _], { rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] }, rw [mul_comm n m, h.1] } end⟩ lemma pmul [comm_semiring R] {f g : arithmetic_function R} (hf : f.is_multiplicative) (hg : g.is_multiplicative) : is_multiplicative (f.pmul g) := ⟨by { simp [hf, hg], }, λ m n cop, begin simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop], ring, end⟩ end is_multiplicative section special_functions /-- The identity on `ℕ` as an `arithmetic_function`. -/ def id : arithmetic_function ℕ := ⟨id, rfl⟩ @[simp] lemma id_apply {x : ℕ} : id x = x := rfl /-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/ def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k @[simp] lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k := begin cases k, { simp [pow] }, simp [pow, (ne_of_lt (nat.succ_pos k)).symm], end /-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/ def sigma (k : ℕ) : arithmetic_function ℕ := ⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩ localized "notation `σ` := sigma" in arithmetic_function @[simp] lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k := begin ext, rw [sigma, zeta_mul_apply], apply sum_congr rfl, intros x hx, rw [pow_apply, if_neg (not_and_of_not_right _ _)], contrapose! hx, simp [hx], end lemma is_multiplicative_zeta : is_multiplicative ζ := ⟨by simp, λ m n cop, begin cases m, {simp}, cases n, {simp}, simp [nat.succ_ne_zero] end⟩ lemma is_multiplicative_id : is_multiplicative arithmetic_function.id := ⟨rfl, λ _ _ _, rfl⟩ lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R} (hf : f.is_multiplicative) {k : ℕ} : is_multiplicative (f.ppow k) := begin induction k with k hi, { exact is_multiplicative_zeta.nat_cast }, { rw ppow_succ, apply hf.pmul hi }, end lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) := is_multiplicative_id.ppow lemma is_multiplicative_sigma {k : ℕ} : is_multiplicative (sigma k) := begin rw [← zeta_mul_pow_eq_sigma], apply ((is_multiplicative_zeta).mul is_multiplicative_pow) end /-- `Ω n` is the number of prime factors of `n`. -/ def card_factors : arithmetic_function ℕ := ⟨λ n, n.factors.length, by simp⟩ localized "notation `Ω` := card_factors" in arithmetic_function lemma card_factors_apply {n : ℕ} : Ω n = n.factors.length := rfl @[simp] lemma card_factors_one : Ω 1 = 0 := by simp [card_factors] lemma card_factors_eq_one_iff_prime {n : ℕ} : Ω n = 1 ↔ n.prime := begin refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩, cases n, { contrapose! h, simp }, rcases list.length_eq_one.1 h with ⟨x, hx⟩, rw [← prod_factors n.succ_pos, hx, list.prod_singleton], apply prime_of_mem_factors, rw [hx, list.mem_singleton] end lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) : Ω (m * n) = Ω m + Ω n := by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card, ← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq, multiset.card_add, multiset.coe_card, multiset.coe_card] lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) : Ω s.prod = (multiset.map Ω s).sum := begin revert h0, apply s.induction_on, by simp, intros a t h h0, rw [multiset.prod_cons, mul_ne_zero_iff] at h0, simp [h0, card_factors_mul, h], end /-- `ω n` is the number of distinct prime factors of `n`. -/ def card_distinct_factors : arithmetic_function ℕ := ⟨λ n, n.factors.erase_dup.length, by simp⟩ localized "notation `ω` := card_distinct_factors" in arithmetic_function lemma card_distinct_factors_zero : ω 0 = 0 := by simp lemma card_distinct_factors_apply {n : ℕ} : ω n = n.factors.erase_dup.length := rfl lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) : ω n = Ω n ↔ squarefree n := begin rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply], split; intro h, { rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h, apply list.nodup_erase_dup }, { rw list.erase_dup_eq_self.2 h, refl } end /-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors, `μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`. If `n` is not squarefree, `μ n = 0`. -/ def moebius : arithmetic_function ℤ := ⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩ localized "notation `μ` := moebius" in arithmetic_function @[simp] lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) := if_pos h @[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n := begin split; intro h, { contrapose! h, simp [h] }, { simp [h, pow_ne_zero] } end lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 := begin split; intro h, { rw moebius_ne_zero_iff_squarefree at h, rw moebius_apply_of_squarefree h, apply neg_one_pow_eq_or }, { rcases h with h | h; simp [h] } end open unique_factorization_monoid @[simp] lemma coe_moebius_mul_coe_zeta [comm_ring R] : (μ * ζ : arithmetic_function R) = 1 := begin ext x, cases x, { simp only [divisors_zero, sum_empty, ne.def, not_false_iff, coe_mul_zeta_apply, zero_ne_one, one_apply_ne] }, cases x, { simp only [moebius_apply_of_squarefree, card_factors_one, squarefree_one, divisors_one, int.cast_one, sum_singleton, coe_mul_zeta_apply, one_one, int_coe_apply, pow_zero] }, rw [coe_mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))], simp_rw [int_coe_apply], rw [←int.cast_sum, ← sum_filter_ne_zero], convert int.cast_zero, simp only [moebius_ne_zero_iff_squarefree], suffices : ∑ (y : finset ℕ) in (unique_factorization_monoid.normalized_factors x.succ.succ).to_finset.powerset, ite (squarefree y.val.prod) ((-1:ℤ) ^ Ω y.val.prod) 0 = 0, { have h : ∑ i in _, ite (squarefree i) ((-1:ℤ) ^ Ω i) 0 = _ := (sum_divisors_filter_squarefree (nat.succ_ne_zero _)), exact (eq.trans (by congr') h).trans this }, apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _), { intros y hy, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy, have h : unique_factorization_monoid.normalized_factors y.val.prod = y.val, { apply factors_multiset_prod_of_irreducible, intros z hz, apply irreducible_of_normalized_factor _ (multiset.subset_of_le (le_trans hy (multiset.erase_dup_le _)) hz) }, rw [if_pos], { rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] }, rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors, h], { apply y.nodup }, rw [ne.def, multiset.prod_eq_zero_iff], intro con, rw ← h at con, exact not_irreducible_zero (irreducible_of_normalized_factor 0 con) }, { rw finset.nonempty, rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩, { rcases exists_mem_normalized_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩, use j, apply multiset.mem_to_finset.2 hj }, rw nat.is_unit_iff, norm_num }, end @[simp] lemma coe_zeta_mul_coe_moebius [comm_ring R] : (ζ * μ : arithmetic_function R) = 1 := by rw [mul_comm, coe_moebius_mul_coe_zeta] @[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_moebius_mul_coe_zeta] @[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 := by rw [← int_coe_int μ, coe_zeta_mul_coe_moebius] section comm_ring variable [comm_ring R] instance : invertible (ζ : arithmetic_function R) := { inv_of := μ, inv_of_mul_self := coe_moebius_mul_coe_zeta, mul_inv_of_self := coe_zeta_mul_coe_moebius} /-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/ def zeta_unit : units (arithmetic_function R) := ⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩ @[simp] lemma coe_zeta_unit : ((zeta_unit : units (arithmetic_function R)) : arithmetic_function R) = ζ := rfl @[simp] lemma inv_zeta_unit : ((zeta_unit⁻¹ : units (arithmetic_function R)) : arithmetic_function R) = μ := rfl end comm_ring /-- Möbius inversion for functions to an `add_comm_group`. -/ theorem sum_eq_iff_sum_smul_moebius_eq [add_comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n := begin let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩, let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩, transitivity (ζ : arithmetic_function ℤ) • f' = g', { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, rw coe_zeta_smul_apply, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) }, transitivity μ • g' = f', { split; intro h, { rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] }, { rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } }, { rw ext_iff, apply forall_congr, intro n, cases n, { simp }, simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply, if_false, zero_hom.coe_mk], rw sum_congr rfl (λ x hx, _), rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) }, end /-- Möbius inversion for functions to a `comm_ring`. -/ theorem sum_eq_iff_sum_mul_moebius_eq [comm_ring R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n := begin rw sum_eq_iff_sum_smul_moebius_eq, apply forall_congr, intro a, apply imp_congr (iff.refl _) (eq.congr_left (sum_congr rfl (λ x hx, _))), rw [gsmul_eq_mul], end /-- Möbius inversion for functions to a `comm_group`. -/ theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := @sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _ /-- Möbius inversion for functions to a `comm_group_with_zero`. -/ theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R} (hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) : (∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔ ∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n := begin refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq (units R) _ (λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1) (λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _)); refine imp_congr_right (λ hn, _), { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] }, { dsimp, rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0, prod_congr rfl _], intros x hx, rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)), units.coe_hom_apply, units.coe_gpow₀, units.coe_mk0] } end end special_functions end arithmetic_function end nat
eb84c9ef7d5438f25de4d5ad0d864bfc7bce86af
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/analysis/normed_space/basic.lean
af715c62849e4f71ee23c197d3275313057b0c8f
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
24,570
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} local attribute [instance, priority 0] nat.cast_coe local attribute [instance, priority 0] int.cast_coe local attribute [instance, priority 0] rat.cast_coe noncomputable theory open filter metric local notation f `→_{`:50 a `}`:0 b := tendsto f (nhds a) (nhds b) class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_triangle_sum {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_triangle lemma norm_pos_iff (g : α) : 0 < ∥ g ∥ ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma norm_reverse_triangle' (a b : α) : ∥a∥ - ∥b∥ ≤ ∥a - b∥ := by simpa using add_le_add (norm_triangle (a - b) (b)) (le_refl (-∥b∥)) lemma norm_reverse_triangle (a b : α) : abs(∥a∥ - ∥b∥) ≤ ∥a - b∥ := suffices -(∥a∥ - ∥b∥) ≤ ∥a - b∥, from abs_le_of_le_of_neg_le (norm_reverse_triangle' a b) this, calc -(∥a∥ - ∥b∥) = ∥b∥ - ∥a∥ : by abel ... ≤ ∥b - a∥ : norm_reverse_triangle' b a ... = ∥a - b∥ : by rw ← norm_neg (a - b); simp lemma norm_triangle_sub {a b : α} : ∥a - b∥ ≤ ∥a∥ + ∥b∥ := by simpa only [sub_eq_add_neg, norm_neg] using norm_triangle a (-b) lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by rw ←norm_neg; simp lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp theorem normed_space.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (nhds 0) ↔ ∀ ε > 0, { x | ∥ f x ∥ < ε } ∈ l := begin rw [metric.tendsto_nhds], simp only [normed_group.dist_eq, sub_zero], split, { intros h ε εgt0, rcases h ε εgt0 with ⟨s, ssets, hs⟩, exact mem_sets_of_superset ssets hs }, intros h ε εgt0, exact ⟨_, h ε εgt0, set.subset.refl _⟩ end section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group [normed_group β] : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : α → Type*} [fintype α] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero [normed_group α] [normed_group β] {f : γ → β} {a : filter γ} : tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e ∥) a (nhds 0) := have tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (nhds 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm] ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_triangle_sub ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end instance normed_top_monoid : topological_add_monoid α := by apply_instance instance normed_top_group : topological_add_group α := by apply_instance end normed_group section normed_ring class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, n > 0 → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_triangle }, { rw ←zero_add (0 : ℝ), apply tendsto_add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto_mul, { apply continuous_iff_continuous_at.1, apply continuous.comp, { apply continuous_fst }, { apply continuous_norm }}, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto_mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section normed_field class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) = norm a * norm b) class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul], ..i } @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (finset.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } lemma real.norm_eq_abs (r : ℝ): norm r = abs r := rfl end normed_field @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] section normed_space class normed_space (α : Type*) (β : Type*) [normed_field α] extends normed_group β, vector_space α β := (norm_smul : ∀ (a:α) b, norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] instance normed_field.to_normed_space : normed_space α α := { dist_eq := normed_field.dist_eq, norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp limg (continuous_iff_continuous_at.1 continuous_norm _), have lim1 := tendsto_mul limf' limg', simp only [zero_mul, sub_eq_add_neg] at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := tendsto_mul (tendsto_const_nhds : tendsto _ _ (nhds ∥ s ∥)) limg3, simp only [sub_eq_add_neg, mul_zero] at lim2, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end lemma tendsto_smul_const {g : γ → F} {e : filter γ} (s : α) {b : F} : (tendsto g e (nhds b)) → tendsto (λ x, s • (g x)) e (nhds (s • b)) := tendsto_smul tendsto_const_nhds lemma continuous_smul [topological_space γ] {f : γ → α} {g : γ → E} (hf : continuous f) (hg : continuous g) : continuous (λc, f c • g c) := continuous_iff_continuous_at.2 $ assume c, tendsto_smul (continuous_iff_continuous_at.1 hf _) (continuous_iff_continuous_at.1 hg _) /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos ((norm_pos_iff _).2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {ι : Type*} {E : ι → Type*} [fintype ι] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm := λf, ((finset.univ.sup (λb, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume f g, congr_arg coe $ congr_arg (finset.sup finset.univ) $ by funext i; exact nndist_eq_nnnorm _ _, norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul], ..metric_space_pi, ..pi.vector_space α } /-- A normed space can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_space.core (α : Type*) (β : Type*) [normed_field α] [add_comm_group β] [has_scalar α β] [has_norm β] := (norm_eq_zero_iff : ∀ x : β, ∥x∥ = 0 ↔ x = 0) (norm_smul : ∀ c : α, ∀ x : β, ∥c • x∥ = ∥c∥ * ∥x∥) (triangle : ∀ x y : β, ∥x + y∥ ≤ ∥x∥ + ∥y∥) noncomputable def normed_space.of_core (α : Type*) (β : Type*) [normed_field α] [add_comm_group β] [vector_space α β] [has_norm β] (C : normed_space.core α β) : normed_space α β := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(1 : α) • (y - x)∥ : by simp ... = ∥y - x∥ : begin rw[C.norm_smul], simp end, norm_smul := C.norm_smul } end normed_space section summable local attribute [instance] classical.prop_decidable open finset filter variables [normed_group α] [complete_space α] lemma summable_iff_vanishing_norm {f : ι → α} : summable f ↔ ∀ε>0, (∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε) := begin simp only [summable_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hf : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := summable_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hf ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.zero_le_sum (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_triangle_sum t f) $ lt_of_le_of_lt (finset.sum_le_sum $ assume i _, h i) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (nhds ∥(∑ i, f i)∥) := (has_sum_tsum $ summable_of_summable_norm hf).comp (continuous_norm.tendsto _), have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (nhds (∑ i, ∥f i∥)) := has_sum_tsum hf, le_of_tendsto_of_tendsto at_top_ne_bot h₁ h₂ $ univ_mem_sets' $ assume s, norm_triangle_sum _ _ end summable namespace complex instance : normed_field ℂ := { norm := complex.abs, dist_eq := λ _ _, rfl, norm_mul := complex.abs_mul, .. complex.discrete_field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := complex.abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := complex.abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : n ≥ 0) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn end complex
60da68fecd5d19d6398a0087dc735a9933d655cc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/triangulated/rotate.lean
4e5f57120189f02c8972bc7f84ec054edcbe4a45
[ "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
12,157
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.preadditive.additive_functor import category_theory.triangulated.basic /-! # Rotate This file adds the ability to rotate triangles and triangle morphisms. It also shows that rotation gives an equivalence on the category of triangles. -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.pretriangulated open category_theory.category /-- We work in an preadditive category `C` equipped with an additive shift. -/ variables {C : Type u} [category.{v} C] [preadditive C] variables [has_shift C ℤ] variables (X : C) /-- If you rotate a triangle, you get another triangle. Given a triangle of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` applying `rotate` gives a triangle of the form: ``` g h -f⟦1⟧' Y ───> Z ───> X⟦1⟧ ───> Y⟦1⟧ ``` -/ @[simps] def triangle.rotate (T : triangle C) : triangle C := triangle.mk T.mor₂ T.mor₃ (-T.mor₁⟦1⟧') section local attribute [semireducible] shift_shift_neg shift_neg_shift /-- Given a triangle of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` applying `inv_rotate` gives a triangle that can be thought of as: ``` -h⟦-1⟧' f g Z⟦-1⟧ ───> X ───> Y ───> Z ``` (note that this diagram doesn't technically fit the definition of triangle, as `Z⟦-1⟧⟦1⟧` is not necessarily equal to `Z`, but it is isomorphic, by the `counit_iso` of `shift C`) -/ @[simps] def triangle.inv_rotate (T : triangle C) : triangle C := triangle.mk (-T.mor₃⟦(-1:ℤ)⟧' ≫ (shift_shift_neg _ _).hom) T.mor₁ (T.mor₂ ≫ (shift_neg_shift _ _).inv) end namespace triangle_morphism variables {T₁ T₂ T₃ T₄: triangle C} open triangle /-- You can also rotate a triangle morphism to get a morphism between the two rotated triangles. Given a triangle morphism of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧ V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` applying `rotate` gives a triangle morphism of the form: ``` g h -f⟦1⟧ Y ───> Z ───> X⟦1⟧ ───> Y⟦1⟧ │ │ │ │ │b │c │a⟦1⟧ │b⟦1⟧' V V V V Y' ───> Z' ───> X'⟦1⟧ ───> Y'⟦1⟧ g' h' -f'⟦1⟧ ``` -/ @[simps] def rotate (f : triangle_morphism T₁ T₂) : triangle_morphism (T₁.rotate) (T₂.rotate):= { hom₁ := f.hom₂, hom₂ := f.hom₃, hom₃ := f.hom₁⟦1⟧', comm₃' := begin dsimp, simp only [rotate_mor₃, comp_neg, neg_comp, ← functor.map_comp, f.comm₁] end } /-- Given a triangle morphism of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧ V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` applying `inv_rotate` gives a triangle morphism that can be thought of as: ``` -h⟦-1⟧ f g Z⟦-1⟧ ───> X ───> Y ───> Z │ │ │ │ │c⟦-1⟧' │a │b │c V V V V Z'⟦-1⟧ ───> X' ───> Y' ───> Z' -h'⟦-1⟧ f' g' ``` (note that this diagram doesn't technically fit the definition of triangle morphism, as `Z⟦-1⟧⟦1⟧` is not necessarily equal to `Z`, and `Z'⟦-1⟧⟦1⟧` is not necessarily equal to `Z'`, but they are isomorphic, by the `counit_iso` of `shift C`) -/ @[simps] def inv_rotate (f : triangle_morphism T₁ T₂) : triangle_morphism (T₁.inv_rotate) (T₂.inv_rotate) := { hom₁ := f.hom₃⟦-1⟧', hom₂ := f.hom₁, hom₃ := f.hom₂, comm₁' := begin dsimp [inv_rotate_mor₁], simp only [discrete.functor_map_id, id_comp, preadditive.comp_neg, assoc, neg_inj, nat_trans.id_app, preadditive.neg_comp], rw [← functor.map_comp_assoc, ← f.comm₃, functor.map_comp_assoc, μ_naturality_assoc, nat_trans.naturality, functor.id_map], end, comm₃' := begin dsimp, simp only [discrete.functor_map_id, id_comp, μ_inv_naturality, category.assoc, nat_trans.id_app, unit_of_tensor_iso_unit_inv_app], erw ε_naturality_assoc, rw comm₂_assoc end } end triangle_morphism variables (C) /-- Rotating triangles gives an endofunctor on the category of triangles in `C`. -/ @[simps] def rotate : triangle C ⥤ triangle C := { obj := triangle.rotate, map := λ _ _ f, f.rotate } /-- The inverse rotation of triangles gives an endofunctor on the category of triangles in `C`. -/ @[simps] def inv_rotate : triangle C ⥤ triangle C := { obj := triangle.inv_rotate, map := λ _ _ f, f.inv_rotate } variables {C} variables [∀ n : ℤ, functor.additive (shift_functor C n)] /-- There is a natural map from a triangle to the `inv_rotate` of its `rotate`. -/ @[simps] def to_inv_rotate_rotate (T : triangle C) : T ⟶ (inv_rotate C).obj ((rotate C).obj T) := { hom₁ := (shift_shift_neg _ _).inv, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃, comm₃' := begin dsimp, simp only [ε_app_obj, eq_to_iso.hom, discrete.functor_map_id, id_comp, eq_to_iso.inv, category.assoc, obj_μ_inv_app, functor.map_comp, nat_trans.id_app, obj_ε_app, unit_of_tensor_iso_unit_inv_app], erw μ_inv_hom_app_assoc, refl end } /-- There is a natural transformation between the identity functor on triangles in `C`, and the composition of a rotation with an inverse rotation. -/ @[simps] def rot_comp_inv_rot_hom : 𝟭 (triangle C) ⟶ rotate C ⋙ inv_rotate C := { app := to_inv_rotate_rotate, naturality' := begin introv, ext, { dsimp, simp only [nat_iso.cancel_nat_iso_inv_right_assoc, discrete.functor_map_id, id_comp, μ_inv_naturality, assoc, nat_trans.id_app, unit_of_tensor_iso_unit_inv_app], erw ε_naturality }, { dsimp, rw [comp_id, id_comp] }, { dsimp, rw [comp_id, id_comp] }, end } /-- There is a natural map from the `inv_rotate` of the `rotate` of a triangle to itself. -/ @[simps] def from_inv_rotate_rotate (T : triangle C) : (inv_rotate C).obj ((rotate C).obj T) ⟶ T := { hom₁ := (shift_equiv C 1).unit_inv.app T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃, comm₃' := begin dsimp, rw [unit_of_tensor_iso_unit_inv_app, ε_app_obj], simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, assoc, functor.map_comp, obj_μ_app, obj_ε_inv_app, comp_id, μ_inv_hom_app_assoc], erw [μ_inv_hom_app, μ_inv_hom_app_assoc, category.comp_id] end } /-- There is a natural transformation between the composition of a rotation with an inverse rotation on triangles in `C`, and the identity functor. -/ @[simps] def rot_comp_inv_rot_inv : rotate C ⋙ inv_rotate C ⟶ 𝟭 (triangle C) := { app := from_inv_rotate_rotate } /-- The natural transformations between the identity functor on triangles in `C` and the composition of a rotation with an inverse rotation are natural isomorphisms (they are isomorphisms in the category of functors). -/ @[simps] def rot_comp_inv_rot : 𝟭 (triangle C) ≅ rotate C ⋙ inv_rotate C := { hom := rot_comp_inv_rot_hom, inv := rot_comp_inv_rot_inv } /-- There is a natural map from the `rotate` of the `inv_rotate` of a triangle to itself. -/ @[simps] def from_rotate_inv_rotate (T : triangle C) : (rotate C).obj ((inv_rotate C).obj T) ⟶ T := { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := (shift_equiv C 1).counit.app T.obj₃, comm₂' := begin dsimp, rw unit_of_tensor_iso_unit_inv_app, simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, add_neg_equiv_counit_iso_hom, eq_to_hom_refl, nat_trans.comp_app, assoc, μ_inv_hom_app_assoc, ε_hom_inv_app], exact category.comp_id _, end, comm₃' := begin dsimp, simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, functor.map_neg, functor.map_comp, obj_μ_app, obj_ε_inv_app, comp_id, assoc, μ_naturality_assoc, neg_neg, category_theory.functor.map_id, add_neg_equiv_counit_iso_hom, eq_to_hom_refl, nat_trans.comp_app], erw [μ_inv_hom_app, category.comp_id, obj_zero_map_μ_app], rw [discrete.functor_map_id, nat_trans.id_app, comp_id], end } /-- There is a natural transformation between the composition of an inverse rotation with a rotation on triangles in `C`, and the identity functor. -/ @[simps] def inv_rot_comp_rot_hom : inv_rotate C ⋙ rotate C ⟶ 𝟭 (triangle C) := { app := from_rotate_inv_rotate } /-- There is a natural map from a triangle to the `rotate` of its `inv_rotate`. -/ @[simps] def to_rotate_inv_rotate (T : triangle C) : T ⟶ (rotate C).obj ((inv_rotate C).obj T) := { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := (shift_equiv C 1).counit_inv.app T.obj₃, comm₃' := begin dsimp, rw category_theory.functor.map_id, simp only [comp_id, add_neg_equiv_counit_iso_inv, eq_to_hom_refl, id_comp, nat_trans.comp_app, discrete.functor_map_id, nat_trans.id_app, functor.map_neg, functor.map_comp, obj_μ_app, obj_ε_inv_app, assoc, μ_naturality_assoc, neg_neg, μ_inv_hom_app_assoc], erw [μ_inv_hom_app, category.comp_id, obj_zero_map_μ_app], simp only [discrete.functor_map_id, nat_trans.id_app, comp_id, ε_hom_inv_app_assoc], end } /-- There is a natural transformation between the identity functor on triangles in `C`, and the composition of an inverse rotation with a rotation. -/ @[simps] def inv_rot_comp_rot_inv : 𝟭 (triangle C) ⟶ inv_rotate C ⋙ rotate C := { app := to_rotate_inv_rotate, naturality' := begin introv, ext, { dsimp, rw [comp_id, id_comp] }, { dsimp, rw [comp_id, id_comp] }, { dsimp, rw [add_neg_equiv_counit_iso_inv, eq_to_hom_map, eq_to_hom_refl, id_comp], simp only [nat_trans.comp_app, assoc], erw [μ_inv_naturality, ε_naturality_assoc] }, end } /-- The natural transformations between the composition of a rotation with an inverse rotation on triangles in `C`, and the identity functor on triangles are natural isomorphisms (they are isomorphisms in the category of functors). -/ @[simps] def inv_rot_comp_rot : inv_rotate C ⋙ rotate C ≅ 𝟭 (triangle C) := { hom := inv_rot_comp_rot_hom, inv := inv_rot_comp_rot_inv } variables (C) /-- Rotating triangles gives an auto-equivalence on the category of triangles in `C`. -/ @[simps] def triangle_rotation : equivalence (triangle C) (triangle C) := { functor := rotate C, inverse := inv_rotate C, unit_iso := rot_comp_inv_rot, counit_iso := inv_rot_comp_rot, functor_unit_iso_comp' := begin introv, ext, { dsimp, rw comp_id }, { dsimp, rw comp_id }, { dsimp, rw unit_of_tensor_iso_unit_inv_app, simp only [discrete.functor_map_id, nat_trans.id_app, id_comp, functor.map_comp, obj_ε_app, obj_μ_inv_app, assoc, add_neg_equiv_counit_iso_hom, eq_to_hom_refl, nat_trans.comp_app, ε_inv_app_obj, comp_id, μ_inv_hom_app_assoc], erw [μ_inv_hom_app_assoc, μ_inv_hom_app], refl } end } variables {C} instance : is_equivalence (rotate C) := by { change is_equivalence (triangle_rotation C).functor, apply_instance, } instance : is_equivalence (inv_rotate C) := by { change is_equivalence (triangle_rotation C).inverse, apply_instance, } end category_theory.pretriangulated
61b52020b753fa7283760824292452ea01bcb61d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/algebra/tower.lean
7416808106c253283dd70a459d7f3f7dfd5d00ae
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
14,049
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.subalgebra.basic import algebra.algebra.bilinear /-! # Towers of algebras In this file we prove basic facts about towers of algebra. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. An important definition is `to_alg_hom R S A`, the canonical `R`-algebra homomorphism `S →ₐ[R] A`. -/ open_locale pointwise universes u v w u₁ v₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) (M : Type v₁) namespace algebra variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables {A} /-- The `R`-algebra morphism `A → End (M)` corresponding to the representation of the algebra `A` on the `R`-module `M`. This is a stronger version of `distrib_mul_action.to_linear_map`, and could also have been called `algebra.to_module_End`. -/ def lsmul : A →ₐ[R] module.End R M := { to_fun := distrib_mul_action.to_linear_map R M, map_one' := linear_map.ext $ λ _, one_smul A _, map_mul' := λ a b, linear_map.ext $ smul_assoc a b, map_zero' := linear_map.ext $ λ _, zero_smul A _, map_add' := λ a b, linear_map.ext $ λ _, add_smul _ _ _, commutes' := λ r, linear_map.ext $ algebra_map_smul A r, } @[simp] lemma lsmul_coe (a : A) : (lsmul R M a : M → M) = (•) a := rfl lemma lmul_algebra_map (x : R) : algebra.lmul R A (algebra_map R A x) = algebra.lsmul R A x := eq.symm $ linear_map.ext $ smul_def x end algebra namespace is_scalar_tower section module variables [comm_semiring R] [semiring A] [algebra R A] variables [has_smul R M] [mul_action A M] [is_scalar_tower R A M] variables {R} (A) {M} theorem algebra_map_smul (r : R) (x : M) : algebra_map R A r • x = r • x := by rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] end module section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables {R S A} theorem of_algebra_map_eq [algebra R A] (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) : is_scalar_tower R S A := ⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩ /-- See note [partially-applied ext lemmas]. -/ theorem of_algebra_map_eq' [algebra R A] (h : algebra_map R A = (algebra_map S A).comp (algebra_map R S)) : is_scalar_tower R S A := of_algebra_map_eq $ ring_hom.ext_iff.1 h variables (R S A) instance subalgebra (S₀ : subalgebra R S) : is_scalar_tower S₀ S A := of_algebra_map_eq $ λ x, rfl variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] theorem algebra_map_eq : algebra_map R A = (algebra_map S A).comp (algebra_map R S) := ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] theorem algebra_map_apply (x : R) : algebra_map R A x = algebra_map S A (algebra_map R S x) := by rw [algebra_map_eq R S A, ring_hom.comp_apply] instance subalgebra' (S₀ : subalgebra R S) : is_scalar_tower R S₀ A := @is_scalar_tower.of_algebra_map_eq R S₀ A _ _ _ _ _ _ $ λ _, (is_scalar_tower.algebra_map_apply R S A _ : _) @[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A] (h1 h2 : algebra S A) (h : ∀ (r : S) (x : A), (by haveI := h1; exact r • x) = r • x) : h1 = h2 := algebra.algebra_ext _ _ $ λ r, by simpa only [@algebra.smul_def _ _ _ _ h1, @algebra.smul_def _ _ _ _ h2, mul_one] using h r 1 /-- In a tower, the canonical map from the middle element to the top element is an algebra homomorphism over the bottom element. -/ def to_alg_hom : S →ₐ[R] A := { commutes' := λ _, (algebra_map_apply _ _ _ _).symm, .. algebra_map S A } lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl @[simp] lemma coe_to_alg_hom : ↑(to_alg_hom R S A) = algebra_map S A := ring_hom.ext $ λ _, rfl @[simp] lemma coe_to_alg_hom' : (to_alg_hom R S A : S → A) = algebra_map S A := rfl variables {R S A B} @[simp, priority 900] lemma _root_.alg_hom.map_algebra_map (f : A →ₐ[S] B) (r : R) : f (algebra_map R A r) = algebra_map R B r := by rw [algebra_map_apply R S A r, f.commutes, ← algebra_map_apply R S B] variables (R) @[simp, priority 900] lemma _root_.alg_hom.comp_algebra_map_of_tower (f : A →ₐ[S] B) : (f : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext f.map_algebra_map variables (R) {S A B} -- conflicts with is_scalar_tower.subalgebra @[priority 999] instance subsemiring (U : subsemiring S) : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl @[nolint instance_priority] instance of_ring_hom {R A B : Type*} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : @is_scalar_tower R A B _ (f.to_ring_hom.to_algebra.to_has_smul) _ := by { letI := (f : A →+* B).to_algebra, exact of_algebra_map_eq (λ x, (f.commutes x).symm) } end semiring end is_scalar_tower section homs variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R) {A S B} open is_scalar_tower namespace alg_hom /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A →ₐ[S] B) : A →ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A →+* B) } lemma restrict_scalars_apply (f : A →ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A →ₐ[S] B) : (f.restrict_scalars R : A →+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A →ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : (A →ₐ[S] B) → (A →ₐ[R] B)) := λ f g h, alg_hom.ext (alg_hom.congr_fun h : _) end alg_hom namespace alg_equiv /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A ≃ₐ[S] B) : A ≃ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A ≃+* B) } lemma restrict_scalars_apply (f : A ≃ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A ≃ₐ[S] B) : (f.restrict_scalars R : A ≃+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A ≃ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : (A ≃ₐ[S] B) → (A ≃ₐ[R] B)) := λ f g h, alg_equiv.ext (alg_equiv.congr_fun h : _) end alg_equiv end homs namespace subalgebra open is_scalar_tower section semiring variables (R) {S A B} [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra R A] [algebra S B] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] /-- Given a tower `A / ↥U / S / R` of algebras, where `U` is an `S`-subalgebra of `A`, reinterpret `U` as an `R`-subalgebra of `A`. -/ def restrict_scalars (U : subalgebra S A) : subalgebra R A := { algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ }, .. U } @[simp] lemma coe_restrict_scalars {U : subalgebra S A} : (restrict_scalars R U : set A) = (U : set A) := rfl @[simp] lemma restrict_scalars_top : restrict_scalars R (⊤ : subalgebra S A) = ⊤ := set_like.coe_injective rfl @[simp] lemma restrict_scalars_to_submodule {U : subalgebra S A} : (U.restrict_scalars R).to_submodule = U.to_submodule.restrict_scalars R := set_like.coe_injective rfl @[simp] lemma mem_restrict_scalars {U : subalgebra S A} {x : A} : x ∈ restrict_scalars R U ↔ x ∈ U := iff.rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : subalgebra S A → subalgebra R A) := λ U V H, ext $ λ x, by rw [← mem_restrict_scalars R, H, mem_restrict_scalars] /-- Produces an `R`-algebra map from `U.restrict_scalars R` given an `S`-algebra map from `U`. This is a special case of `alg_hom.restrict_scalars` that can be helpful in elaboration. -/ @[simp] def of_restrict_scalars (U : subalgebra S A) (f : U →ₐ[S] B) : U.restrict_scalars R →ₐ[R] B := f.restrict_scalars R end semiring end subalgebra namespace algebra variables {R A} [comm_semiring R] [semiring A] [algebra R A] variables {M} [add_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M] lemma span_restrict_scalars_eq_span_of_surjective (h : function.surjective (algebra_map R A)) (s : set M) : (submodule.span A s).restrict_scalars R = submodule.span R s := begin refine le_antisymm (λ x hx, _) (submodule.span_subset_span _ _ _), refine submodule.span_induction hx _ _ _ _, { exact λ x hx, submodule.subset_span hx }, { exact submodule.zero_mem _ }, { exact λ x y, submodule.add_mem _ }, { intros c x hx, obtain ⟨c', rfl⟩ := h c, rw is_scalar_tower.algebra_map_smul, exact submodule.smul_mem _ _ hx }, end lemma coe_span_eq_span_of_surjective (h : function.surjective (algebra_map R A)) (s : set M) : (submodule.span A s : set M) = submodule.span R s := congr_arg coe (algebra.span_restrict_scalars_eq_span_of_surjective h s) end algebra namespace is_scalar_tower open subalgebra variables [comm_semiring R] [comm_semiring S] [comm_semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] theorem adjoin_range_to_alg_hom (t : set A) : (algebra.adjoin (to_alg_hom R S A).range t).restrict_scalars R = (algebra.adjoin S t).restrict_scalars R := subalgebra.ext $ λ z, show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔ z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A), from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A), by rw this, by { ext z, exact ⟨λ ⟨⟨x, y, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, hy⟩, rfl⟩⟩ } end is_scalar_tower section semiring variables {R S A} namespace submodule section module variables [semiring R] [semiring S] [add_comm_monoid A] variables [module R S] [module S A] [module R A] [is_scalar_tower R S A] open is_scalar_tower theorem smul_mem_span_smul_of_mem {s : set S} {t : set A} {k : S} (hks : k ∈ span R s) {x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) := span_induction hks (λ c hc, subset_span $ set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩) (by { rw zero_smul, exact zero_mem _ }) (λ c₁ c₂ ih₁ ih₂, by { rw add_smul, exact add_mem ih₁ ih₂ }) (λ b c hc, by { rw is_scalar_tower.smul_assoc, exact smul_mem _ _ hc }) variables [smul_comm_class R S A] theorem smul_mem_span_smul {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R t) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem smul_mem_span_smul' {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R (s • t)) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, let ⟨p, q, hp, hq, hpq⟩ := set.mem_smul.1 hx in by { rw [← hpq, smul_smul], exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq }) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem span_smul {s : set S} (hs : span R s = ⊤) (t : set A) : span R (s • t) = (span S t).restrict_scalars R := le_antisymm (span_le.2 $ λ x hx, let ⟨p, q, hps, hqt, hpqx⟩ := set.mem_smul.1 hx in hpqx ▸ (span S t).smul_mem p (subset_span hqt)) $ λ p hp, span_induction hp (λ x hx, one_smul S x ▸ smul_mem_span_smul hs (subset_span hx)) (zero_mem _) (λ _ _, add_mem) (λ k x hx, smul_mem_span_smul' hs hx) end module section algebra variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] /-- A variant of `submodule.span_image` for `algebra_map`. -/ lemma span_algebra_map_image (a : set R) : submodule.span R (algebra_map R S '' a) = (submodule.span R a).map (algebra.linear_map R S) := (submodule.span_image $ algebra.linear_map R S).trans rfl lemma span_algebra_map_image_of_tower {S T : Type*} [comm_semiring S] [semiring T] [module R S] [is_scalar_tower R S S] [algebra R T] [algebra S T] [is_scalar_tower R S T] (a : set S) : submodule.span R (algebra_map S T '' a) = (submodule.span R a).map ((algebra.linear_map S T).restrict_scalars R) := (submodule.span_image $ (algebra.linear_map S T).restrict_scalars R).trans rfl lemma map_mem_span_algebra_map_image {S T : Type*} [comm_semiring S] [semiring T] [algebra R S] [algebra R T] [algebra S T] [is_scalar_tower R S T] (x : S) (a : set S) (hx : x ∈ submodule.span R a) : algebra_map S T x ∈ submodule.span R (algebra_map S T '' a) := by { rw [span_algebra_map_image_of_tower, mem_map], exact ⟨x, hx, rfl⟩ } end algebra end submodule end semiring section ring namespace algebra variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] lemma lsmul_injective [no_zero_smul_divisors A M] {x : A} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_right_injective _ hx end algebra end ring
5c420b4cd5950df06f20ae36386cfea5da0bb8cb
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/univ_vars.lean
92f4c7848d4772775fb05c78ee9e7d845d320dc6
[ "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
417
lean
-- set_option pp.universes true universe u variable A : Type.{u} definition id1 (a : A) : A := a check @id1 variable B : Type definition id2 (a : B) : B := a check @id2 universe variable k variable C : Type.{k} definition id3 (a : C) := a check @id3 universe variables l m variable A₁ : Type.{l} variable A₂ : Type.{l} definition foo (a₁ : A₁) (a₂ : A₂) := a₁ == a₂ check @foo check Type.{m}
7807d566378b4ac62403746a47365885208ce2f4
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/analysis/exponential.lean
812ff22b73e39f7de2fee4b8df9b3a38b1c6ce55
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
57,799
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 -/ import topology.instances.complex tactic.linarith data.complex.exponential group_theory.quotient_group open finset filter metric namespace complex lemma tendsto_exp_zero_one : tendsto exp (nhds 0) (nhds 1) := tendsto_nhds_nhds.2 $ λ ε ε0, ⟨min (ε / 2) 1, lt_min (div_pos ε0 (by norm_num)) (by norm_num), λ x h, have h : abs x < min (ε / 2) 1, by simpa [dist_eq] using h, calc abs (exp x - 1) ≤ 2 * abs x : abs_exp_sub_one_le (le_trans (le_of_lt h) (min_le_right _ _)) ... = abs x + abs x : two_mul (abs x) ... < ε / 2 + ε / 2 : add_lt_add (lt_of_lt_of_le h (min_le_left _ _)) (lt_of_lt_of_le h (min_le_left _ _)) ... = ε : by rw add_halves⟩ lemma continuous_exp : continuous exp := continuous_iff_continuous_at.2 (λ x, have H1 : tendsto (λ h, exp (x + h)) (nhds 0) (nhds (exp x)), by simpa [exp_add] using tendsto_mul tendsto_const_nhds tendsto_exp_zero_one, have H2 : tendsto (λ y, y - x) (nhds x) (nhds (x - x)) := tendsto_sub tendsto_id (@tendsto_const_nhds _ _ _ x _), suffices tendsto ((λ h, exp (x + h)) ∘ (λ y, id y - (λ z, x) y)) (nhds x) (nhds (exp x)), by simp only [function.comp, add_sub_cancel'_right, id.def] at this; exact this, tendsto.comp (by rw [sub_self] at H2; exact H2) H1) lemma continuous_sin : continuous sin := continuous_mul (continuous_mul (continuous_sub ((continuous_mul continuous_neg' continuous_const).comp continuous_exp) ((continuous_mul continuous_id continuous_const).comp continuous_exp)) continuous_const) continuous_const lemma continuous_cos : continuous cos := continuous_mul (continuous_add ((continuous_mul continuous_id continuous_const).comp continuous_exp) ((continuous_mul continuous_neg' continuous_const).comp continuous_exp)) continuous_const lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := continuous_mul (continuous_subtype_val.comp continuous_sin) (continuous_inv subtype.property (continuous_subtype_val.comp continuous_cos)) lemma continuous_sinh : continuous sinh := continuous_mul (continuous_sub continuous_exp (continuous_neg'.comp continuous_exp)) continuous_const lemma continuous_cosh : continuous cosh := continuous_mul (continuous_add continuous_exp (continuous_neg'.comp continuous_exp)) continuous_const end complex namespace real lemma continuous_exp : continuous exp := (complex.continuous_of_real.comp complex.continuous_exp).comp complex.continuous_re lemma continuous_sin : continuous sin := (complex.continuous_of_real.comp complex.continuous_sin).comp complex.continuous_re lemma continuous_cos : continuous cos := (complex.continuous_of_real.comp complex.continuous_cos).comp complex.continuous_re lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact continuous_mul (continuous_subtype_val.comp continuous_sin) (continuous_inv subtype.property (continuous_subtype_val.comp continuous_cos)) lemma continuous_sinh : continuous sinh := (complex.continuous_of_real.comp complex.continuous_sinh).comp complex.continuous_re lemma continuous_cosh : continuous cosh := (complex.continuous_of_real.comp complex.continuous_cosh).comp complex.continuous_re private lemma exists_exp_eq_of_one_le {x : ℝ} (hx : 1 ≤ x) : ∃ y, exp y = x := let ⟨y, hy⟩ := @intermediate_value real.exp 0 (x - 1) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_exp _) (by simpa) (by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hx)) (sub_nonneg.2 hx) in ⟨y, hy.2.2⟩ lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := exists_exp_eq_of_one_le (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := exists_exp_eq_of_one_le hx1 end noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma exists_cos_eq_zero : ∃ x, 1 ≤ x ∧ x ≤ 2 ∧ cos x = 0 := real.intermediate_value' (λ x _ _, continuous_iff_continuous_at.1 continuous_cos _) (le_of_lt cos_one_pos) (le_of_lt cos_two_neg) (by norm_num) noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero local notation `π` := pi @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.1 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith using [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_pow_two_add_cos_pow_two (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_pow_two_add_cos_pow_two x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith using [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith using [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : ∃ y, -(π / 2) ≤ y ∧ y ≤ π / 2 ∧ sin y = x := @real.intermediate_value sin (-(π / 2)) (π / 2) x (λ _ _ _, continuous_iff_continuous_at.1 continuous_sin _) (by rwa [sin_neg, sin_pi_div_two]) (by rwa sin_pi_div_two) (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) namespace angle /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : is_add_group_hom (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := is_add_group_hom.gsmul _ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ two_ne_zero, ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ two_ne_zero, eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_left_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero, cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx.1 hx.2) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).2.1 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq hx₁ hx₂)).2.2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith using [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith using [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith using [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_pow_two_add_cos_pow_two (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_pow_two_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith using [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith using [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex local notation `π` := real.pi /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x,abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith using [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith using [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := if hx : x = 0 then by simp [hx] else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx, div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)] lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow 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⟩ lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[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 ℂ _), 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 [cpow_def]; split_ifs; 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 [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 [cpow_def]; split_ifs; simp [exp_neg] @[simp] 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_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_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 : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_lt hx).symm, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero'] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] end real
1c3753f233768c3d5e0e720ea9f46cdb0d558ad0
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/defeq_simp_lemmas2.lean
99f04490efe485b29c052fd7a2459c34c2ea2376
[ "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
1,436
lean
namespace foo universe l constants (A : Type.{l}) noncomputable definition q (x : A) := x noncomputable definition h (x : A) : A := q x noncomputable definition g (x y : A) := h y noncomputable definition f (x y z : A) := g (g x y) z noncomputable definition d (x y z w : A) := f (f x y z) (f y z w) (f x w z) attribute [defeq] definition h.rfl (x : A) : h x = x := rfl attribute [defeq] definition g.rfl (x y : A) : g x y = y := rfl attribute [defeq] definition f.rfl (x y z : A) : f x y z = z := rfl attribute [defeq] definition d.rfl (x y z w : A) : d x y z w = z := rfl attribute [defeq] definition h.def (x : A) : h x = q x := rfl attribute [defeq] definition g.def (x y : A) : g x y = h y := rfl attribute [defeq] definition f.def (x y z : A) : f x y z = g (g x y) z := rfl attribute [defeq] definition d.def (x y z w : A) : d x y z w = f (f x y z) (f y z w) (f x w z) := rfl -- Confirm that more recent annotations get priority print [defeq] attribute h.rfl [defeq, priority 1001] attribute g.rfl [defeq, priority 1001] attribute f.rfl [defeq, priority 1001] attribute d.rfl [defeq, priority 1001] -- Confirm that priority annotations override print [defeq] attribute h.def [defeq, priority 1001] attribute g.def [defeq, priority 1001] attribute f.def [defeq, priority 1001] attribute d.def [defeq, priority 1001] -- Confirm that most recent annotations get priority to break explicit priority ties print [defeq] end foo
2246d3338f1ae1bca2bb3868731008d41851d5fd
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_simp3.lean
cbbb6b549ea785754bd2a7bee14137d6990c9fcd
[ "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
152
lean
example (A : Type₁) (a₁ a₂ : A) : a₁ = a₂ → (λ (B : Type₁) (f : A → B), f a₁) = (λ (B : Type₁) (f : A → B), f a₂) := by simp
5c902de533afbf13815e118117d5f3c0ada38649
84c325c9a58de83324b777adc78ac188ecdbceae
/src/util/io.lean
08fd78324f372bbf87b5a84a30ea04a227814e63
[ "Apache-2.0" ]
permissive
brando90/lean-gym
0c3b433dac9c1a1079623721cdb3307a0981d86b
f4a94fcf54f8729be416ebdca82097d95a6f1c39
refs/heads/main
1,683,583,589,195
1,622,558,076,000
1,622,558,076,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,146
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Stanislas Polu Helper functions to work with the io monad. -/ import system.io import tactic.gptf.utils.util section io open interaction_monad interaction_monad.result namespace io /-- verion of io.run_tactic' which does not suppress the exception msg -/ meta def run_tactic'' {α} (tac :tactic α) : io α := do { io.run_tactic $ do { result ← tactic.capture tac, match result with | (success val _) := pure val | (exception m_fmt pos _) := do { let fmt_msg := (m_fmt.get_or_else (λ _, format!"n/a")) (), let msg := format!"run_tactic_failed: failed: pos={pos} msg={fmt_msg}", tactic.trace format!"TRACE RUN_TACTIC FAILURE: {msg}", tactic.fail msg } end } } end io end io -- convenience function for command-line argument parsing meta def list.nth_except {α} : list α → ℕ → string → io α := λ xs pos msg, match (xs.nth pos) with | (some result) := pure result | none := do io.fail' format!"must supply {msg} as argument {pos}" end
9d994db1d9b32698e419d119ed303467bbfcc657
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/manifold/cont_mdiff.lean
4b7650eb57e3d001f015e3658516759fe710487e
[ "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
93,542
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 geometry.manifold.mfderiv import geometry.manifold.local_invariant_properties /-! # Smooth functions between smooth manifolds We define `Cⁿ` functions between smooth manifolds, as functions which are `Cⁿ` in charts, and prove basic properties of these notions. ## Main definitions and statements Let `M ` and `M'` be two smooth manifolds, with respect to model with corners `I` and `I'`. Let `f : M → M'`. * `cont_mdiff_within_at I I' n f s x` states that the function `f` is `Cⁿ` within the set `s` around the point `x`. * `cont_mdiff_at I I' n f x` states that the function `f` is `Cⁿ` around `x`. * `cont_mdiff_on I I' n f s` states that the function `f` is `Cⁿ` on the set `s` * `cont_mdiff I I' n f` states that the function `f` is `Cⁿ`. * `cont_mdiff_on.comp` gives the invariance of the `Cⁿ` property under composition * `cont_mdiff_on.cont_mdiff_on_tangent_map_within` states that the bundled derivative of a `Cⁿ` function in a domain is `Cᵐ` when `m + 1 ≤ n`. * `cont_mdiff.cont_mdiff_tangent_map` states that the bundled derivative of a `Cⁿ` function is `Cᵐ` when `m + 1 ≤ n`. * `cont_mdiff_iff_cont_diff` states that, for functions between vector spaces, manifold-smoothness is equivalent to usual smoothness. We also give many basic properties of smooth functions between manifolds, following the API of smooth functions between vector spaces. ## Implementation details Many properties follow for free from the corresponding properties of functions in vector spaces, as being `Cⁿ` is a local property invariant under the smooth groupoid. We take advantage of the general machinery developed in `local_invariant_properties.lean` to get these properties automatically. For instance, the fact that being `Cⁿ` does not depend on the chart one considers is given by `lift_prop_within_at_indep_chart`. For this to work, the definition of `cont_mdiff_within_at` and friends has to follow definitionally the setup of local invariant properties. Still, we recast the definition in terms of extended charts in `cont_mdiff_on_iff` and `cont_mdiff_iff`. -/ open set function filter charted_space smooth_manifold_with_corners open_locale topological_space manifold /-! ### Definition of smooth functions between manifolds -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] -- declare a smooth manifold `M` over the pair `(E, H)`. {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [charted_space H M] [Is : smooth_manifold_with_corners I M] -- declare a smooth manifold `M'` over the pair `(E', H')`. {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H') {M' : Type*} [topological_space M'] [charted_space H' M'] [I's : smooth_manifold_with_corners I' M'] -- declare a smooth manifold `N` over the pair `(F, G)`. {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] {G : Type*} [topological_space G] {J : model_with_corners 𝕜 F G} {N : Type*} [topological_space N] [charted_space G N] [Js : smooth_manifold_with_corners J N] -- declare a smooth manifold `N'` over the pair `(F', G')`. {F' : Type*} [normed_add_comm_group F'] [normed_space 𝕜 F'] {G' : Type*} [topological_space G'] {J' : model_with_corners 𝕜 F' G'} {N' : Type*} [topological_space N'] [charted_space G' N'] [J's : smooth_manifold_with_corners J' N'] -- declare functions, sets, points and smoothness indices {f f₁ : M → M'} {s s₁ t : set M} {x : M} {m n : ℕ∞} /-- Property in the model space of a model with corners of being `C^n` within at set at a point, when read in the model vector space. This property will be lifted to manifolds to define smooth functions between manifolds. -/ def cont_diff_within_at_prop (n : ℕ∞) (f : H → H') (s : set H) (x : H) : Prop := cont_diff_within_at 𝕜 n (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I x) lemma cont_diff_within_at_prop_self_source {f : E → H'} {s : set E} {x : E} : cont_diff_within_at_prop 𝓘(𝕜, E) I' n f s x ↔ cont_diff_within_at 𝕜 n (I' ∘ f) s x := begin simp_rw [cont_diff_within_at_prop, model_with_corners_self_coe, range_id, inter_univ], refl end lemma cont_diff_within_at_prop_self {f : E → E'} {s : set E} {x : E} : cont_diff_within_at_prop 𝓘(𝕜, E) 𝓘(𝕜, E') n f s x ↔ cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_prop_self_source 𝓘(𝕜, E') lemma cont_diff_within_at_prop_self_target {f : H → E'} {s : set H} {x : H} : cont_diff_within_at_prop I 𝓘(𝕜, E') n f s x ↔ cont_diff_within_at 𝕜 n (f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I x) := iff.rfl /-- Being `Cⁿ` in the model space is a local property, invariant under smooth maps. Therefore, it will lift nicely to manifolds. -/ lemma cont_diff_within_at_local_invariant_prop (n : ℕ∞) : (cont_diff_groupoid ∞ I).local_invariant_prop (cont_diff_groupoid ∞ I') (cont_diff_within_at_prop I I' n) := { is_local := begin assume s x u f u_open xu, have : I.symm ⁻¹' (s ∩ u) ∩ range I = (I.symm ⁻¹' s ∩ range I) ∩ I.symm ⁻¹' u, by simp only [inter_right_comm, preimage_inter], rw [cont_diff_within_at_prop, cont_diff_within_at_prop, this], symmetry, apply cont_diff_within_at_inter, have : u ∈ 𝓝 (I.symm (I x)), by { rw [model_with_corners.left_inv], exact is_open.mem_nhds u_open xu }, apply continuous_at.preimage_mem_nhds I.continuous_symm.continuous_at this, end, right_invariance' := begin assume s x f e he hx h, rw cont_diff_within_at_prop at h ⊢, have : I x = (I ∘ e.symm ∘ I.symm) (I (e x)), by simp only [hx] with mfld_simps, rw this at h, have : I (e x) ∈ (I.symm) ⁻¹' e.target ∩ range I, by simp only [hx] with mfld_simps, have := ((mem_groupoid_of_pregroupoid.2 he).2.cont_diff_within_at this).of_le le_top, convert (h.comp' _ this).mono_of_mem _ using 1, { ext y, simp only with mfld_simps }, refine mem_nhds_within.mpr ⟨I.symm ⁻¹' e.target, e.open_target.preimage I.continuous_symm, by simp_rw [mem_preimage, I.left_inv, e.maps_to hx], _⟩, mfld_set_tac end, congr_of_forall := begin assume s x f g h hx hf, apply hf.congr, { assume y hy, simp only with mfld_simps at hy, simp only [h, hy] with mfld_simps }, { simp only [hx] with mfld_simps } end, left_invariance' := begin assume s x f e' he' hs hx h, rw cont_diff_within_at_prop at h ⊢, have A : (I' ∘ f ∘ I.symm) (I x) ∈ (I'.symm ⁻¹' e'.source ∩ range I'), by simp only [hx] with mfld_simps, have := ((mem_groupoid_of_pregroupoid.2 he').1.cont_diff_within_at A).of_le le_top, convert this.comp _ h _, { ext y, simp only with mfld_simps }, { assume y hy, simp only with mfld_simps at hy, simpa only [hy] with mfld_simps using hs hy.1 } end } lemma cont_diff_within_at_prop_mono (n : ℕ∞) ⦃s x t⦄ ⦃f : H → H'⦄ (hts : t ⊆ s) (h : cont_diff_within_at_prop I I' n f s x) : cont_diff_within_at_prop I I' n f t x := begin apply h.mono (λ y hy, _), simp only with mfld_simps at hy, simp only [hy, hts _] with mfld_simps end lemma cont_diff_within_at_prop_id (x : H) : cont_diff_within_at_prop I I ∞ id univ x := begin simp [cont_diff_within_at_prop], have : cont_diff_within_at 𝕜 ∞ id (range I) (I x) := cont_diff_id.cont_diff_at.cont_diff_within_at, apply this.congr (λ y hy, _), { simp only with mfld_simps }, { simp only [model_with_corners.right_inv I hy] with mfld_simps } end /-- A function is `n` times continuously differentiable within a set at a point in a manifold if it is continuous and it is `n` times continuously differentiable in this set around this point, when read in the preferred chart at this point. -/ def cont_mdiff_within_at (n : ℕ∞) (f : M → M') (s : set M) (x : M) := lift_prop_within_at (cont_diff_within_at_prop I I' n) f s x /-- Abbreviation for `cont_mdiff_within_at I I' ⊤ f s x`. See also documentation for `smooth`. -/ @[reducible] def smooth_within_at (f : M → M') (s : set M) (x : M) := cont_mdiff_within_at I I' ⊤ f s x /-- A function is `n` times continuously differentiable at a point in a manifold if it is continuous and it is `n` times continuously differentiable around this point, when read in the preferred chart at this point. -/ def cont_mdiff_at (n : ℕ∞) (f : M → M') (x : M) := cont_mdiff_within_at I I' n f univ x lemma cont_mdiff_at_iff {n : ℕ∞} {f : M → M'} {x : M} : cont_mdiff_at I I' n f x ↔ continuous_at f x ∧ cont_diff_within_at 𝕜 n (ext_chart_at I' (f x) ∘ f ∘ (ext_chart_at I x).symm) (range I) (ext_chart_at I x x) := lift_prop_at_iff.trans $ by { rw [cont_diff_within_at_prop, preimage_univ, univ_inter], refl } /-- Abbreviation for `cont_mdiff_at I I' ⊤ f x`. See also documentation for `smooth`. -/ @[reducible] def smooth_at (f : M → M') (x : M) := cont_mdiff_at I I' ⊤ f x /-- A function is `n` times continuously differentiable in a set of a manifold if it is continuous and, for any pair of points, it is `n` times continuously differentiable on this set in the charts around these points. -/ def cont_mdiff_on (n : ℕ∞) (f : M → M') (s : set M) := ∀ x ∈ s, cont_mdiff_within_at I I' n f s x /-- Abbreviation for `cont_mdiff_on I I' ⊤ f s`. See also documentation for `smooth`. -/ @[reducible] def smooth_on (f : M → M') (s : set M) := cont_mdiff_on I I' ⊤ f s /-- A function is `n` times continuously differentiable in a manifold if it is continuous and, for any pair of points, it is `n` times continuously differentiable in the charts around these points. -/ def cont_mdiff (n : ℕ∞) (f : M → M') := ∀ x, cont_mdiff_at I I' n f x /-- Abbreviation for `cont_mdiff I I' ⊤ f`. Short note to work with these abbreviations: a lemma of the form `cont_mdiff_foo.bar` will apply fine to an assumption `smooth_foo` using dot notation or normal notation. If the consequence `bar` of the lemma involves `cont_diff`, it is still better to restate the lemma replacing `cont_diff` with `smooth` both in the assumption and in the conclusion, to make it possible to use `smooth` consistently. This also applies to `smooth_at`, `smooth_on` and `smooth_within_at`.-/ @[reducible] def smooth (f : M → M') := cont_mdiff I I' ⊤ f /-! ### Basic properties of smooth functions between manifolds -/ variables {I I'} lemma cont_mdiff.smooth (h : cont_mdiff I I' ⊤ f) : smooth I I' f := h lemma smooth.cont_mdiff (h : smooth I I' f) : cont_mdiff I I' ⊤ f := h lemma cont_mdiff_on.smooth_on (h : cont_mdiff_on I I' ⊤ f s) : smooth_on I I' f s := h lemma smooth_on.cont_mdiff_on (h : smooth_on I I' f s) : cont_mdiff_on I I' ⊤ f s := h lemma cont_mdiff_at.smooth_at (h : cont_mdiff_at I I' ⊤ f x) : smooth_at I I' f x := h lemma smooth_at.cont_mdiff_at (h : smooth_at I I' f x) : cont_mdiff_at I I' ⊤ f x := h lemma cont_mdiff_within_at.smooth_within_at (h : cont_mdiff_within_at I I' ⊤ f s x) : smooth_within_at I I' f s x := h lemma smooth_within_at.cont_mdiff_within_at (h : smooth_within_at I I' f s x) : cont_mdiff_within_at I I' ⊤ f s x := h lemma cont_mdiff.cont_mdiff_at (h : cont_mdiff I I' n f) : cont_mdiff_at I I' n f x := h x lemma smooth.smooth_at (h : smooth I I' f) : smooth_at I I' f x := cont_mdiff.cont_mdiff_at h lemma cont_mdiff_within_at_univ : cont_mdiff_within_at I I' n f univ x ↔ cont_mdiff_at I I' n f x := iff.rfl lemma smooth_within_at_univ : smooth_within_at I I' f univ x ↔ smooth_at I I' f x := cont_mdiff_within_at_univ lemma cont_mdiff_on_univ : cont_mdiff_on I I' n f univ ↔ cont_mdiff I I' n f := by simp only [cont_mdiff_on, cont_mdiff, cont_mdiff_within_at_univ, forall_prop_of_true, mem_univ] lemma smooth_on_univ : smooth_on I I' f univ ↔ smooth I I' f := cont_mdiff_on_univ /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart. -/ lemma cont_mdiff_within_at_iff : cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ cont_diff_within_at 𝕜 n ((ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) (ext_chart_at I x x) := iff.rfl /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart. This form states smoothness of `f` written in such a way that the set is restricted to lie within the domain/codomain of the corresponding charts. Even though this expression is more complicated than the one in `cont_mdiff_within_at_iff`, it is a smaller set, but their germs at `ext_chart_at I x x` are equal. It is sometimes useful to rewrite using this in the goal. -/ lemma cont_mdiff_within_at_iff' : cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ cont_diff_within_at 𝕜 n ((ext_chart_at I' (f x)) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' (f x)).source)) (ext_chart_at I x x) := begin rw [cont_mdiff_within_at_iff, and.congr_right_iff], set e := ext_chart_at I x, set e' := ext_chart_at I' (f x), refine λ hc, cont_diff_within_at_congr_nhds _, rw [← e.image_source_inter_eq', ← ext_chart_at_map_nhds_within_eq_image, ← ext_chart_at_map_nhds_within, inter_comm, nhds_within_inter_of_mem], exact hc (ext_chart_at_source_mem_nhds _ _) end /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in the corresponding extended chart in the target. -/ lemma cont_mdiff_within_at_iff_target : cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ cont_mdiff_within_at I 𝓘(𝕜, E') n (ext_chart_at I' (f x) ∘ f) s x := begin simp_rw [cont_mdiff_within_at, lift_prop_within_at, ← and_assoc], have cont : (continuous_within_at f s x ∧ continuous_within_at (ext_chart_at I' (f x) ∘ f) s x) ↔ continuous_within_at f s x, { refine ⟨λ h, h.1, λ h, ⟨h, _⟩⟩, have h₂ := (chart_at H' (f x)).continuous_to_fun.continuous_within_at (mem_chart_source _ _), refine ((I'.continuous_at.comp_continuous_within_at h₂).comp' h).mono_of_mem _, exact inter_mem self_mem_nhds_within (h.preimage_mem_nhds_within $ (chart_at _ _).open_source.mem_nhds $ mem_chart_source _ _) }, simp_rw [cont, cont_diff_within_at_prop, ext_chart_at, local_equiv.coe_trans, model_with_corners.to_local_equiv_coe, local_homeomorph.coe_coe, model_with_corners_self_coe, chart_at_self_eq, local_homeomorph.refl_apply, comp.left_id] end lemma smooth_within_at_iff : smooth_within_at I I' f s x ↔ continuous_within_at f s x ∧ cont_diff_within_at 𝕜 ∞ (ext_chart_at I' (f x) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) (ext_chart_at I x x) := cont_mdiff_within_at_iff lemma smooth_within_at_iff_target : smooth_within_at I I' f s x ↔ continuous_within_at f s x ∧ smooth_within_at I 𝓘(𝕜, E') (ext_chart_at I' (f x) ∘ f) s x := cont_mdiff_within_at_iff_target lemma cont_mdiff_at_iff_target {x : M} : cont_mdiff_at I I' n f x ↔ continuous_at f x ∧ cont_mdiff_at I 𝓘(𝕜, E') n (ext_chart_at I' (f x) ∘ f) x := by rw [cont_mdiff_at, cont_mdiff_at, cont_mdiff_within_at_iff_target, continuous_within_at_univ] lemma smooth_at_iff_target {x : M} : smooth_at I I' f x ↔ continuous_at f x ∧ smooth_at I 𝓘(𝕜, E') (ext_chart_at I' (f x) ∘ f) x := cont_mdiff_at_iff_target include Is I's /-- One can reformulate smoothness within a set at a point as continuity within this set at this point, and smoothness in any chart containing that point. -/ lemma cont_mdiff_within_at_iff_of_mem_source {x' : M} {y : M'} (hx : x' ∈ (chart_at H x).source) (hy : f x' ∈ (chart_at H' y).source) : cont_mdiff_within_at I I' n f s x' ↔ continuous_within_at f s x' ∧ cont_diff_within_at 𝕜 n (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) (ext_chart_at I x x') := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_indep_chart (structure_groupoid.chart_mem_maximal_atlas _ x) hx (structure_groupoid.chart_mem_maximal_atlas _ y) hy lemma cont_mdiff_within_at_iff_of_mem_source' {x' : M} {y : M'} (hx : x' ∈ (chart_at H x).source) (hy : f x' ∈ (chart_at H' y).source) : cont_mdiff_within_at I I' n f s x' ↔ continuous_within_at f s x' ∧ cont_diff_within_at 𝕜 n ((ext_chart_at I' y) ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' y).source)) (ext_chart_at I x x') := begin refine (cont_mdiff_within_at_iff_of_mem_source hx hy).trans _, rw [← ext_chart_at_source I] at hx, rw [← ext_chart_at_source I'] at hy, rw [and.congr_right_iff], set e := ext_chart_at I x, set e' := ext_chart_at I' (f x), refine λ hc, cont_diff_within_at_congr_nhds _, rw [← e.image_source_inter_eq', ← ext_chart_at_map_nhds_within_eq_image' I x hx, ← ext_chart_at_map_nhds_within' I x hx, inter_comm, nhds_within_inter_of_mem], exact hc ((ext_chart_at_open_source _ _).mem_nhds hy) end lemma cont_mdiff_at_iff_of_mem_source {x' : M} {y : M'} (hx : x' ∈ (chart_at H x).source) (hy : f x' ∈ (chart_at H' y).source) : cont_mdiff_at I I' n f x' ↔ continuous_at f x' ∧ cont_diff_within_at 𝕜 n (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) (range I) (ext_chart_at I x x') := (cont_mdiff_within_at_iff_of_mem_source hx hy).trans $ by rw [continuous_within_at_univ, preimage_univ, univ_inter] omit Is lemma cont_mdiff_within_at_iff_target_of_mem_source {x : M} {y : M'} (hy : f x ∈ (chart_at H' y).source) : cont_mdiff_within_at I I' n f s x ↔ continuous_within_at f s x ∧ cont_mdiff_within_at I 𝓘(𝕜, E') n (ext_chart_at I' y ∘ f) s x := begin simp_rw [cont_mdiff_within_at], rw [(cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_indep_chart_target (chart_mem_maximal_atlas I' y) hy, and_congr_right], intro hf, simp_rw [structure_groupoid.lift_prop_within_at_self_target], simp_rw [((chart_at H' y).continuous_at hy).comp_continuous_within_at hf], rw [← ext_chart_at_source I'] at hy, simp_rw [(ext_chart_at_continuous_at' I' _ hy).comp_continuous_within_at hf], refl, end lemma cont_mdiff_at_iff_target_of_mem_source {x : M} {y : M'} (hy : f x ∈ (chart_at H' y).source) : cont_mdiff_at I I' n f x ↔ continuous_at f x ∧ cont_mdiff_at I 𝓘(𝕜, E') n (ext_chart_at I' y ∘ f) x := begin rw [cont_mdiff_at, cont_mdiff_within_at_iff_target_of_mem_source hy, continuous_within_at_univ, cont_mdiff_at], apply_instance end omit I's variable (I) lemma model_with_corners.symm_continuous_within_at_comp_right_iff {X} [topological_space X] {f : H → X} {s : set H} {x : H} : continuous_within_at (f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I x) ↔ continuous_within_at f s x := begin refine ⟨λ h, _, λ h, _⟩, { have := h.comp I.continuous_within_at (maps_to_preimage _ _), simp_rw [preimage_inter, preimage_preimage, I.left_inv, preimage_id', preimage_range, inter_univ] at this, rwa [function.comp.assoc, I.symm_comp_self] at this }, { rw [← I.left_inv x] at h, exact h.comp I.continuous_within_at_symm (inter_subset_left _ _) } end variable {I} lemma ext_chart_at_symm_continuous_within_at_comp_right_iff {X} [topological_space X] {f : M → X} {s : set M} {x x' : M} : continuous_within_at (f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) (ext_chart_at I x x') ↔ continuous_within_at (f ∘ (chart_at H x).symm) ((chart_at H x).symm ⁻¹' s) (chart_at H x x') := by convert I.symm_continuous_within_at_comp_right_iff; refl include Is lemma cont_mdiff_within_at_iff_source_of_mem_source {x' : M} (hx' : x' ∈ (chart_at H x).source) : cont_mdiff_within_at I I' n f s x' ↔ cont_mdiff_within_at 𝓘(𝕜, E) I' n (f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).symm ⁻¹' s ∩ range I) (ext_chart_at I x x') := begin have h2x' := hx', rw [← ext_chart_at_source I] at h2x', simp_rw [cont_mdiff_within_at, (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_indep_chart_source (chart_mem_maximal_atlas I x) hx', structure_groupoid.lift_prop_within_at_self_source, ext_chart_at_symm_continuous_within_at_comp_right_iff, cont_diff_within_at_prop_self_source, cont_diff_within_at_prop, function.comp, (chart_at H x).left_inv hx', (ext_chart_at I x).left_inv h2x'], refl, end lemma cont_mdiff_at_iff_source_of_mem_source {x' : M} (hx' : x' ∈ (chart_at H x).source) : cont_mdiff_at I I' n f x' ↔ cont_mdiff_within_at 𝓘(𝕜, E) I' n (f ∘ (ext_chart_at I x).symm) (range I) (ext_chart_at I x x') := by simp_rw [cont_mdiff_at, cont_mdiff_within_at_iff_source_of_mem_source hx', preimage_univ, univ_inter] lemma cont_mdiff_at_ext_chart_at' {x' : M} (h : x' ∈ (chart_at H x).source) : cont_mdiff_at I 𝓘(𝕜, E) n (ext_chart_at I x) x' := begin refine (cont_mdiff_at_iff_of_mem_source h (mem_chart_source _ _)).mpr _, rw [← ext_chart_at_source I] at h, refine ⟨ext_chart_at_continuous_at' _ _ h, _⟩, refine cont_diff_within_at_id.congr_of_eventually_eq _ _, { refine eventually_eq_of_mem (ext_chart_at_target_mem_nhds_within' I x h) (λ x₂ hx₂, _), simp_rw [function.comp_apply, (ext_chart_at I x).right_inv hx₂], refl }, simp_rw [function.comp_apply, (ext_chart_at I x).right_inv ((ext_chart_at I x).maps_to h)], refl end lemma cont_mdiff_at_ext_chart_at : cont_mdiff_at I 𝓘(𝕜, E) n (ext_chart_at I x) x := cont_mdiff_at_ext_chart_at' $ mem_chart_source H x include I's /-- If the set where you want `f` to be smooth lies entirely in a single chart, and `f` maps it into a single chart, the smoothness of `f` on that set can be expressed by purely looking in these charts. Note: this lemma uses `ext_chart_at I x '' s` instead of `(ext_chart_at I x).symm ⁻¹' s` to ensure that this set lies in `(ext_chart_at I x).target`. -/ lemma cont_mdiff_on_iff_of_subset_source {x : M} {y : M'} (hs : s ⊆ (chart_at H x).source) (h2s : maps_to f s (chart_at H' y).source) : cont_mdiff_on I I' n f s ↔ continuous_on f s ∧ cont_diff_on 𝕜 n (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) (ext_chart_at I x '' s) := begin split, { refine λ H, ⟨λ x hx, (H x hx).1, _⟩, rintro _ ⟨x', hx', rfl⟩, exact ((cont_mdiff_within_at_iff_of_mem_source (hs hx') (h2s.image_subset $ mem_image_of_mem f hx')).mp (H _ hx')).2.mono (maps_to_ext_chart_at I x hs).image_subset }, { rintro ⟨h1, h2⟩ x' hx', refine (cont_mdiff_within_at_iff_of_mem_source (hs hx') (h2s.image_subset $ mem_image_of_mem f hx')).mpr ⟨h1.continuous_within_at hx', _⟩, refine (h2 _ $ mem_image_of_mem _ hx').mono_of_mem _, rw [← ext_chart_at_source I] at hs, rw [(ext_chart_at I x).image_eq_target_inter_inv_preimage hs], refine inter_mem _ (ext_chart_preimage_mem_nhds_within' I x (hs hx') self_mem_nhds_within), have := ext_chart_at_target_mem_nhds_within' I x (hs hx'), refine nhds_within_mono _ (inter_subset_right _ _) this } end /-- One can reformulate smoothness on a set as continuity on this set, and smoothness in any extended chart. -/ lemma cont_mdiff_on_iff : cont_mdiff_on I I' n f s ↔ continuous_on f s ∧ ∀ (x : M) (y : M'), cont_diff_on 𝕜 n (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' y).source)) := begin split, { assume h, refine ⟨λ x hx, (h x hx).1, λ x y z hz, _⟩, simp only with mfld_simps at hz, let w := (ext_chart_at I x).symm z, have : w ∈ s, by simp only [w, hz] with mfld_simps, specialize h w this, have w1 : w ∈ (chart_at H x).source, by simp only [w, hz] with mfld_simps, have w2 : f w ∈ (chart_at H' y).source, by simp only [w, hz] with mfld_simps, convert ((cont_mdiff_within_at_iff_of_mem_source w1 w2).mp h).2.mono _, { simp only [w, hz] with mfld_simps }, { mfld_set_tac } }, { rintros ⟨hcont, hdiff⟩ x hx, refine ((cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_iff $ hcont x hx).mpr _, dsimp [cont_diff_within_at_prop], convert hdiff x (f x) (ext_chart_at I x x) (by simp only [hx] with mfld_simps) using 1, mfld_set_tac } end /-- One can reformulate smoothness on a set as continuity on this set, and smoothness in any extended chart in the target. -/ lemma cont_mdiff_on_iff_target : cont_mdiff_on I I' n f s ↔ continuous_on f s ∧ ∀ (y : M'), cont_mdiff_on I 𝓘(𝕜, E') n (ext_chart_at I' y ∘ f) (s ∩ f ⁻¹' (ext_chart_at I' y).source) := begin inhabit E', simp only [cont_mdiff_on_iff, model_with_corners.source_eq, chart_at_self_eq, local_homeomorph.refl_local_equiv, local_equiv.refl_trans, ext_chart_at.equations._eqn_1, set.preimage_univ, set.inter_univ, and.congr_right_iff], intros h, split, { refine λ h' y, ⟨_, λ x _, h' x y⟩, have h'' : continuous_on _ univ := (model_with_corners.continuous I').continuous_on, convert (h''.comp' (chart_at H' y).continuous_to_fun).comp' h, simp }, { exact λ h' x y, (h' y).2 x default } end lemma smooth_on_iff : smooth_on I I' f s ↔ continuous_on f s ∧ ∀ (x : M) (y : M'), cont_diff_on 𝕜 ⊤ (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (s ∩ f ⁻¹' (ext_chart_at I' y).source)) := cont_mdiff_on_iff lemma smooth_on_iff_target : smooth_on I I' f s ↔ continuous_on f s ∧ ∀ (y : M'), smooth_on I 𝓘(𝕜, E') (ext_chart_at I' y ∘ f) (s ∩ f ⁻¹' (ext_chart_at I' y).source) := cont_mdiff_on_iff_target /-- One can reformulate smoothness as continuity and smoothness in any extended chart. -/ lemma cont_mdiff_iff : cont_mdiff I I' n f ↔ continuous f ∧ ∀ (x : M) (y : M'), cont_diff_on 𝕜 n (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' y).source)) := by simp [← cont_mdiff_on_univ, cont_mdiff_on_iff, continuous_iff_continuous_on_univ] /-- One can reformulate smoothness as continuity and smoothness in any extended chart in the target. -/ lemma cont_mdiff_iff_target : cont_mdiff I I' n f ↔ continuous f ∧ ∀ (y : M'), cont_mdiff_on I 𝓘(𝕜, E') n (ext_chart_at I' y ∘ f) (f ⁻¹' (ext_chart_at I' y).source) := begin rw [← cont_mdiff_on_univ, cont_mdiff_on_iff_target], simp [continuous_iff_continuous_on_univ] end lemma smooth_iff : smooth I I' f ↔ continuous f ∧ ∀ (x : M) (y : M'), cont_diff_on 𝕜 ⊤ (ext_chart_at I' y ∘ f ∘ (ext_chart_at I x).symm) ((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' y).source)) := cont_mdiff_iff lemma smooth_iff_target : smooth I I' f ↔ continuous f ∧ ∀ (y : M'), smooth_on I 𝓘(𝕜, E') (ext_chart_at I' y ∘ f) (f ⁻¹' (ext_chart_at I' y).source) := cont_mdiff_iff_target omit Is I's /-! ### Deducing smoothness from higher smoothness -/ lemma cont_mdiff_within_at.of_le (hf : cont_mdiff_within_at I I' n f s x) (le : m ≤ n) : cont_mdiff_within_at I I' m f s x := ⟨hf.1, hf.2.of_le le⟩ lemma cont_mdiff_at.of_le (hf : cont_mdiff_at I I' n f x) (le : m ≤ n) : cont_mdiff_at I I' m f x := cont_mdiff_within_at.of_le hf le lemma cont_mdiff_on.of_le (hf : cont_mdiff_on I I' n f s) (le : m ≤ n) : cont_mdiff_on I I' m f s := λ x hx, (hf x hx).of_le le lemma cont_mdiff.of_le (hf : cont_mdiff I I' n f) (le : m ≤ n) : cont_mdiff I I' m f := λ x, (hf x).of_le le /-! ### Deducing smoothness from smoothness one step beyond -/ lemma cont_mdiff_within_at.of_succ {n : ℕ} (h : cont_mdiff_within_at I I' n.succ f s x) : cont_mdiff_within_at I I' n f s x := h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)) lemma cont_mdiff_at.of_succ {n : ℕ} (h : cont_mdiff_at I I' n.succ f x) : cont_mdiff_at I I' n f x := cont_mdiff_within_at.of_succ h lemma cont_mdiff_on.of_succ {n : ℕ} (h : cont_mdiff_on I I' n.succ f s) : cont_mdiff_on I I' n f s := λ x hx, (h x hx).of_succ lemma cont_mdiff.of_succ {n : ℕ} (h : cont_mdiff I I' n.succ f) : cont_mdiff I I' n f := λ x, (h x).of_succ /-! ### Deducing continuity from smoothness -/ lemma cont_mdiff_within_at.continuous_within_at (hf : cont_mdiff_within_at I I' n f s x) : continuous_within_at f s x := hf.1 lemma cont_mdiff_at.continuous_at (hf : cont_mdiff_at I I' n f x) : continuous_at f x := (continuous_within_at_univ _ _ ).1 $ cont_mdiff_within_at.continuous_within_at hf lemma cont_mdiff_on.continuous_on (hf : cont_mdiff_on I I' n f s) : continuous_on f s := λ x hx, (hf x hx).continuous_within_at lemma cont_mdiff.continuous (hf : cont_mdiff I I' n f) : continuous f := continuous_iff_continuous_at.2 $ λ x, (hf x).continuous_at /-! ### Deducing differentiability from smoothness -/ lemma cont_mdiff_within_at.mdifferentiable_within_at (hf : cont_mdiff_within_at I I' n f s x) (hn : 1 ≤ n) : mdifferentiable_within_at I I' f s x := begin suffices h : mdifferentiable_within_at I I' f (s ∩ (f ⁻¹' (ext_chart_at I' (f x)).source)) x, { rwa mdifferentiable_within_at_inter' at h, apply (hf.1).preimage_mem_nhds_within, exact is_open.mem_nhds (ext_chart_at_open_source I' (f x)) (mem_ext_chart_source I' (f x)) }, rw mdifferentiable_within_at_iff, exact ⟨hf.1.mono (inter_subset_left _ _), (hf.2.differentiable_within_at hn).mono (by mfld_set_tac)⟩, end lemma cont_mdiff_at.mdifferentiable_at (hf : cont_mdiff_at I I' n f x) (hn : 1 ≤ n) : mdifferentiable_at I I' f x := mdifferentiable_within_at_univ.1 $ cont_mdiff_within_at.mdifferentiable_within_at hf hn lemma cont_mdiff_on.mdifferentiable_on (hf : cont_mdiff_on I I' n f s) (hn : 1 ≤ n) : mdifferentiable_on I I' f s := λ x hx, (hf x hx).mdifferentiable_within_at hn lemma cont_mdiff.mdifferentiable (hf : cont_mdiff I I' n f) (hn : 1 ≤ n) : mdifferentiable I I' f := λ x, (hf x).mdifferentiable_at hn lemma smooth.mdifferentiable (hf : smooth I I' f) : mdifferentiable I I' f := cont_mdiff.mdifferentiable hf le_top lemma smooth.mdifferentiable_at (hf : smooth I I' f) : mdifferentiable_at I I' f x := hf.mdifferentiable x lemma smooth.mdifferentiable_within_at (hf : smooth I I' f) : mdifferentiable_within_at I I' f s x := hf.mdifferentiable_at.mdifferentiable_within_at /-! ### `C^∞` smoothness -/ lemma cont_mdiff_within_at_top : smooth_within_at I I' f s x ↔ (∀n:ℕ, cont_mdiff_within_at I I' n f s x) := ⟨λ h n, ⟨h.1, cont_diff_within_at_top.1 h.2 n⟩, λ H, ⟨(H 0).1, cont_diff_within_at_top.2 (λ n, (H n).2)⟩⟩ lemma cont_mdiff_at_top : smooth_at I I' f x ↔ (∀n:ℕ, cont_mdiff_at I I' n f x) := cont_mdiff_within_at_top lemma cont_mdiff_on_top : smooth_on I I' f s ↔ (∀n:ℕ, cont_mdiff_on I I' n f s) := ⟨λ h n, h.of_le le_top, λ h x hx, cont_mdiff_within_at_top.2 (λ n, h n x hx)⟩ lemma cont_mdiff_top : smooth I I' f ↔ (∀n:ℕ, cont_mdiff I I' n f) := ⟨λ h n, h.of_le le_top, λ h x, cont_mdiff_within_at_top.2 (λ n, h n x)⟩ lemma cont_mdiff_within_at_iff_nat : cont_mdiff_within_at I I' n f s x ↔ (∀m:ℕ, (m : ℕ∞) ≤ n → cont_mdiff_within_at I I' m f s x) := begin refine ⟨λ h m hm, h.of_le hm, λ h, _⟩, cases n, { exact cont_mdiff_within_at_top.2 (λ n, h n le_top) }, { exact h n le_rfl } end /-! ### Restriction to a smaller set -/ lemma cont_mdiff_within_at.mono (hf : cont_mdiff_within_at I I' n f s x) (hts : t ⊆ s) : cont_mdiff_within_at I I' n f t x := structure_groupoid.local_invariant_prop.lift_prop_within_at_mono (cont_diff_within_at_prop_mono I I' n) hf hts lemma cont_mdiff_at.cont_mdiff_within_at (hf : cont_mdiff_at I I' n f x) : cont_mdiff_within_at I I' n f s x := cont_mdiff_within_at.mono hf (subset_univ _) lemma smooth_at.smooth_within_at (hf : smooth_at I I' f x) : smooth_within_at I I' f s x := cont_mdiff_at.cont_mdiff_within_at hf lemma cont_mdiff_on.mono (hf : cont_mdiff_on I I' n f s) (hts : t ⊆ s) : cont_mdiff_on I I' n f t := λ x hx, (hf x (hts hx)).mono hts lemma cont_mdiff.cont_mdiff_on (hf : cont_mdiff I I' n f) : cont_mdiff_on I I' n f s := λ x hx, (hf x).cont_mdiff_within_at lemma smooth.smooth_on (hf : smooth I I' f) : smooth_on I I' f s := cont_mdiff.cont_mdiff_on hf lemma cont_mdiff_within_at_inter' (ht : t ∈ 𝓝[s] x) : cont_mdiff_within_at I I' n f (s ∩ t) x ↔ cont_mdiff_within_at I I' n f s x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_inter' ht lemma cont_mdiff_within_at_inter (ht : t ∈ 𝓝 x) : cont_mdiff_within_at I I' n f (s ∩ t) x ↔ cont_mdiff_within_at I I' n f s x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_inter ht lemma cont_mdiff_within_at.cont_mdiff_at (h : cont_mdiff_within_at I I' n f s x) (ht : s ∈ 𝓝 x) : cont_mdiff_at I I' n f x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_at_of_lift_prop_within_at h ht lemma smooth_within_at.smooth_at (h : smooth_within_at I I' f s x) (ht : s ∈ 𝓝 x) : smooth_at I I' f x := cont_mdiff_within_at.cont_mdiff_at h ht lemma cont_mdiff_on.cont_mdiff_at (h : cont_mdiff_on I I' n f s) (hx : s ∈ 𝓝 x) : cont_mdiff_at I I' n f x := (h x (mem_of_mem_nhds hx)).cont_mdiff_at hx lemma smooth_on.smooth_at (h : smooth_on I I' f s) (hx : s ∈ 𝓝 x) : smooth_at I I' f x := h.cont_mdiff_at hx include Is lemma cont_mdiff_on_ext_chart_at : cont_mdiff_on I 𝓘(𝕜, E) n (ext_chart_at I x) (chart_at H x).source := λ x' hx', (cont_mdiff_at_ext_chart_at' hx').cont_mdiff_within_at include I's /-- A function is `C^n` within a set at a point, for `n : ℕ`, if and only if it is `C^n` on a neighborhood of this point. -/ lemma cont_mdiff_within_at_iff_cont_mdiff_on_nhds {n : ℕ} : cont_mdiff_within_at I I' n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, cont_mdiff_on I I' n f u := begin split, { assume h, -- the property is true in charts. We will pull such a good neighborhood in the chart to the -- manifold. For this, we need to restrict to a small enough set where everything makes sense obtain ⟨o, o_open, xo, ho, h'o⟩ : ∃ (o : set M), is_open o ∧ x ∈ o ∧ o ⊆ (chart_at H x).source ∧ o ∩ s ⊆ f ⁻¹' (chart_at H' (f x)).source, { have : (chart_at H' (f x)).source ∈ 𝓝 (f x) := is_open.mem_nhds (local_homeomorph.open_source _) (mem_chart_source H' (f x)), rcases mem_nhds_within.1 (h.1.preimage_mem_nhds_within this) with ⟨u, u_open, xu, hu⟩, refine ⟨u ∩ (chart_at H x).source, _, ⟨xu, mem_chart_source _ _⟩, _, _⟩, { exact is_open.inter u_open (local_homeomorph.open_source _) }, { assume y hy, exact hy.2 }, { assume y hy, exact hu ⟨hy.1.1, hy.2⟩ } }, have h' : cont_mdiff_within_at I I' n f (s ∩ o) x := h.mono (inter_subset_left _ _), simp only [cont_mdiff_within_at, lift_prop_within_at, cont_diff_within_at_prop] at h', -- let `u` be a good neighborhood in the chart where the function is smooth rcases h.2.cont_diff_on le_rfl with ⟨u, u_nhds, u_subset, hu⟩, -- pull it back to the manifold, and intersect with a suitable neighborhood of `x`, to get the -- desired good neighborhood `v`. let v := ((insert x s) ∩ o) ∩ (ext_chart_at I x) ⁻¹' u, have v_incl : v ⊆ (chart_at H x).source := λ y hy, ho hy.1.2, have v_incl' : ∀ y ∈ v, f y ∈ (chart_at H' (f x)).source, { assume y hy, rcases hy.1.1 with rfl|h', { simp only with mfld_simps }, { apply h'o ⟨hy.1.2, h'⟩ } }, refine ⟨v, _, _⟩, show v ∈ 𝓝[insert x s] x, { rw nhds_within_restrict _ xo o_open, refine filter.inter_mem self_mem_nhds_within _, suffices : u ∈ 𝓝[(ext_chart_at I x) '' (insert x s ∩ o)] (ext_chart_at I x x), from (ext_chart_at_continuous_at I x).continuous_within_at.preimage_mem_nhds_within' this, apply nhds_within_mono _ _ u_nhds, rw image_subset_iff, assume y hy, rcases hy.1 with rfl|h', { simp only [mem_insert_iff] with mfld_simps }, { simp only [mem_insert_iff, ho hy.2, h', h'o ⟨hy.2, h'⟩] with mfld_simps } }, show cont_mdiff_on I I' n f v, { assume y hy, have : continuous_within_at f v y, { apply (((ext_chart_at_continuous_on_symm I' (f x) _ _).comp' (hu _ hy.2).continuous_within_at).comp' (ext_chart_at_continuous_on I x _ _)).congr_mono, { assume z hz, simp only [v_incl hz, v_incl' z hz] with mfld_simps }, { assume z hz, simp only [v_incl hz, v_incl' z hz] with mfld_simps, exact hz.2 }, { simp only [v_incl hy, v_incl' y hy] with mfld_simps }, { simp only [v_incl hy, v_incl' y hy] with mfld_simps }, { simp only [v_incl hy] with mfld_simps } }, refine (cont_mdiff_within_at_iff_of_mem_source' (v_incl hy) (v_incl' y hy)).mpr ⟨this, _⟩, { apply hu.mono, { assume z hz, simp only [v] with mfld_simps at hz, have : I ((chart_at H x) (((chart_at H x).symm) (I.symm z))) ∈ u, by simp only [hz], simpa only [hz] with mfld_simps using this }, { have exty : I (chart_at H x y) ∈ u := hy.2, simp only [v_incl hy, v_incl' y hy, exty, hy.1.1, hy.1.2] with mfld_simps } } } }, { rintros ⟨u, u_nhds, hu⟩, have : cont_mdiff_within_at I I' ↑n f (insert x s ∩ u) x, { have : x ∈ insert x s := mem_insert x s, exact hu.mono (inter_subset_right _ _) _ ⟨this, mem_of_mem_nhds_within this u_nhds⟩ }, rw cont_mdiff_within_at_inter' u_nhds at this, exact this.mono (subset_insert x s) } end /-- A function is `C^n` at a point, for `n : ℕ`, if and only if it is `C^n` on a neighborhood of this point. -/ lemma cont_mdiff_at_iff_cont_mdiff_on_nhds {n : ℕ} : cont_mdiff_at I I' n f x ↔ ∃ u ∈ 𝓝 x, cont_mdiff_on I I' n f u := by simp [← cont_mdiff_within_at_univ, cont_mdiff_within_at_iff_cont_mdiff_on_nhds, nhds_within_univ] /-- Note: This does not hold for `n = ∞`. `f` being `C^∞` at `x` means that for every `n`, `f` is `C^n` on some neighborhood of `x`, but this neighborhood can depend on `n`. -/ lemma cont_mdiff_at_iff_cont_mdiff_at_nhds {n : ℕ} : cont_mdiff_at I I' n f x ↔ ∀ᶠ x' in 𝓝 x, cont_mdiff_at I I' n f x' := begin refine ⟨_, λ h, h.self_of_nhds⟩, rw [cont_mdiff_at_iff_cont_mdiff_on_nhds], rintro ⟨u, hu, h⟩, refine (eventually_mem_nhds.mpr hu).mono (λ x' hx', _), exact (h x' $ mem_of_mem_nhds hx').cont_mdiff_at hx' end omit Is I's /-! ### Congruence lemmas -/ lemma cont_mdiff_within_at.congr (h : cont_mdiff_within_at I I' n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : cont_mdiff_within_at I I' n f₁ s x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_congr h h₁ hx lemma cont_mdiff_within_at_congr (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : cont_mdiff_within_at I I' n f₁ s x ↔ cont_mdiff_within_at I I' n f s x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_congr_iff h₁ hx lemma cont_mdiff_within_at.congr_of_eventually_eq (h : cont_mdiff_within_at I I' n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : cont_mdiff_within_at I I' n f₁ s x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_within_at_congr_of_eventually_eq h h₁ hx lemma filter.eventually_eq.cont_mdiff_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : cont_mdiff_within_at I I' n f₁ s x ↔ cont_mdiff_within_at I I' n f s x := (cont_diff_within_at_local_invariant_prop I I' n) .lift_prop_within_at_congr_iff_of_eventually_eq h₁ hx lemma cont_mdiff_at.congr_of_eventually_eq (h : cont_mdiff_at I I' n f x) (h₁ : f₁ =ᶠ[𝓝 x] f) : cont_mdiff_at I I' n f₁ x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_at_congr_of_eventually_eq h h₁ lemma filter.eventually_eq.cont_mdiff_at_iff (h₁ : f₁ =ᶠ[𝓝 x] f) : cont_mdiff_at I I' n f₁ x ↔ cont_mdiff_at I I' n f x := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_at_congr_iff_of_eventually_eq h₁ lemma cont_mdiff_on.congr (h : cont_mdiff_on I I' n f s) (h₁ : ∀ y ∈ s, f₁ y = f y) : cont_mdiff_on I I' n f₁ s := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_on_congr h h₁ lemma cont_mdiff_on_congr (h₁ : ∀ y ∈ s, f₁ y = f y) : cont_mdiff_on I I' n f₁ s ↔ cont_mdiff_on I I' n f s := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_on_congr_iff h₁ /-! ### Locality -/ /-- Being `C^n` is a local property. -/ lemma cont_mdiff_on_of_locally_cont_mdiff_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ cont_mdiff_on I I' n f (s ∩ u)) : cont_mdiff_on I I' n f s := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_on_of_locally_lift_prop_on h lemma cont_mdiff_of_locally_cont_mdiff_on (h : ∀x, ∃u, is_open u ∧ x ∈ u ∧ cont_mdiff_on I I' n f u) : cont_mdiff I I' n f := (cont_diff_within_at_local_invariant_prop I I' n).lift_prop_of_locally_lift_prop_on h /-! ### Smoothness of the composition of smooth functions between manifolds -/ section composition variables {E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] /-- The composition of `C^n` functions within domains at points is `C^n`. -/ lemma cont_mdiff_within_at.comp {t : set M'} {g : M' → M''} (x : M) (hg : cont_mdiff_within_at I' I'' n g t (f x)) (hf : cont_mdiff_within_at I I' n f s x) (st : maps_to f s t) : cont_mdiff_within_at I I'' n (g ∘ f) s x := begin rw cont_mdiff_within_at_iff at hg hf ⊢, refine ⟨hg.1.comp hf.1 st, _⟩, set e := ext_chart_at I x, set e' := ext_chart_at I' (f x), set e'' := ext_chart_at I'' (g (f x)), have : e' (f x) = (written_in_ext_chart_at I I' x f) (e x), by simp only [e, e'] with mfld_simps, rw this at hg, have A : ∀ᶠ y in 𝓝[e.symm ⁻¹' s ∩ range I] e x, y ∈ e.target ∧ f (e.symm y) ∈ t ∧ f (e.symm y) ∈ e'.source ∧ g (f (e.symm y)) ∈ e''.source, { simp only [← ext_chart_at_map_nhds_within, eventually_map], filter_upwards [hf.1.tendsto (ext_chart_at_source_mem_nhds I' (f x)), (hg.1.comp hf.1 st).tendsto (ext_chart_at_source_mem_nhds I'' (g (f x))), (inter_mem_nhds_within s (ext_chart_at_source_mem_nhds I x))], rintros x' (hfx' : f x' ∈ _) (hgfx' : g (f x') ∈ _) ⟨hx's, hx'⟩, simp only [e.map_source hx', true_and, e.left_inv hx', st hx's, *] }, refine ((hg.2.comp _ (hf.2.mono (inter_subset_right _ _)) (inter_subset_left _ _)).mono_of_mem (inter_mem _ self_mem_nhds_within)).congr_of_eventually_eq _ _, { filter_upwards [A], rintro x' ⟨hx', ht, hfx', hgfx'⟩, simp only [*, mem_preimage, written_in_ext_chart_at, (∘), mem_inter_eq, e'.left_inv, true_and], exact mem_range_self _ }, { filter_upwards [A], rintro x' ⟨hx', ht, hfx', hgfx'⟩, simp only [*, (∘), written_in_ext_chart_at, e'.left_inv] }, { simp only [written_in_ext_chart_at, (∘), mem_ext_chart_source, e.left_inv, e'.left_inv] } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma cont_mdiff_on.comp {t : set M'} {g : M' → M''} (hg : cont_mdiff_on I' I'' n g t) (hf : cont_mdiff_on I I' n f s) (st : s ⊆ f ⁻¹' t) : cont_mdiff_on I I'' n (g ∘ f) s := λ x hx, (hg _ (st hx)).comp x (hf x hx) st /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma cont_mdiff_on.comp' {t : set M'} {g : M' → M''} (hg : cont_mdiff_on I' I'' n g t) (hf : cont_mdiff_on I I' n f s) : cont_mdiff_on I I'' n (g ∘ f) (s ∩ f ⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of `C^n` functions is `C^n`. -/ lemma cont_mdiff.comp {g : M' → M''} (hg : cont_mdiff I' I'' n g) (hf : cont_mdiff I I' n f) : cont_mdiff I I'' n (g ∘ f) := begin rw ← cont_mdiff_on_univ at hf hg ⊢, exact hg.comp hf subset_preimage_univ, end /-- The composition of `C^n` functions within domains at points is `C^n`. -/ lemma cont_mdiff_within_at.comp' {t : set M'} {g : M' → M''} (x : M) (hg : cont_mdiff_within_at I' I'' n g t (f x)) (hf : cont_mdiff_within_at I I' n f s x) : cont_mdiff_within_at I I'' n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- `g ∘ f` is `C^n` within `s` at `x` if `g` is `C^n` at `f x` and `f` is `C^n` within `s` at `x`. -/ lemma cont_mdiff_at.comp_cont_mdiff_within_at {g : M' → M''} (x : M) (hg : cont_mdiff_at I' I'' n g (f x)) (hf : cont_mdiff_within_at I I' n f s x) : cont_mdiff_within_at I I'' n (g ∘ f) s x := hg.comp x hf (maps_to_univ _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma cont_mdiff_at.comp {g : M' → M''} (x : M) (hg : cont_mdiff_at I' I'' n g (f x)) (hf : cont_mdiff_at I I' n f x) : cont_mdiff_at I I'' n (g ∘ f) x := hg.comp x hf (maps_to_univ _ _) lemma cont_mdiff.comp_cont_mdiff_on {f : M → M'} {g : M' → M''} {s : set M} (hg : cont_mdiff I' I'' n g) (hf : cont_mdiff_on I I' n f s) : cont_mdiff_on I I'' n (g ∘ f) s := hg.cont_mdiff_on.comp hf set.subset_preimage_univ lemma smooth.comp_smooth_on {f : M → M'} {g : M' → M''} {s : set M} (hg : smooth I' I'' g) (hf : smooth_on I I' f s) : smooth_on I I'' (g ∘ f) s := hg.smooth_on.comp hf set.subset_preimage_univ lemma cont_mdiff_on.comp_cont_mdiff {t : set M'} {g : M' → M''} (hg : cont_mdiff_on I' I'' n g t) (hf : cont_mdiff I I' n f) (ht : ∀ x, f x ∈ t) : cont_mdiff I I'' n (g ∘ f) := cont_mdiff_on_univ.mp $ hg.comp hf.cont_mdiff_on (λ x _, ht x) lemma smooth_on.comp_smooth {t : set M'} {g : M' → M''} (hg : smooth_on I' I'' g t) (hf : smooth I I' f) (ht : ∀ x, f x ∈ t) : smooth I I'' (g ∘ f) := hg.comp_cont_mdiff hf ht end composition /-! ### Atlas members are smooth -/ section atlas variables {e : local_homeomorph M H} include Is /-- An atlas member is `C^n` for any `n`. -/ lemma cont_mdiff_on_of_mem_maximal_atlas (h : e ∈ maximal_atlas I M) : cont_mdiff_on I I n e e.source := cont_mdiff_on.of_le ((cont_diff_within_at_local_invariant_prop I I ∞).lift_prop_on_of_mem_maximal_atlas (cont_diff_within_at_prop_id I) h) le_top /-- The inverse of an atlas member is `C^n` for any `n`. -/ lemma cont_mdiff_on_symm_of_mem_maximal_atlas (h : e ∈ maximal_atlas I M) : cont_mdiff_on I I n e.symm e.target := cont_mdiff_on.of_le ((cont_diff_within_at_local_invariant_prop I I ∞).lift_prop_on_symm_of_mem_maximal_atlas (cont_diff_within_at_prop_id I) h) le_top lemma cont_mdiff_on_chart : cont_mdiff_on I I n (chart_at H x) (chart_at H x).source := cont_mdiff_on_of_mem_maximal_atlas ((cont_diff_groupoid ⊤ I).chart_mem_maximal_atlas x) lemma cont_mdiff_on_chart_symm : cont_mdiff_on I I n (chart_at H x).symm (chart_at H x).target := cont_mdiff_on_symm_of_mem_maximal_atlas ((cont_diff_groupoid ⊤ I).chart_mem_maximal_atlas x) end atlas /-! ### The identity is smooth -/ section id lemma cont_mdiff_id : cont_mdiff I I n (id : M → M) := cont_mdiff.of_le ((cont_diff_within_at_local_invariant_prop I I ∞).lift_prop_id (cont_diff_within_at_prop_id I)) le_top lemma smooth_id : smooth I I (id : M → M) := cont_mdiff_id lemma cont_mdiff_on_id : cont_mdiff_on I I n (id : M → M) s := cont_mdiff_id.cont_mdiff_on lemma smooth_on_id : smooth_on I I (id : M → M) s := cont_mdiff_on_id lemma cont_mdiff_at_id : cont_mdiff_at I I n (id : M → M) x := cont_mdiff_id.cont_mdiff_at lemma smooth_at_id : smooth_at I I (id : M → M) x := cont_mdiff_at_id lemma cont_mdiff_within_at_id : cont_mdiff_within_at I I n (id : M → M) s x := cont_mdiff_at_id.cont_mdiff_within_at lemma smooth_within_at_id : smooth_within_at I I (id : M → M) s x := cont_mdiff_within_at_id end id /-! ### Constants are smooth -/ section id variable {c : M'} lemma cont_mdiff_const : cont_mdiff I I' n (λ (x : M), c) := begin assume x, refine ⟨continuous_within_at_const, _⟩, simp only [cont_diff_within_at_prop, (∘)], exact cont_diff_within_at_const, end @[to_additive] lemma cont_mdiff_one [has_one M'] : cont_mdiff I I' n (1 : M → M') := by simp only [pi.one_def, cont_mdiff_const] lemma smooth_const : smooth I I' (λ (x : M), c) := cont_mdiff_const @[to_additive] lemma smooth_one [has_one M'] : smooth I I' (1 : M → M') := by simp only [pi.one_def, smooth_const] lemma cont_mdiff_on_const : cont_mdiff_on I I' n (λ (x : M), c) s := cont_mdiff_const.cont_mdiff_on @[to_additive] lemma cont_mdiff_on_one [has_one M'] : cont_mdiff_on I I' n (1 : M → M') s := cont_mdiff_one.cont_mdiff_on lemma smooth_on_const : smooth_on I I' (λ (x : M), c) s := cont_mdiff_on_const @[to_additive] lemma smooth_on_one [has_one M'] : smooth_on I I' (1 : M → M') s := cont_mdiff_on_one lemma cont_mdiff_at_const : cont_mdiff_at I I' n (λ (x : M), c) x := cont_mdiff_const.cont_mdiff_at @[to_additive] lemma cont_mdiff_at_one [has_one M'] : cont_mdiff_at I I' n (1 : M → M') x := cont_mdiff_one.cont_mdiff_at lemma smooth_at_const : smooth_at I I' (λ (x : M), c) x := cont_mdiff_at_const @[to_additive] lemma smooth_at_one [has_one M'] : smooth_at I I' (1 : M → M') x := cont_mdiff_at_one lemma cont_mdiff_within_at_const : cont_mdiff_within_at I I' n (λ (x : M), c) s x := cont_mdiff_at_const.cont_mdiff_within_at @[to_additive] lemma cont_mdiff_within_at_one [has_one M'] : cont_mdiff_within_at I I' n (1 : M → M') s x := cont_mdiff_at_const.cont_mdiff_within_at lemma smooth_within_at_const : smooth_within_at I I' (λ (x : M), c) s x := cont_mdiff_within_at_const @[to_additive] lemma smooth_within_at_one [has_one M'] : smooth_within_at I I' (1 : M → M') s x := cont_mdiff_within_at_one end id lemma cont_mdiff_of_support {f : M → F} (hf : ∀ x ∈ tsupport f, cont_mdiff_at I 𝓘(𝕜, F) n f x) : cont_mdiff I 𝓘(𝕜, F) n f := begin intro x, by_cases hx : x ∈ tsupport f, { exact hf x hx }, { refine cont_mdiff_at.congr_of_eventually_eq _ (eventually_eq_zero_nhds.2 hx), exact cont_mdiff_at_const } end /-! ### Equivalence with the basic definition for functions between vector spaces -/ section module lemma cont_mdiff_within_at_iff_cont_diff_within_at {f : E → E'} {s : set E} {x : E} : cont_mdiff_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') n f s x ↔ cont_diff_within_at 𝕜 n f s x := begin simp only [cont_mdiff_within_at, lift_prop_within_at, cont_diff_within_at_prop, iff_def] with mfld_simps {contextual := tt}, exact cont_diff_within_at.continuous_within_at end alias cont_mdiff_within_at_iff_cont_diff_within_at ↔ cont_mdiff_within_at.cont_diff_within_at cont_diff_within_at.cont_mdiff_within_at lemma cont_mdiff_at_iff_cont_diff_at {f : E → E'} {x : E} : cont_mdiff_at 𝓘(𝕜, E) 𝓘(𝕜, E') n f x ↔ cont_diff_at 𝕜 n f x := by rw [← cont_mdiff_within_at_univ, cont_mdiff_within_at_iff_cont_diff_within_at, cont_diff_within_at_univ] alias cont_mdiff_at_iff_cont_diff_at ↔ cont_mdiff_at.cont_diff_at cont_diff_at.cont_mdiff_at lemma cont_mdiff_on_iff_cont_diff_on {f : E → E'} {s : set E} : cont_mdiff_on 𝓘(𝕜, E) 𝓘(𝕜, E') n f s ↔ cont_diff_on 𝕜 n f s := forall_congr $ by simp [cont_mdiff_within_at_iff_cont_diff_within_at] alias cont_mdiff_on_iff_cont_diff_on ↔ cont_mdiff_on.cont_diff_on cont_diff_on.cont_mdiff_on lemma cont_mdiff_iff_cont_diff {f : E → E'} : cont_mdiff 𝓘(𝕜, E) 𝓘(𝕜, E') n f ↔ cont_diff 𝕜 n f := by rw [← cont_diff_on_univ, ← cont_mdiff_on_univ, cont_mdiff_on_iff_cont_diff_on] alias cont_mdiff_iff_cont_diff ↔ cont_mdiff.cont_diff cont_diff.cont_mdiff end module /-! ### The tangent map of a smooth function is smooth -/ section tangent_map /-- If a function is `C^n` with `1 ≤ n` on a domain with unique derivatives, then its bundled derivative is continuous. In this auxiliary lemma, we prove this fact when the source and target space are model spaces in models with corners. The general fact is proved in `cont_mdiff_on.continuous_on_tangent_map_within`-/ lemma cont_mdiff_on.continuous_on_tangent_map_within_aux {f : H → H'} {s : set H} (hf : cont_mdiff_on I I' n f s) (hn : 1 ≤ n) (hs : unique_mdiff_on I s) : continuous_on (tangent_map_within I I' f s) ((tangent_bundle.proj I H) ⁻¹' s) := begin suffices h : continuous_on (λ (p : H × E), (f p.fst, (fderiv_within 𝕜 (written_in_ext_chart_at I I' p.fst f) (I.symm ⁻¹' s ∩ range I) ((ext_chart_at I p.fst) p.fst) : E →L[𝕜] E') p.snd)) (prod.fst ⁻¹' s), { have A := (tangent_bundle_model_space_homeomorph H I).continuous, rw continuous_iff_continuous_on_univ at A, have B := ((tangent_bundle_model_space_homeomorph H' I').symm.continuous.comp_continuous_on h) .comp' A, have : (univ ∩ ⇑(tangent_bundle_model_space_homeomorph H I) ⁻¹' (prod.fst ⁻¹' s)) = tangent_bundle.proj I H ⁻¹' s, by { ext ⟨x, v⟩, simp only with mfld_simps }, rw this at B, apply B.congr, rintros ⟨x, v⟩ hx, dsimp [tangent_map_within], ext, { refl }, simp only with mfld_simps, apply congr_fun, apply congr_arg, rw mdifferentiable_within_at.mfderiv_within (hf.mdifferentiable_on hn x hx), refl }, suffices h : continuous_on (λ (p : H × E), (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I p.fst) : E →L[𝕜] E') p.snd) (prod.fst ⁻¹' s), { dsimp [written_in_ext_chart_at, ext_chart_at], apply continuous_on.prod (continuous_on.comp hf.continuous_on continuous_fst.continuous_on (subset.refl _)), apply h.congr, assume p hp, refl }, suffices h : continuous_on (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I)) (I '' s), { have C := continuous_on.comp h I.continuous_to_fun.continuous_on (subset.refl _), have A : continuous (λq : (E →L[𝕜] E') × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : H × E, (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) (I p.1), p.2)) (prod.fst ⁻¹' s), { apply continuous_on.prod _ continuous_snd.continuous_on, refine (continuous_on.comp C continuous_fst.continuous_on _ : _), exact preimage_mono (subset_preimage_image _ _) }, exact A.comp_continuous_on B }, rw cont_mdiff_on_iff at hf, let x : H := I.symm (0 : E), let y : H' := I'.symm (0 : E'), have A := hf.2 x y, simp only [I.image_eq, inter_comm] with mfld_simps at A ⊢, apply A.continuous_on_fderiv_within _ hn, convert hs.unique_diff_on_target_inter x using 1, simp only [inter_comm] with mfld_simps end /-- If a function is `C^n` on a domain with unique derivatives, then its bundled derivative is `C^m` when `m+1 ≤ n`. In this auxiliary lemma, we prove this fact when the source and target space are model spaces in models with corners. The general fact is proved in `cont_mdiff_on.cont_mdiff_on_tangent_map_within` -/ lemma cont_mdiff_on.cont_mdiff_on_tangent_map_within_aux {f : H → H'} {s : set H} (hf : cont_mdiff_on I I' n f s) (hmn : m + 1 ≤ n) (hs : unique_mdiff_on I s) : cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' f s) ((tangent_bundle.proj I H) ⁻¹' s) := begin have m_le_n : m ≤ n, { apply le_trans _ hmn, have : m + 0 ≤ m + 1 := add_le_add_left (zero_le _) _, simpa only [add_zero] using this }, have one_le_n : 1 ≤ n, { apply le_trans _ hmn, change 0 + 1 ≤ m + 1, exact add_le_add_right (zero_le _) _ }, have U': unique_diff_on 𝕜 (range I ∩ I.symm ⁻¹' s), { assume y hy, simpa only [unique_mdiff_on, unique_mdiff_within_at, hy.1, inter_comm] with mfld_simps using hs (I.symm y) hy.2 }, rw cont_mdiff_on_iff, refine ⟨hf.continuous_on_tangent_map_within_aux one_le_n hs, λp q, _⟩, have A : range I ×ˢ univ ∩ ((equiv.sigma_equiv_prod H E).symm ∘ λ (p : E × E), ((I.symm) p.fst, p.snd)) ⁻¹' (tangent_bundle.proj I H ⁻¹' s) = (range I ∩ I.symm ⁻¹' s) ×ˢ univ, by { ext ⟨x, v⟩, simp only with mfld_simps }, suffices h : cont_diff_on 𝕜 m (((λ (p : H' × E'), (I' p.fst, p.snd)) ∘ (equiv.sigma_equiv_prod H' E')) ∘ tangent_map_within I I' f s ∘ ((equiv.sigma_equiv_prod H E).symm) ∘ λ (p : E × E), (I.symm p.fst, p.snd)) ((range ⇑I ∩ ⇑(I.symm) ⁻¹' s) ×ˢ univ), by simpa [A] using h, change cont_diff_on 𝕜 m (λ (p : E × E), ((I' (f (I.symm p.fst)), ((mfderiv_within I I' f s (I.symm p.fst)) : E → E') p.snd) : E' × E')) ((range I ∩ I.symm ⁻¹' s) ×ˢ univ), -- check that all bits in this formula are `C^n` have hf' := cont_mdiff_on_iff.1 hf, have A : cont_diff_on 𝕜 m (I' ∘ f ∘ I.symm) (range I ∩ I.symm ⁻¹' s) := by simpa only with mfld_simps using (hf'.2 (I.symm 0) (I'.symm 0)).of_le m_le_n, have B : cont_diff_on 𝕜 m ((I' ∘ f ∘ I.symm) ∘ prod.fst) ((range I ∩ I.symm ⁻¹' s) ×ˢ univ) := A.comp (cont_diff_fst.cont_diff_on) (prod_subset_preimage_fst _ _), suffices C : cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) p.1 : _) p.2)) ((range I ∩ I.symm ⁻¹' s) ×ˢ univ), { apply cont_diff_on.prod B _, apply C.congr (λp hp, _), simp only with mfld_simps at hp, simp only [mfderiv_within, hf.mdifferentiable_on one_le_n _ hp.2, hp.1, dif_pos] with mfld_simps }, have D : cont_diff_on 𝕜 m (λ x, (fderiv_within 𝕜 (I' ∘ f ∘ I.symm) (I.symm ⁻¹' s ∩ range I) x)) (range I ∩ I.symm ⁻¹' s), { have : cont_diff_on 𝕜 n (I' ∘ f ∘ I.symm) (range I ∩ I.symm ⁻¹' s) := by simpa only with mfld_simps using (hf'.2 (I.symm 0) (I'.symm 0)), simpa only [inter_comm] using this.fderiv_within U' hmn }, have := D.comp (cont_diff_fst.cont_diff_on) (prod_subset_preimage_fst _ _), have := cont_diff_on.prod this (cont_diff_snd.cont_diff_on), exact is_bounded_bilinear_map_apply.cont_diff.comp_cont_diff_on this, end include Is I's /-- If a function is `C^n` on a domain with unique derivatives, then its bundled derivative is `C^m` when `m+1 ≤ n`. -/ theorem cont_mdiff_on.cont_mdiff_on_tangent_map_within (hf : cont_mdiff_on I I' n f s) (hmn : m + 1 ≤ n) (hs : unique_mdiff_on I s) : cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' f s) ((tangent_bundle.proj I M) ⁻¹' s) := begin /- The strategy of the proof is to avoid unfolding the definitions, and reduce by functoriality to the case of functions on the model spaces, where we have already proved the result. Let `l` and `r` be the charts to the left and to the right, so that we have ``` l^{-1} f r H --------> M ---> M' ---> H' ``` Then the tangent map `T(r ∘ f ∘ l)` is smooth by a previous result. Consider the composition ``` Tl T(r ∘ f ∘ l^{-1}) Tr^{-1} TM -----> TH -------------------> TH' ---------> TM' ``` where `Tr^{-1}` and `Tl` are the tangent maps of `r^{-1}` and `l`. Writing `Tl` and `Tr^{-1}` as composition of charts (called `Dl` and `il` for `l` and `Dr` and `ir` in the proof below), it follows that they are smooth. The composition of all these maps is `Tf`, and is therefore smooth as a composition of smooth maps. -/ have m_le_n : m ≤ n, { apply le_trans _ hmn, have : m + 0 ≤ m + 1 := add_le_add_left (zero_le _) _, simpa only [add_zero] }, have one_le_n : 1 ≤ n, { apply le_trans _ hmn, change 0 + 1 ≤ m + 1, exact add_le_add_right (zero_le _) _ }, /- First step: local reduction on the space, to a set `s'` which is contained in chart domains. -/ refine cont_mdiff_on_of_locally_cont_mdiff_on (λp hp, _), have hf' := cont_mdiff_on_iff.1 hf, simp [tangent_bundle.proj] at hp, let l := chart_at H p.1, set Dl := chart_at (model_prod H E) p with hDl, let r := chart_at H' (f p.1), let Dr := chart_at (model_prod H' E') (tangent_map_within I I' f s p), let il := chart_at (model_prod H E) (tangent_map I I l p), let ir := chart_at (model_prod H' E') (tangent_map I I' (r ∘ f) p), let s' := f ⁻¹' r.source ∩ s ∩ l.source, let s'_lift := (tangent_bundle.proj I M)⁻¹' s', let s'l := l.target ∩ l.symm ⁻¹' s', let s'l_lift := (tangent_bundle.proj I H) ⁻¹' s'l, rcases continuous_on_iff'.1 hf'.1 r.source r.open_source with ⟨o, o_open, ho⟩, suffices h : cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' f s) s'_lift, { refine ⟨(tangent_bundle.proj I M)⁻¹' (o ∩ l.source), _, _, _⟩, show is_open ((tangent_bundle.proj I M)⁻¹' (o ∩ l.source)), from (is_open.inter o_open l.open_source).preimage (tangent_bundle_proj_continuous _ _) , show p ∈ tangent_bundle.proj I M ⁻¹' (o ∩ l.source), { simp [tangent_bundle.proj] at ⊢, have : p.1 ∈ f ⁻¹' r.source ∩ s, by simp [hp], rw ho at this, exact this.1 }, { have : tangent_bundle.proj I M ⁻¹' s ∩ tangent_bundle.proj I M ⁻¹' (o ∩ l.source) = s'_lift, { dsimp only [s'_lift, s'], rw [ho], mfld_set_tac }, rw this, exact h } }, /- Second step: check that all functions are smooth, and use the chain rule to write the bundled derivative as a composition of a function between model spaces and of charts. Convention: statements about the differentiability of `a ∘ b ∘ c` are named `diff_abc`. Statements about differentiability in the bundle have a `_lift` suffix. -/ have U' : unique_mdiff_on I s', { apply unique_mdiff_on.inter _ l.open_source, rw [ho, inter_comm], exact hs.inter o_open }, have U'l : unique_mdiff_on I s'l := U'.unique_mdiff_on_preimage (mdifferentiable_chart _ _), have diff_f : cont_mdiff_on I I' n f s' := hf.mono (by mfld_set_tac), have diff_r : cont_mdiff_on I' I' n r r.source := cont_mdiff_on_chart, have diff_rf : cont_mdiff_on I I' n (r ∘ f) s', { apply cont_mdiff_on.comp diff_r diff_f (λx hx, _), simp only [s'] with mfld_simps at hx, simp only [hx] with mfld_simps }, have diff_l : cont_mdiff_on I I n l.symm s'l, { have A : cont_mdiff_on I I n l.symm l.target := cont_mdiff_on_chart_symm, exact A.mono (by mfld_set_tac) }, have diff_rfl : cont_mdiff_on I I' n (r ∘ f ∘ l.symm) s'l, { apply cont_mdiff_on.comp diff_rf diff_l, mfld_set_tac }, have diff_rfl_lift : cont_mdiff_on I.tangent I'.tangent m (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l) s'l_lift := diff_rfl.cont_mdiff_on_tangent_map_within_aux hmn U'l, have diff_irrfl_lift : cont_mdiff_on I.tangent I'.tangent m (ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l)) s'l_lift, { have A : cont_mdiff_on I'.tangent I'.tangent m ir ir.source := cont_mdiff_on_chart, exact cont_mdiff_on.comp A diff_rfl_lift (λp hp, by simp only [ir] with mfld_simps) }, have diff_Drirrfl_lift : cont_mdiff_on I.tangent I'.tangent m (Dr.symm ∘ (ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l))) s'l_lift, { have A : cont_mdiff_on I'.tangent I'.tangent m Dr.symm Dr.target := cont_mdiff_on_chart_symm, apply cont_mdiff_on.comp A diff_irrfl_lift (λp hp, _), simp only [s'l_lift, tangent_bundle.proj] with mfld_simps at hp, simp only [ir, @local_equiv.refl_coe (model_prod H' E'), hp] with mfld_simps }, -- conclusion of this step: the composition of all the maps above is smooth have diff_DrirrflilDl : cont_mdiff_on I.tangent I'.tangent m (Dr.symm ∘ (ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l)) ∘ (il.symm ∘ Dl)) s'_lift, { have A : cont_mdiff_on I.tangent I.tangent m Dl Dl.source := cont_mdiff_on_chart, have A' : cont_mdiff_on I.tangent I.tangent m Dl s'_lift, { apply A.mono (λp hp, _), simp only [s'_lift, tangent_bundle.proj] with mfld_simps at hp, simp only [Dl, hp] with mfld_simps }, have B : cont_mdiff_on I.tangent I.tangent m il.symm il.target := cont_mdiff_on_chart_symm, have C : cont_mdiff_on I.tangent I.tangent m (il.symm ∘ Dl) s'_lift := cont_mdiff_on.comp B A' (λp hp, by simp only [il] with mfld_simps), apply cont_mdiff_on.comp diff_Drirrfl_lift C (λp hp, _), simp only [s'_lift, tangent_bundle.proj] with mfld_simps at hp, simp only [il, s'l_lift, hp, tangent_bundle.proj] with mfld_simps }, /- Third step: check that the composition of all the maps indeed coincides with the derivative we are looking for -/ have eq_comp : ∀q ∈ s'_lift, tangent_map_within I I' f s q = (Dr.symm ∘ ir ∘ (tangent_map_within I I' (r ∘ f ∘ l.symm) s'l) ∘ (il.symm ∘ Dl)) q, { assume q hq, simp only [s'_lift, tangent_bundle.proj] with mfld_simps at hq, have U'q : unique_mdiff_within_at I s' q.1, by { apply U', simp only [hq, s'] with mfld_simps }, have U'lq : unique_mdiff_within_at I s'l (Dl q).1, by { apply U'l, simp only [hq, s'l] with mfld_simps }, have A : tangent_map_within I I' ((r ∘ f) ∘ l.symm) s'l (il.symm (Dl q)) = tangent_map_within I I' (r ∘ f) s' (tangent_map_within I I l.symm s'l (il.symm (Dl q))), { refine tangent_map_within_comp_at (il.symm (Dl q)) _ _ (λp hp, _) U'lq, { apply diff_rf.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, { apply diff_l.mdifferentiable_on one_le_n, simp only [s'l, hq] with mfld_simps }, { simp only with mfld_simps at hp, simp only [hp] with mfld_simps } }, have B : tangent_map_within I I l.symm s'l (il.symm (Dl q)) = q, { have : tangent_map_within I I l.symm s'l (il.symm (Dl q)) = tangent_map I I l.symm (il.symm (Dl q)), { refine tangent_map_within_eq_tangent_map U'lq _, refine mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) _, simp only [hq] with mfld_simps }, rw [this, tangent_map_chart_symm, hDl], { simp only [hq] with mfld_simps, have : q ∈ (chart_at (model_prod H E) p).source, by simp only [hq] with mfld_simps, exact (chart_at (model_prod H E) p).left_inv this }, { simp only [hq] with mfld_simps } }, have C : tangent_map_within I I' (r ∘ f) s' q = tangent_map_within I' I' r r.source (tangent_map_within I I' f s' q), { refine tangent_map_within_comp_at q _ _ (λr hr, _) U'q, { apply diff_r.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, { apply diff_f.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, { simp only [s'] with mfld_simps at hr, simp only [hr] with mfld_simps } }, have D : Dr.symm (ir (tangent_map_within I' I' r r.source (tangent_map_within I I' f s' q))) = tangent_map_within I I' f s' q, { have A : tangent_map_within I' I' r r.source (tangent_map_within I I' f s' q) = tangent_map I' I' r (tangent_map_within I I' f s' q), { apply tangent_map_within_eq_tangent_map, { apply is_open.unique_mdiff_within_at _ r.open_source, simp [hq] }, { refine mdifferentiable_at_atlas _ (chart_mem_atlas _ _) _, simp only [hq] with mfld_simps } }, have : f p.1 = (tangent_map_within I I' f s p).1 := rfl, rw [A], dsimp [r, Dr], rw [this, tangent_map_chart], { simp only [hq] with mfld_simps, have : tangent_map_within I I' f s' q ∈ (chart_at (model_prod H' E') (tangent_map_within I I' f s p)).source, by simp only [hq] with mfld_simps, exact (chart_at (model_prod H' E') (tangent_map_within I I' f s p)).left_inv this }, { simp only [hq] with mfld_simps } }, have E : tangent_map_within I I' f s' q = tangent_map_within I I' f s q, { refine tangent_map_within_subset (by mfld_set_tac) U'q _, apply hf.mdifferentiable_on one_le_n, simp only [hq] with mfld_simps }, simp only [(∘), A, B, C, D, E.symm] }, exact diff_DrirrflilDl.congr eq_comp, end /-- If a function is `C^n` on a domain with unique derivatives, with `1 ≤ n`, then its bundled derivative is continuous there. -/ theorem cont_mdiff_on.continuous_on_tangent_map_within (hf : cont_mdiff_on I I' n f s) (hmn : 1 ≤ n) (hs : unique_mdiff_on I s) : continuous_on (tangent_map_within I I' f s) ((tangent_bundle.proj I M) ⁻¹' s) := begin have : cont_mdiff_on I.tangent I'.tangent 0 (tangent_map_within I I' f s) ((tangent_bundle.proj I M) ⁻¹' s) := hf.cont_mdiff_on_tangent_map_within hmn hs, exact this.continuous_on end /-- If a function is `C^n`, then its bundled derivative is `C^m` when `m+1 ≤ n`. -/ theorem cont_mdiff.cont_mdiff_tangent_map (hf : cont_mdiff I I' n f) (hmn : m + 1 ≤ n) : cont_mdiff I.tangent I'.tangent m (tangent_map I I' f) := begin rw ← cont_mdiff_on_univ at hf ⊢, convert hf.cont_mdiff_on_tangent_map_within hmn unique_mdiff_on_univ, rw tangent_map_within_univ end /-- If a function is `C^n`, with `1 ≤ n`, then its bundled derivative is continuous. -/ theorem cont_mdiff.continuous_tangent_map (hf : cont_mdiff I I' n f) (hmn : 1 ≤ n) : continuous (tangent_map I I' f) := begin rw ← cont_mdiff_on_univ at hf, rw continuous_iff_continuous_on_univ, convert hf.continuous_on_tangent_map_within hmn unique_mdiff_on_univ, rw tangent_map_within_univ end end tangent_map /-! ### Smoothness of the projection in a basic smooth bundle -/ namespace basic_smooth_vector_bundle_core variables (Z : basic_smooth_vector_bundle_core I M E') /-- A version of `cont_mdiff_at_iff_target` when the codomain is the total space of a `basic_smooth_vector_bundle_core`. The continuity condition in the RHS is weaker. -/ lemma cont_mdiff_at_iff_target {f : N → Z.to_topological_vector_bundle_core.total_space} {x : N} {n : ℕ∞} : cont_mdiff_at J (I.prod 𝓘(𝕜, E')) n f x ↔ continuous_at (bundle.total_space.proj ∘ f) x ∧ cont_mdiff_at J 𝓘(𝕜, E × E') n (ext_chart_at (I.prod 𝓘(𝕜, E')) (f x) ∘ f) x := begin let Z' := Z.to_topological_vector_bundle_core, rw [cont_mdiff_at_iff_target, and.congr_left_iff], refine λ hf, ⟨λ h, Z'.continuous_proj.continuous_at.comp h, λ h, _⟩, exact (Z'.local_triv ⟨chart_at _ (f x).1, chart_mem_atlas _ _⟩).to_fiber_bundle_trivialization .continuous_at_of_comp_left h (mem_chart_source _ _) (h.prod hf.continuous_at.snd) end lemma cont_mdiff_proj : cont_mdiff (I.prod 𝓘(𝕜, E')) I n Z.to_topological_vector_bundle_core.proj := begin assume x, rw [cont_mdiff_at, cont_mdiff_within_at_iff'], refine ⟨Z.to_topological_vector_bundle_core.continuous_proj.continuous_within_at, _⟩, simp only [(∘), chart_at, chart] with mfld_simps, apply cont_diff_within_at_fst.congr, { rintros ⟨a, b⟩ hab, simp only with mfld_simps at hab, simp only [hab] with mfld_simps }, { simp only with mfld_simps } end lemma smooth_proj : smooth (I.prod 𝓘(𝕜, E')) I Z.to_topological_vector_bundle_core.proj := cont_mdiff_proj Z lemma cont_mdiff_on_proj {s : set (Z.to_topological_vector_bundle_core.total_space)} : cont_mdiff_on (I.prod 𝓘(𝕜, E')) I n Z.to_topological_vector_bundle_core.proj s := Z.cont_mdiff_proj.cont_mdiff_on lemma smooth_on_proj {s : set (Z.to_topological_vector_bundle_core.total_space)} : smooth_on (I.prod 𝓘(𝕜, E')) I Z.to_topological_vector_bundle_core.proj s := cont_mdiff_on_proj Z lemma cont_mdiff_at_proj {p : Z.to_topological_vector_bundle_core.total_space} : cont_mdiff_at (I.prod 𝓘(𝕜, E')) I n Z.to_topological_vector_bundle_core.proj p := Z.cont_mdiff_proj.cont_mdiff_at lemma smooth_at_proj {p : Z.to_topological_vector_bundle_core.total_space} : smooth_at (I.prod 𝓘(𝕜, E')) I Z.to_topological_vector_bundle_core.proj p := Z.cont_mdiff_at_proj lemma cont_mdiff_within_at_proj {s : set (Z.to_topological_vector_bundle_core.total_space)} {p : Z.to_topological_vector_bundle_core.total_space} : cont_mdiff_within_at (I.prod 𝓘(𝕜, E')) I n Z.to_topological_vector_bundle_core.proj s p := Z.cont_mdiff_at_proj.cont_mdiff_within_at lemma smooth_within_at_proj {s : set (Z.to_topological_vector_bundle_core.total_space)} {p : Z.to_topological_vector_bundle_core.total_space} : smooth_within_at (I.prod 𝓘(𝕜, E')) I Z.to_topological_vector_bundle_core.proj s p := Z.cont_mdiff_within_at_proj /-- If an element of `E'` is invariant under all coordinate changes, then one can define a corresponding section of the fiber bundle, which is smooth. This applies in particular to the zero section of a vector bundle. Another example (not yet defined) would be the identity section of the endomorphism bundle of a vector bundle. -/ lemma smooth_const_section (v : E') (h : ∀ (i j : atlas H M), ∀ x ∈ i.1.source ∩ j.1.source, Z.coord_change i j (i.1 x) v = v) : smooth I (I.prod 𝓘(𝕜, E')) (show M → Z.to_topological_vector_bundle_core.total_space, from λ x, ⟨x, v⟩) := begin assume x, rw [cont_mdiff_at, cont_mdiff_within_at_iff'], split, { apply continuous.continuous_within_at, apply topological_fiber_bundle_core.continuous_const_section, assume i j y hy, exact h _ _ _ hy }, { have : cont_diff 𝕜 ⊤ (λ (y : E), (y, v)) := cont_diff_id.prod cont_diff_const, apply this.cont_diff_within_at.congr, { assume y hy, simp only with mfld_simps at hy, simp only [chart, hy, chart_at, prod.mk.inj_iff, to_topological_vector_bundle_core] with mfld_simps, apply h, simp only [hy, subtype.val_eq_coe] with mfld_simps, exact mem_chart_source H (((chart_at H x).symm) ((model_with_corners.symm I) y)) }, { simp only [chart, chart_at, prod.mk.inj_iff, to_topological_vector_bundle_core] with mfld_simps, apply h, simp only [subtype.val_eq_coe] with mfld_simps, exact mem_chart_source H x, } } end end basic_smooth_vector_bundle_core /-! ### Smoothness of the tangent bundle projection -/ namespace tangent_bundle include Is lemma cont_mdiff_proj : cont_mdiff I.tangent I n (proj I M) := basic_smooth_vector_bundle_core.cont_mdiff_proj _ lemma smooth_proj : smooth I.tangent I (proj I M) := basic_smooth_vector_bundle_core.smooth_proj _ lemma cont_mdiff_on_proj {s : set (tangent_bundle I M)} : cont_mdiff_on I.tangent I n (proj I M) s := basic_smooth_vector_bundle_core.cont_mdiff_on_proj _ lemma smooth_on_proj {s : set (tangent_bundle I M)} : smooth_on I.tangent I (proj I M) s := basic_smooth_vector_bundle_core.smooth_on_proj _ lemma cont_mdiff_at_proj {p : tangent_bundle I M} : cont_mdiff_at I.tangent I n (proj I M) p := basic_smooth_vector_bundle_core.cont_mdiff_at_proj _ lemma smooth_at_proj {p : tangent_bundle I M} : smooth_at I.tangent I (proj I M) p := basic_smooth_vector_bundle_core.smooth_at_proj _ lemma cont_mdiff_within_at_proj {s : set (tangent_bundle I M)} {p : tangent_bundle I M} : cont_mdiff_within_at I.tangent I n (proj I M) s p := basic_smooth_vector_bundle_core.cont_mdiff_within_at_proj _ lemma smooth_within_at_proj {s : set (tangent_bundle I M)} {p : tangent_bundle I M} : smooth_within_at I.tangent I (proj I M) s p := basic_smooth_vector_bundle_core.smooth_within_at_proj _ variables (I M) /-- The zero section of the tangent bundle -/ def zero_section : M → tangent_bundle I M := λ x, ⟨x, 0⟩ variables {I M} lemma smooth_zero_section : smooth I I.tangent (zero_section I M) := begin apply basic_smooth_vector_bundle_core.smooth_const_section (tangent_bundle_core I M) 0, assume i j x hx, simp only [tangent_bundle_core, continuous_linear_map.map_zero, continuous_linear_map.coe_coe] with mfld_simps, end open bundle /-- The derivative of the zero section of the tangent bundle maps `⟨x, v⟩` to `⟨⟨x, 0⟩, ⟨v, 0⟩⟩`. Note that, as currently framed, this is a statement in coordinates, thus reliant on the choice of the coordinate system we use on the tangent bundle. However, the result itself is coordinate-dependent only to the extent that the coordinates determine a splitting of the tangent bundle. Moreover, there is a canonical splitting at each point of the zero section (since there is a canonical horizontal space there, the tangent space to the zero section, in addition to the canonical vertical space which is the kernel of the derivative of the projection), and this canonical splitting is also the one that comes from the coordinates on the tangent bundle in our definitions. So this statement is not as crazy as it may seem. TODO define splittings of vector bundles; state this result invariantly. -/ lemma tangent_map_tangent_bundle_pure (p : tangent_bundle I M) : tangent_map I I.tangent (tangent_bundle.zero_section I M) p = ⟨⟨p.1, 0⟩, ⟨p.2, 0⟩⟩ := begin rcases p with ⟨x, v⟩, have N : I.symm ⁻¹' (chart_at H x).target ∈ 𝓝 (I ((chart_at H x) x)), { apply is_open.mem_nhds, apply (local_homeomorph.open_target _).preimage I.continuous_inv_fun, simp only with mfld_simps }, have A : mdifferentiable_at I I.tangent (λ x, @total_space_mk M (tangent_space I) x 0) x := tangent_bundle.smooth_zero_section.mdifferentiable_at, have B : fderiv_within 𝕜 (λ (x_1 : E), (x_1, (0 : E))) (set.range ⇑I) (I ((chart_at H x) x)) v = (v, 0), { rw [fderiv_within_eq_fderiv, differentiable_at.fderiv_prod], { simp }, { exact differentiable_at_id' }, { exact differentiable_at_const _ }, { exact model_with_corners.unique_diff_at_image I }, { exact differentiable_at_id'.prod (differentiable_at_const _) } }, simp only [tangent_bundle.zero_section, tangent_map, mfderiv, A, dif_pos, chart_at, basic_smooth_vector_bundle_core.chart, basic_smooth_vector_bundle_core.to_topological_vector_bundle_core, tangent_bundle_core, function.comp, continuous_linear_map.map_zero] with mfld_simps, rw ← fderiv_within_inter N (I.unique_diff (I ((chart_at H x) x)) (set.mem_range_self _)) at B, rw [← fderiv_within_inter N (I.unique_diff (I ((chart_at H x) x)) (set.mem_range_self _)), ← B], congr' 2, apply fderiv_within_congr _ (λ y hy, _), { simp only [prod.mk.inj_iff] with mfld_simps, exact ((tangent_bundle_core I M).to_topological_vector_bundle_core.coord_change ((tangent_bundle_core I M).to_topological_vector_bundle_core.index_at (((chart_at H x).symm) (I.symm (I ((chart_at H x) x))))) ⟨chart_at H x, _⟩ (((chart_at H x).symm) (I.symm (I ((chart_at H x) x))))).map_zero, }, { apply unique_diff_within_at.inter (I.unique_diff _ _) N, simp only with mfld_simps }, { simp only with mfld_simps at hy, simp only [hy, prod.mk.inj_iff] with mfld_simps, exact ((tangent_bundle_core I M).to_topological_vector_bundle_core.coord_change ((tangent_bundle_core I M).to_topological_vector_bundle_core.index_at (((chart_at H x).symm) (I.symm y))) ⟨chart_at H x, _⟩ (((chart_at H x).symm) (I.symm y))).map_zero, }, end end tangent_bundle /-! ### Smoothness of standard maps associated to the product of manifolds -/ section prod_mk lemma cont_mdiff_within_at.prod_mk {f : M → M'} {g : M → N'} (hf : cont_mdiff_within_at I I' n f s x) (hg : cont_mdiff_within_at I J' n g s x) : cont_mdiff_within_at I (I'.prod J') n (λ x, (f x, g x)) s x := begin rw cont_mdiff_within_at_iff at *, exact ⟨hf.1.prod hg.1, hf.2.prod hg.2⟩, end lemma cont_mdiff_within_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : cont_mdiff_within_at I 𝓘(𝕜, E') n f s x) (hg : cont_mdiff_within_at I 𝓘(𝕜, F') n g s x) : cont_mdiff_within_at I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) s x := begin rw cont_mdiff_within_at_iff at *, exact ⟨hf.1.prod hg.1, hf.2.prod hg.2⟩, end lemma cont_mdiff_at.prod_mk {f : M → M'} {g : M → N'} (hf : cont_mdiff_at I I' n f x) (hg : cont_mdiff_at I J' n g x) : cont_mdiff_at I (I'.prod J') n (λ x, (f x, g x)) x := hf.prod_mk hg lemma cont_mdiff_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : cont_mdiff_at I 𝓘(𝕜, E') n f x) (hg : cont_mdiff_at I 𝓘(𝕜, F') n g x) : cont_mdiff_at I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) x := hf.prod_mk_space hg lemma cont_mdiff_on.prod_mk {f : M → M'} {g : M → N'} (hf : cont_mdiff_on I I' n f s) (hg : cont_mdiff_on I J' n g s) : cont_mdiff_on I (I'.prod J') n (λ x, (f x, g x)) s := λ x hx, (hf x hx).prod_mk (hg x hx) lemma cont_mdiff_on.prod_mk_space {f : M → E'} {g : M → F'} (hf : cont_mdiff_on I 𝓘(𝕜, E') n f s) (hg : cont_mdiff_on I 𝓘(𝕜, F') n g s) : cont_mdiff_on I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) s := λ x hx, (hf x hx).prod_mk_space (hg x hx) lemma cont_mdiff.prod_mk {f : M → M'} {g : M → N'} (hf : cont_mdiff I I' n f) (hg : cont_mdiff I J' n g) : cont_mdiff I (I'.prod J') n (λ x, (f x, g x)) := λ x, (hf x).prod_mk (hg x) lemma cont_mdiff.prod_mk_space {f : M → E'} {g : M → F'} (hf : cont_mdiff I 𝓘(𝕜, E') n f) (hg : cont_mdiff I 𝓘(𝕜, F') n g) : cont_mdiff I 𝓘(𝕜, E' × F') n (λ x, (f x, g x)) := λ x, (hf x).prod_mk_space (hg x) lemma smooth_within_at.prod_mk {f : M → M'} {g : M → N'} (hf : smooth_within_at I I' f s x) (hg : smooth_within_at I J' g s x) : smooth_within_at I (I'.prod J') (λ x, (f x, g x)) s x := hf.prod_mk hg lemma smooth_within_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth_within_at I 𝓘(𝕜, E') f s x) (hg : smooth_within_at I 𝓘(𝕜, F') g s x) : smooth_within_at I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) s x := hf.prod_mk_space hg lemma smooth_at.prod_mk {f : M → M'} {g : M → N'} (hf : smooth_at I I' f x) (hg : smooth_at I J' g x) : smooth_at I (I'.prod J') (λ x, (f x, g x)) x := hf.prod_mk hg lemma smooth_at.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth_at I 𝓘(𝕜, E') f x) (hg : smooth_at I 𝓘(𝕜, F') g x) : smooth_at I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) x := hf.prod_mk_space hg lemma smooth_on.prod_mk {f : M → M'} {g : M → N'} (hf : smooth_on I I' f s) (hg : smooth_on I J' g s) : smooth_on I (I'.prod J') (λ x, (f x, g x)) s := hf.prod_mk hg lemma smooth_on.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth_on I 𝓘(𝕜, E') f s) (hg : smooth_on I 𝓘(𝕜, F') g s) : smooth_on I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) s := hf.prod_mk_space hg lemma smooth.prod_mk {f : M → M'} {g : M → N'} (hf : smooth I I' f) (hg : smooth I J' g) : smooth I (I'.prod J') (λ x, (f x, g x)) := hf.prod_mk hg lemma smooth.prod_mk_space {f : M → E'} {g : M → F'} (hf : smooth I 𝓘(𝕜, E') f) (hg : smooth I 𝓘(𝕜, F') g) : smooth I 𝓘(𝕜, E' × F') (λ x, (f x, g x)) := hf.prod_mk_space hg end prod_mk section projections lemma cont_mdiff_within_at_fst {s : set (M × N)} {p : M × N} : cont_mdiff_within_at (I.prod J) I n prod.fst s p := begin rw cont_mdiff_within_at_iff', refine ⟨continuous_within_at_fst, _⟩, refine cont_diff_within_at_fst.congr (λ y hy, _) _, { simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, { simp only with mfld_simps } end lemma cont_mdiff_at_fst {p : M × N} : cont_mdiff_at (I.prod J) I n prod.fst p := cont_mdiff_within_at_fst lemma cont_mdiff_on_fst {s : set (M × N)} : cont_mdiff_on (I.prod J) I n prod.fst s := λ x hx, cont_mdiff_within_at_fst lemma cont_mdiff_fst : cont_mdiff (I.prod J) I n (@prod.fst M N) := λ x, cont_mdiff_at_fst lemma smooth_within_at_fst {s : set (M × N)} {p : M × N} : smooth_within_at (I.prod J) I prod.fst s p := cont_mdiff_within_at_fst lemma smooth_at_fst {p : M × N} : smooth_at (I.prod J) I prod.fst p := cont_mdiff_at_fst lemma smooth_on_fst {s : set (M × N)} : smooth_on (I.prod J) I prod.fst s := cont_mdiff_on_fst lemma smooth_fst : smooth (I.prod J) I (@prod.fst M N) := cont_mdiff_fst lemma cont_mdiff_within_at_snd {s : set (M × N)} {p : M × N} : cont_mdiff_within_at (I.prod J) J n prod.snd s p := begin rw cont_mdiff_within_at_iff', refine ⟨continuous_within_at_snd, _⟩, refine cont_diff_within_at_snd.congr (λ y hy, _) _, { simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, { simp only with mfld_simps } end lemma cont_mdiff_at_snd {p : M × N} : cont_mdiff_at (I.prod J) J n prod.snd p := cont_mdiff_within_at_snd lemma cont_mdiff_on_snd {s : set (M × N)} : cont_mdiff_on (I.prod J) J n prod.snd s := λ x hx, cont_mdiff_within_at_snd lemma cont_mdiff_snd : cont_mdiff (I.prod J) J n (@prod.snd M N) := λ x, cont_mdiff_at_snd lemma smooth_within_at_snd {s : set (M × N)} {p : M × N} : smooth_within_at (I.prod J) J prod.snd s p := cont_mdiff_within_at_snd lemma smooth_at_snd {p : M × N} : smooth_at (I.prod J) J prod.snd p := cont_mdiff_at_snd lemma smooth_on_snd {s : set (M × N)} : smooth_on (I.prod J) J prod.snd s := cont_mdiff_on_snd lemma smooth_snd : smooth (I.prod J) J (@prod.snd M N) := cont_mdiff_snd lemma smooth_iff_proj_smooth {f : M → M' × N'} : (smooth I (I'.prod J') f) ↔ (smooth I I' (prod.fst ∘ f)) ∧ (smooth I J' (prod.snd ∘ f)) := begin split, { intro h, exact ⟨smooth_fst.comp h, smooth_snd.comp h⟩ }, { rintro ⟨h_fst, h_snd⟩, simpa only [prod.mk.eta] using h_fst.prod_mk h_snd, } end end projections section prod_map variables {g : N → N'} {r : set N} {y : N} /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_mdiff_within_at.prod_map' {p : M × N} (hf : cont_mdiff_within_at I I' n f s p.1) (hg : cont_mdiff_within_at J J' n g r p.2) : cont_mdiff_within_at (I.prod J) (I'.prod J') n (prod.map f g) (s ×ˢ r) p := (hf.comp p cont_mdiff_within_at_fst (prod_subset_preimage_fst _ _)).prod_mk $ hg.comp p cont_mdiff_within_at_snd (prod_subset_preimage_snd _ _) lemma cont_mdiff_within_at.prod_map (hf : cont_mdiff_within_at I I' n f s x) (hg : cont_mdiff_within_at J J' n g r y) : cont_mdiff_within_at (I.prod J) (I'.prod J') n (prod.map f g) (s ×ˢ r) (x, y) := cont_mdiff_within_at.prod_map' hf hg lemma cont_mdiff_at.prod_map (hf : cont_mdiff_at I I' n f x) (hg : cont_mdiff_at J J' n g y) : cont_mdiff_at (I.prod J) (I'.prod J') n (prod.map f g) (x, y) := begin rw ← cont_mdiff_within_at_univ at *, convert hf.prod_map hg, exact univ_prod_univ.symm end lemma cont_mdiff_at.prod_map' {p : M × N} (hf : cont_mdiff_at I I' n f p.1) (hg : cont_mdiff_at J J' n g p.2) : cont_mdiff_at (I.prod J) (I'.prod J') n (prod.map f g) p := begin rcases p, exact hf.prod_map hg end lemma cont_mdiff_on.prod_map (hf : cont_mdiff_on I I' n f s) (hg : cont_mdiff_on J J' n g r) : cont_mdiff_on (I.prod J) (I'.prod J') n (prod.map f g) (s ×ˢ r) := (hf.comp cont_mdiff_on_fst (prod_subset_preimage_fst _ _)).prod_mk $ hg.comp (cont_mdiff_on_snd) (prod_subset_preimage_snd _ _) lemma cont_mdiff.prod_map (hf : cont_mdiff I I' n f) (hg : cont_mdiff J J' n g) : cont_mdiff (I.prod J) (I'.prod J') n (prod.map f g) := begin assume p, exact (hf p.1).prod_map' (hg p.2) end lemma smooth_within_at.prod_map (hf : smooth_within_at I I' f s x) (hg : smooth_within_at J J' g r y) : smooth_within_at (I.prod J) (I'.prod J') (prod.map f g) (s ×ˢ r) (x, y) := hf.prod_map hg lemma smooth_at.prod_map (hf : smooth_at I I' f x) (hg : smooth_at J J' g y) : smooth_at (I.prod J) (I'.prod J') (prod.map f g) (x, y) := hf.prod_map hg lemma smooth_on.prod_map (hf : smooth_on I I' f s) (hg : smooth_on J J' g r) : smooth_on (I.prod J) (I'.prod J') (prod.map f g) (s ×ˢ r) := hf.prod_map hg lemma smooth.prod_map (hf : smooth I I' f) (hg : smooth J J' g) : smooth (I.prod J) (I'.prod J') (prod.map f g) := hf.prod_map hg end prod_map section pi_space /-! ### Smoothness of functions with codomain `Π i, F i` We have no `model_with_corners.pi` yet, so we prove lemmas about functions `f : M → Π i, F i` and use `𝓘(𝕜, Π i, F i)` as the model space. -/ variables {ι : Type*} [fintype ι] {Fi : ι → Type*} [Π i, normed_add_comm_group (Fi i)] [Π i, normed_space 𝕜 (Fi i)] {φ : M → Π i, Fi i} lemma cont_mdiff_within_at_pi_space : cont_mdiff_within_at I (𝓘(𝕜, Π i, Fi i)) n φ s x ↔ ∀ i, cont_mdiff_within_at I (𝓘(𝕜, Fi i)) n (λ x, φ x i) s x := by simp only [cont_mdiff_within_at_iff, continuous_within_at_pi, cont_diff_within_at_pi, forall_and_distrib, written_in_ext_chart_at, ext_chart_model_space_eq_id, (∘), local_equiv.refl_coe, id] lemma cont_mdiff_on_pi_space : cont_mdiff_on I (𝓘(𝕜, Π i, Fi i)) n φ s ↔ ∀ i, cont_mdiff_on I (𝓘(𝕜, Fi i)) n (λ x, φ x i) s := ⟨λ h i x hx, cont_mdiff_within_at_pi_space.1 (h x hx) i, λ h x hx, cont_mdiff_within_at_pi_space.2 (λ i, h i x hx)⟩ lemma cont_mdiff_at_pi_space : cont_mdiff_at I (𝓘(𝕜, Π i, Fi i)) n φ x ↔ ∀ i, cont_mdiff_at I (𝓘(𝕜, Fi i)) n (λ x, φ x i) x := cont_mdiff_within_at_pi_space lemma cont_mdiff_pi_space : cont_mdiff I (𝓘(𝕜, Π i, Fi i)) n φ ↔ ∀ i, cont_mdiff I (𝓘(𝕜, Fi i)) n (λ x, φ x i) := ⟨λ h i x, cont_mdiff_at_pi_space.1 (h x) i, λ h x, cont_mdiff_at_pi_space.2 (λ i, h i x)⟩ lemma smooth_within_at_pi_space : smooth_within_at I (𝓘(𝕜, Π i, Fi i)) φ s x ↔ ∀ i, smooth_within_at I (𝓘(𝕜, Fi i)) (λ x, φ x i) s x := cont_mdiff_within_at_pi_space lemma smooth_on_pi_space : smooth_on I (𝓘(𝕜, Π i, Fi i)) φ s ↔ ∀ i, smooth_on I (𝓘(𝕜, Fi i)) (λ x, φ x i) s := cont_mdiff_on_pi_space lemma smooth_at_pi_space : smooth_at I (𝓘(𝕜, Π i, Fi i)) φ x ↔ ∀ i, smooth_at I (𝓘(𝕜, Fi i)) (λ x, φ x i) x := cont_mdiff_at_pi_space lemma smooth_pi_space : smooth I (𝓘(𝕜, Π i, Fi i)) φ ↔ ∀ i, smooth I (𝓘(𝕜, Fi i)) (λ x, φ x i) := cont_mdiff_pi_space end pi_space /-! ### Linear maps between normed spaces are smooth -/ lemma continuous_linear_map.cont_mdiff (L : E →L[𝕜] F) : cont_mdiff 𝓘(𝕜, E) 𝓘(𝕜, F) n L := L.cont_diff.cont_mdiff /-! ### Smoothness of standard operations -/ variables {V : Type*} [normed_add_comm_group V] [normed_space 𝕜 V] /-- On any vector space, multiplication by a scalar is a smooth operation. -/ lemma smooth_smul : smooth (𝓘(𝕜).prod 𝓘(𝕜, V)) 𝓘(𝕜, V) (λp : 𝕜 × V, p.1 • p.2) := smooth_iff.2 ⟨continuous_smul, λ x y, cont_diff_smul.cont_diff_on⟩ lemma cont_mdiff_within_at.smul {f : M → 𝕜} {g : M → V} (hf : cont_mdiff_within_at I 𝓘(𝕜) n f s x) (hg : cont_mdiff_within_at I 𝓘(𝕜, V) n g s x) : cont_mdiff_within_at I 𝓘(𝕜, V) n (λ p, f p • g p) s x := (smooth_smul.of_le le_top).cont_mdiff_at.comp_cont_mdiff_within_at x (hf.prod_mk hg) lemma cont_mdiff_at.smul {f : M → 𝕜} {g : M → V} (hf : cont_mdiff_at I 𝓘(𝕜) n f x) (hg : cont_mdiff_at I 𝓘(𝕜, V) n g x) : cont_mdiff_at I 𝓘(𝕜, V) n (λ p, f p • g p) x := hf.smul hg lemma cont_mdiff_on.smul {f : M → 𝕜} {g : M → V} (hf : cont_mdiff_on I 𝓘(𝕜) n f s) (hg : cont_mdiff_on I 𝓘(𝕜, V) n g s) : cont_mdiff_on I 𝓘(𝕜, V) n (λ p, f p • g p) s := λ x hx, (hf x hx).smul (hg x hx) lemma cont_mdiff.smul {f : M → 𝕜} {g : M → V} (hf : cont_mdiff I 𝓘(𝕜) n f) (hg : cont_mdiff I 𝓘(𝕜, V) n g) : cont_mdiff I 𝓘(𝕜, V) n (λ p, f p • g p) := λ x, (hf x).smul (hg x) lemma smooth_within_at.smul {f : M → 𝕜} {g : M → V} (hf : smooth_within_at I 𝓘(𝕜) f s x) (hg : smooth_within_at I 𝓘(𝕜, V) g s x) : smooth_within_at I 𝓘(𝕜, V) (λ p, f p • g p) s x := hf.smul hg lemma smooth_at.smul {f : M → 𝕜} {g : M → V} (hf : smooth_at I 𝓘(𝕜) f x) (hg : smooth_at I 𝓘(𝕜, V) g x) : smooth_at I 𝓘(𝕜, V) (λ p, f p • g p) x := hf.smul hg lemma smooth_on.smul {f : M → 𝕜} {g : M → V} (hf : smooth_on I 𝓘(𝕜) f s) (hg : smooth_on I 𝓘(𝕜, V) g s) : smooth_on I 𝓘(𝕜, V) (λ p, f p • g p) s := hf.smul hg lemma smooth.smul {f : M → 𝕜} {g : M → V} (hf : smooth I 𝓘(𝕜) f) (hg : smooth I 𝓘(𝕜, V) g) : smooth I 𝓘(𝕜, V) (λ p, f p • g p) := hf.smul hg
6d68220135e630aa35821453eb4387d8361bb5f8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/orientation.lean
ebc1425acc5d6dc7554b75860afeac820e11038d
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
28,617
lean
/- Copyright (c) 2021 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.determinant /-! # Orientations of modules and rays in modules This file defines rays in modules and orientations of modules. ## Main definitions * `module.ray` is a type for the equivalence class of nonzero vectors in a module with some common positive multiple. * `orientation` is a type synonym for `module.ray` for the case where the module is that of alternating maps from a module to its underlying ring. An orientation may be associated with an alternating map or with a basis. * `module.oriented` is a type class for a choice of orientation of a module that is considered the positive orientation. ## Implementation notes `orientation` is defined for an arbitrary index type, but the main intended use case is when that index type is a `fintype` and there exists a basis of the same cardinality. ## References * https://en.wikipedia.org/wiki/Orientation_(vector_space) -/ noncomputable theory open_locale big_operators section ordered_comm_semiring variables (R : Type*) [ordered_comm_semiring R] variables {M : Type*} [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] variables (ι : Type*) [decidable_eq ι] /-- Two vectors are in the same ray if some positive multiples of them are equal (in the typical case over a field, this means each is a positive multiple of the other). Over a field, this is equivalent to `mul_action.orbit_rel`. -/ def same_ray (v₁ v₂ : M) : Prop := ∃ (r₁ r₂ : R), 0 < r₁ ∧ 0 < r₂ ∧ r₁ • v₁ = r₂ • v₂ variables {R} /-- `same_ray` is reflexive. -/ @[refl] lemma same_ray.refl [nontrivial R] (x : M) : same_ray R x x := ⟨1, 1, zero_lt_one, zero_lt_one, rfl⟩ /-- `same_ray` is symmetric. -/ @[symm] lemma same_ray.symm {x y : M} : same_ray R x y → same_ray R y x := λ ⟨r₁, r₂, hr₁, hr₂, h⟩, ⟨r₂, r₁, hr₂, hr₁, h.symm⟩ /-- `same_ray` is transitive. -/ @[trans] lemma same_ray.trans {x y z : M} : same_ray R x y → same_ray R y z → same_ray R x z := λ ⟨r₁, r₂, hr₁, hr₂, h₁⟩ ⟨r₃, r₄, hr₃, hr₄, h₂⟩, ⟨r₃ * r₁, r₂ * r₄, mul_pos hr₃ hr₁, mul_pos hr₂ hr₄, by rw [mul_smul, mul_smul, h₁, ←h₂, smul_comm]⟩ lemma same_ray_comm {x y : M} : same_ray R x y ↔ same_ray R y x := ⟨same_ray.symm, same_ray.symm⟩ variables (R M) /-- `same_ray` is an equivalence relation. -/ lemma equivalence_same_ray [nontrivial R] : equivalence (same_ray R : M → M → Prop) := ⟨same_ray.refl, λ _ _, same_ray.symm, λ _ _ _, same_ray.trans⟩ variables {R M} /-- A vector is in the same ray as a positive multiple of itself. -/ lemma same_ray_pos_smul_right (v : M) {r : R} (h : 0 < r) : same_ray R v (r • v) := ⟨r, 1, h, let f := nontrivial_of_lt _ _ h in by exactI zero_lt_one, (one_smul _ _).symm⟩ /-- A vector is in the same ray as a positive multiple of one it is in the same ray as. -/ lemma same_ray.pos_smul_right {v₁ v₂ : M} {r : R} (h : same_ray R v₁ v₂) (hr : 0 < r) : same_ray R v₁ (r • v₂) := h.trans (same_ray_pos_smul_right v₂ hr) /-- A positive multiple of a vector is in the same ray as that vector. -/ lemma same_ray_pos_smul_left (v : M) {r : R} (h : 0 < r) : same_ray R (r • v) v := ⟨1, r, let f := nontrivial_of_lt _ _ h in by exactI zero_lt_one, h, one_smul _ _⟩ /-- A positive multiple of a vector is in the same ray as one it is in the same ray as. -/ lemma same_ray.pos_smul_left {v₁ v₂ : M} {r : R} (h : same_ray R v₁ v₂) (hr : 0 < r) : same_ray R (r • v₁) v₂ := (same_ray_pos_smul_left v₁ hr).trans h /-- If two vectors are on the same ray then they remain so after appling a linear map. -/ lemma same_ray.map {v₁ v₂ : M} (f : M →ₗ[R] N) (h : same_ray R v₁ v₂) : same_ray R (f v₁) (f v₂) := let ⟨r₁, r₂, hr₁, hr₂, h⟩ := h in ⟨r₁, r₂, hr₁, hr₂, by rw [←f.map_smul, ←f.map_smul, h]⟩ /-- If two vectors are on the same ray then they remain so after appling a linear equivalence. -/ @[simp] lemma same_ray_map_iff {v₁ v₂ : M} (e : M ≃ₗ[R] N) : same_ray R (e v₁) (e v₂) ↔ same_ray R v₁ v₂ := ⟨λ h, by simpa using same_ray.map e.symm.to_linear_map h, same_ray.map e.to_linear_map⟩ /-- If two vectors are on the same ray then both scaled by the same action are also on the same ray. -/ lemma same_ray.smul {S : Type*} [has_scalar S M] [smul_comm_class R S M] {v₁ v₂ : M} (s : S) (h : same_ray R v₁ v₂) : same_ray R (s • v₁) (s • v₂) := let ⟨r₁, r₂, hr₁, hr₂, h⟩ := h in ⟨r₁, r₂, hr₁, hr₂, by rw [smul_comm r₁ s v₁, smul_comm r₂ s v₂, h]⟩ variables (R M) /-- The setoid of the `same_ray` relation for elements of a module. -/ def same_ray_setoid [nontrivial R] : setoid M := { r := same_ray R, iseqv := equivalence_same_ray R M } /-- Nonzero vectors, as used to define rays. -/ @[reducible] def ray_vector := {v : M // v ≠ 0} /-- The setoid of the `same_ray` relation for the subtype of nonzero vectors. -/ def ray_vector.same_ray_setoid [nontrivial R] : setoid (ray_vector M) := (same_ray_setoid R M).comap coe local attribute [instance] ray_vector.same_ray_setoid variables {R M} /-- Equivalence of nonzero vectors, in terms of same_ray. -/ lemma equiv_iff_same_ray [nontrivial R] (v₁ v₂ : ray_vector M) : v₁ ≈ v₂ ↔ same_ray R (v₁ : M) v₂ := iff.rfl variables (R M) /-- A ray (equivalence class of nonzero vectors with common positive multiples) in a module. -/ @[nolint has_inhabited_instance] def module.ray [nontrivial R] := quotient (ray_vector.same_ray_setoid R M) /-- An orientation of a module, intended to be used when `ι` is a `fintype` with the same cardinality as a basis. -/ abbreviation orientation [nontrivial R] := module.ray R (alternating_map R M R ι) /-- A type class fixing an orientation of a module. -/ class module.oriented [nontrivial R] := (positive_orientation : orientation R M ι) variables {M} /-- The ray given by a nonzero vector. -/ protected def ray_of_ne_zero [nontrivial R] (v : M) (h : v ≠ 0) : module.ray R M := ⟦⟨v, h⟩⟧ /-- An induction principle for `module.ray`, used as `induction x using module.ray.ind`. -/ lemma module.ray.ind [nontrivial R] {C : module.ray R M → Prop} (h : Π v (hv : v ≠ 0), C (ray_of_ne_zero R v hv)) (x : module.ray R M) : C x := quotient.ind (subtype.rec $ by exact h) x /-- The rays given by two nonzero vectors are equal if and only if those vectors satisfy `same_ray`. -/ lemma ray_eq_iff [nontrivial R] {v₁ v₂ : M} (hv₁ : v₁ ≠ 0) (hv₂ : v₂ ≠ 0) : ray_of_ne_zero R _ hv₁ = ray_of_ne_zero R _ hv₂ ↔ same_ray R v₁ v₂ := quotient.eq variables {R} /-- The ray given by a positive multiple of a nonzero vector. -/ @[simp] lemma ray_pos_smul [nontrivial R] {v : M} (h : v ≠ 0) {r : R} (hr : 0 < r) (hrv : r • v ≠ 0) : ray_of_ne_zero R _ hrv = ray_of_ne_zero R _ h := begin rw ray_eq_iff, exact same_ray_pos_smul_left v hr end /-- An equivalence between modules implies an equivalence between ray vectors. -/ def ray_vector.map_linear_equiv (e : M ≃ₗ[R] N) : ray_vector M ≃ ray_vector N := equiv.subtype_equiv e.to_equiv $ λ _, e.map_ne_zero_iff.symm /-- An equivalence between modules implies an equivalence between rays. -/ def module.ray.map [nontrivial R] (e : M ≃ₗ[R] N) : module.ray R M ≃ module.ray R N := quotient.congr (ray_vector.map_linear_equiv e) $ λ ⟨a, ha⟩ ⟨b, hb⟩, (same_ray_map_iff _).symm @[simp] lemma module.ray.map_apply [nontrivial R] (e : M ≃ₗ[R] N) (v : M) (hv : v ≠ 0) : module.ray.map e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (e v) (e.map_ne_zero_iff.2 hv) := rfl @[simp] lemma module.ray.map_refl [nontrivial R] : (module.ray.map $ linear_equiv.refl R M) = equiv.refl _ := equiv.ext $ module.ray.ind R $ λ _ _, rfl @[simp] lemma module.ray.map_symm [nontrivial R] (e : M ≃ₗ[R] N) : (module.ray.map e).symm = module.ray.map e.symm := rfl /-- An equivalence between modules implies an equivalence between orientations. -/ def orientation.map [nontrivial R] (e : M ≃ₗ[R] N) : orientation R M ι ≃ orientation R N ι := module.ray.map $ alternating_map.dom_lcongr R R ι R e @[simp] lemma orientation.map_apply [nontrivial R] (e : M ≃ₗ[R] N) (v : alternating_map R M R ι) (hv : v ≠ 0) : orientation.map ι e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (v.comp_linear_map e.symm) (mt (v.comp_linear_equiv_eq_zero_iff e.symm).mp hv) := rfl @[simp] lemma orientation.map_refl [nontrivial R] : (orientation.map ι $ linear_equiv.refl R M) = equiv.refl _ := by rw [orientation.map, alternating_map.dom_lcongr_refl, module.ray.map_refl] @[simp] lemma orientation.map_symm [nontrivial R] (e : M ≃ₗ[R] N) : (orientation.map ι e).symm = orientation.map ι e.symm := rfl section action variables {G : Type*} [group G] [nontrivial R] [distrib_mul_action G M] [smul_comm_class R G M] /-- Any invertible action preserves the non-zeroness of ray vectors. This is primarily of interest when `G = Rˣ` -/ instance : mul_action G (ray_vector M) := { smul := λ r, (subtype.map ((•) r) $ λ a, (smul_ne_zero_iff_ne _).2), mul_smul := λ a b m, subtype.ext $ mul_smul a b _, one_smul := λ m, subtype.ext $ one_smul _ _ } /-- Any invertible action preserves the non-zeroness of rays. This is primarily of interest when `G = Rˣ` -/ instance : mul_action G (module.ray R M) := { smul := λ r, quotient.map ((•) r) (λ a b, same_ray.smul _), mul_smul := λ a b, quotient.ind $ by exact(λ m, congr_arg quotient.mk $ mul_smul a b _), one_smul := quotient.ind $ by exact (λ m, congr_arg quotient.mk $ one_smul _ _), } /-- The action via `linear_equiv.apply_distrib_mul_action` corresponds to `module.ray.map`. -/ @[simp] lemma module.ray.linear_equiv_smul_eq_map (e : M ≃ₗ[R] M) (v : module.ray R M) : e • v = module.ray.map e v := rfl @[simp] lemma smul_ray_of_ne_zero (g : G) (v : M) (hv) : g • ray_of_ne_zero R v hv = ray_of_ne_zero R (g • v) ((smul_ne_zero_iff_ne _).2 hv) := rfl end action namespace module.ray /-- Scaling by a positive unit is a no-op. -/ lemma units_smul_of_pos [nontrivial R] (u : Rˣ) (hu : 0 < (u : R)) (v : module.ray R M) : u • v = v := begin induction v using module.ray.ind, rw [smul_ray_of_ne_zero, ray_eq_iff], exact same_ray_pos_smul_left _ hu, end /-- An arbitrary `ray_vector` giving a ray. -/ def some_ray_vector [nontrivial R] (x : module.ray R M) : ray_vector M := quotient.out x /-- The ray of `some_ray_vector`. -/ @[simp] lemma some_ray_vector_ray [nontrivial R] (x : module.ray R M) : (⟦x.some_ray_vector⟧ : module.ray R M) = x := quotient.out_eq _ /-- An arbitrary nonzero vector giving a ray. -/ def some_vector [nontrivial R] (x : module.ray R M) : M := x.some_ray_vector /-- `some_vector` is nonzero. -/ @[simp] lemma some_vector_ne_zero [nontrivial R] (x : module.ray R M) : x.some_vector ≠ 0 := x.some_ray_vector.property /-- The ray of `some_vector`. -/ @[simp] lemma some_vector_ray [nontrivial R] (x : module.ray R M) : ray_of_ne_zero R _ x.some_vector_ne_zero = x := (congr_arg _ (subtype.coe_eta _ _) : _).trans x.out_eq end module.ray end ordered_comm_semiring section ordered_comm_ring local attribute [instance] ray_vector.same_ray_setoid variables {R : Type*} [ordered_comm_ring R] variables {M N : Type*} [add_comm_group M] [add_comm_group N] [module R M] [module R N] /-- If two vectors are in the same ray, so are their negations. -/ lemma same_ray.neg {v₁ v₂ : M} : same_ray R v₁ v₂ → same_ray R (-v₁) (-v₂) := λ ⟨r₁, r₂, hr₁, hr₂, h⟩, ⟨r₁, r₂, hr₁, hr₂, by rwa [smul_neg, smul_neg, neg_inj]⟩ /-- `same_ray.neg` as an `iff`. -/ @[simp] lemma same_ray_neg_iff {v₁ v₂ : M} : same_ray R (-v₁) (-v₂) ↔ same_ray R v₁ v₂ := ⟨λ h, by simpa only [neg_neg] using h.neg, same_ray.neg⟩ lemma same_ray_neg_swap {v₁ v₂ : M} : same_ray R (-v₁) v₂ ↔ same_ray R v₁ (-v₂) := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, by simpa only [neg_neg] using h.neg⟩ /-- If a vector is in the same ray as its negation, that vector is zero. -/ lemma eq_zero_of_same_ray_self_neg [no_zero_smul_divisors R M] {v₁ : M} (h : same_ray R v₁ (-v₁)) : v₁ = 0 := begin rcases h with ⟨r₁, r₂, hr₁, hr₂, h⟩, rw [smul_neg, ←neg_smul, ←sub_eq_zero, ←sub_smul, sub_neg_eq_add, smul_eq_zero] at h, exact h.resolve_left (add_pos hr₁ hr₂).ne', end namespace ray_vector variables {R} /-- Negating a nonzero vector. -/ instance : has_neg (ray_vector M) := ⟨λ v, ⟨-v, neg_ne_zero.2 v.prop⟩⟩ /-- Negating a nonzero vector commutes with coercion to the underlying module. -/ @[simp, norm_cast] lemma coe_neg (v : ray_vector M) : ↑(-v) = -(v : M) := rfl /-- Negating a nonzero vector twice produces the original vector. -/ @[simp] protected lemma neg_neg (v : ray_vector M) : -(-v) = v := by rw [subtype.ext_iff, coe_neg, coe_neg, neg_neg] variables (R) /-- If two nonzero vectors are equivalent, so are their negations. -/ @[simp] lemma equiv_neg_iff [nontrivial R] (v₁ v₂ : ray_vector M) : -v₁ ≈ -v₂ ↔ v₁ ≈ v₂ := by rw [equiv_iff_same_ray, equiv_iff_same_ray, coe_neg, coe_neg, same_ray_neg_iff] end ray_vector variables (R) /-- Negating a ray. -/ instance [nontrivial R] : has_neg (module.ray R M) := ⟨quotient.map (λ v, -v) (λ v₁ v₂, (ray_vector.equiv_neg_iff R v₁ v₂).2)⟩ /-- The ray given by the negation of a nonzero vector. -/ lemma ray_neg [nontrivial R] (v : M) (h : v ≠ 0) : ray_of_ne_zero R _ (show -v ≠ 0, by rw neg_ne_zero; exact h) = -(ray_of_ne_zero R _ h) := rfl namespace module.ray variables {R} /-- Negating a ray twice produces the original ray. -/ @[simp] protected lemma neg_neg [nontrivial R] (x : module.ray R M) : -(-x) = x := quotient.ind (λ a, congr_arg quotient.mk $ ray_vector.neg_neg _) x variables (R M) /-- Negating a ray is involutive. -/ lemma neg_involutive [nontrivial R] : function.involutive (λ x : module.ray R M, -x) := λ x, module.ray.neg_neg x variables {R M} protected lemma eq_neg_iff_eq_neg [nontrivial R] (x y : module.ray R M) : x = -y ↔ y = -x := by rw [←module.ray.neg_neg x, (neg_involutive R M).injective.eq_iff, module.ray.neg_neg x, eq_comm] /-- A ray does not equal its own negation. -/ lemma ne_neg_self [nontrivial R] [no_zero_smul_divisors R M] (x : module.ray R M) : x ≠ -x := begin intro h, induction x using module.ray.ind, rw [←ray_neg, ray_eq_iff] at h, exact x_hv (eq_zero_of_same_ray_self_neg h) end /-- Scaling by a negative unit is negation. -/ lemma units_smul_of_neg [nontrivial R] (u : Rˣ) (hu : (u : R) < 0) (v : module.ray R M) : u • v = -v := begin induction v using module.ray.ind, rw [smul_ray_of_ne_zero, ←ray_neg, ray_eq_iff, ←same_ray_neg_swap, units.smul_def, ←neg_smul], exact same_ray_pos_smul_left _ (neg_pos_of_neg hu), end end module.ray namespace basis variables {R} {ι : Type*} [fintype ι] [decidable_eq ι] /-- The orientation given by a basis. -/ protected def orientation [nontrivial R] (e : basis ι R M) : orientation R M ι := ray_of_ne_zero R _ e.det_ne_zero lemma orientation_map [nontrivial R] (e : basis ι R M) (f : M ≃ₗ[R] N) : (e.map f).orientation = orientation.map ι f e.orientation := by simp_rw [basis.orientation, orientation.map_apply, basis.det_map'] /-- The value of `orientation.map` when the index type has the cardinality of a basis, in terms of `f.det`. -/ lemma map_orientation_eq_det_inv_smul [nontrivial R] [is_domain R] (e : basis ι R M) (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = (f.det)⁻¹ • x := begin induction x using module.ray.ind with g hg, rw [orientation.map_apply, smul_ray_of_ne_zero, ray_eq_iff, units.smul_def, (g.comp_linear_map ↑f.symm).eq_smul_basis_det e, g.eq_smul_basis_det e, alternating_map.comp_linear_map_apply, alternating_map.smul_apply, basis.det_comp, basis.det_self, mul_one, smul_eq_mul, mul_comm, mul_smul, linear_equiv.coe_inv_det], end /-- The orientation given by a basis derived using `units_smul`, in terms of the product of those units. -/ lemma orientation_units_smul [nontrivial R] (e : basis ι R M) (w : ι → units R) : (e.units_smul w).orientation = (∏ i, w i)⁻¹ • e.orientation := begin rw [basis.orientation, basis.orientation, smul_ray_of_ne_zero, ray_eq_iff, e.det.eq_smul_basis_det (e.units_smul w), det_units_smul, units.smul_def, smul_smul], norm_cast, simp end end basis end ordered_comm_ring section linear_ordered_comm_ring variables {R : Type*} [linear_ordered_comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} [decidable_eq ι] /-- `same_ray` follows from membership of `mul_action.orbit` for the `units.pos_subgroup`. -/ lemma same_ray_of_mem_orbit {v₁ v₂ : M} (h : v₁ ∈ mul_action.orbit (units.pos_subgroup R) v₂) : same_ray R v₁ v₂ := begin rcases h with ⟨⟨r, hr⟩, (rfl : r • v₂ = v₁)⟩, exact same_ray_pos_smul_left _ hr, end /-- Scaling by an inverse unit is the same as scaling by itself. -/ @[simp] lemma units_inv_smul (u : Rˣ) (v : module.ray R M) : u⁻¹ • v = u • v := begin induction v using module.ray.ind with v hv, rw [smul_ray_of_ne_zero, smul_ray_of_ne_zero, ray_eq_iff], have : ∀ {u : Rˣ}, 0 < (u : R) → same_ray R (u⁻¹ • v) (u • v) := λ u h, ((same_ray.refl v).pos_smul_left $ units.inv_pos.mpr h).pos_smul_right h, cases lt_or_lt_iff_ne.2 u.ne_zero, { rw [←units.neg_neg u, units.neg_inv, (- u).neg_smul, units.neg_smul], refine (this _).neg, exact neg_pos_of_neg h }, { exact this h, }, end section variables [no_zero_smul_divisors R M] /-- A nonzero vector is in the same ray as a multiple of itself if and only if that multiple is positive. -/ @[simp] lemma same_ray_smul_right_iff {v : M} (hv : v ≠ 0) (r : R) : same_ray R v (r • v) ↔ 0 < r := begin split, { rintros ⟨r₁, r₂, hr₁, hr₂, h⟩, rw [smul_smul, ←sub_eq_zero, ←sub_smul, sub_eq_add_neg, neg_mul_eq_mul_neg] at h, by_contradiction hr, rw [not_lt, ←neg_le_neg_iff, neg_zero] at hr, have hzzz := ne_of_gt (add_pos_of_pos_of_nonneg hr₁ (mul_nonneg hr₂.le hr)), simpa [ne_of_gt (add_pos_of_pos_of_nonneg hr₁ (mul_nonneg hr₂.le hr)), -mul_neg_eq_neg_mul_symm] using h }, { exact λ h, same_ray_pos_smul_right v h } end /-- A multiple of a nonzero vector is in the same ray as that vector if and only if that multiple is positive. -/ @[simp] lemma same_ray_smul_left_iff {v : M} (hv : v ≠ 0) (r : R) : same_ray R (r • v) v ↔ 0 < r := begin rw same_ray_comm, exact same_ray_smul_right_iff hv r end /-- The negation of a nonzero vector is in the same ray as a multiple of that vector if and only if that multiple is negative. -/ @[simp] lemma same_ray_neg_smul_right_iff {v : M} (hv : v ≠ 0) (r : R) : same_ray R (-v) (r • v) ↔ r < 0 := begin rw [←same_ray_neg_iff, neg_neg, ←neg_smul, same_ray_smul_right_iff hv (-r)], exact right.neg_pos_iff end /-- A multiple of a nonzero vector is in the same ray as the negation of that vector if and only if that multiple is negative. -/ @[simp] lemma same_ray_neg_smul_left_iff {v : M} (hv : v ≠ 0) (r : R) : same_ray R (r • v) (-v) ↔ r < 0 := begin rw [←same_ray_neg_iff, neg_neg, ←neg_smul, same_ray_smul_left_iff hv (-r)], exact left.neg_pos_iff end /-- A nonzero vector is in the same ray as a multiple of itself if and only if that multiple is positive. -/ @[simp] lemma units_smul_eq_self_iff {u : Rˣ} {v : module.ray R M} : u • v = v ↔ (0 : R) < u := begin induction v using module.ray.ind with v hv, rw [smul_ray_of_ne_zero, ray_eq_iff, units.smul_def], exact same_ray_smul_left_iff hv _, end /-- A nonzero vector is in the same ray as a multiple of itself if and only if that multiple is positive. -/ @[simp] lemma units_smul_eq_neg_iff {u : Rˣ} {v : module.ray R M} : u • v = -v ↔ ↑u < (0 : R) := begin induction v using module.ray.ind with v hv, rw [smul_ray_of_ne_zero, ←ray_neg, ray_eq_iff, units.smul_def], exact same_ray_neg_smul_left_iff hv _, end end namespace basis variables [fintype ι] /-- The orientations given by two bases are equal if and only if the determinant of one basis with respect to the other is positive. -/ lemma orientation_eq_iff_det_pos (e₁ e₂ : basis ι R M) : e₁.orientation = e₂.orientation ↔ 0 < e₁.det e₂ := by rw [basis.orientation, basis.orientation, ray_eq_iff, e₁.det.eq_smul_basis_det e₂, alternating_map.smul_apply, basis.det_self, smul_eq_mul, mul_one, same_ray_smul_left_iff e₂.det_ne_zero (_ : R)] /-- Given a basis, any orientation equals the orientation given by that basis or its negation. -/ lemma orientation_eq_or_eq_neg (e : basis ι R M) (x : orientation R M ι) : x = e.orientation ∨ x = -e.orientation := begin induction x using module.ray.ind with x hx, rw [basis.orientation, ray_eq_iff, ←ray_neg, ray_eq_iff, x.eq_smul_basis_det e, same_ray_neg_smul_left_iff e.det_ne_zero (_ : R), same_ray_smul_left_iff e.det_ne_zero (_ : R), lt_or_lt_iff_ne, ne_comm, alternating_map.map_basis_ne_zero_iff], exact hx end /-- Given a basis, an orientation equals the negation of that given by that basis if and only if it does not equal that given by that basis. -/ lemma orientation_ne_iff_eq_neg (e : basis ι R M) (x : orientation R M ι) : x ≠ e.orientation ↔ x = -e.orientation := ⟨λ h, (e.orientation_eq_or_eq_neg x).resolve_left h, λ h, h.symm ▸ (module.ray.ne_neg_self e.orientation).symm⟩ /-- Composing a basis with a linear equiv gives the same orientation if and only if the determinant is positive. -/ lemma orientation_comp_linear_equiv_eq_iff_det_pos (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = e.orientation ↔ 0 < (f : M →ₗ[R] M).det := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] /-- Composing a basis with a linear equiv gives the negation of that orientation if and only if the determinant is negative. -/ lemma orientation_comp_linear_equiv_eq_neg_iff_det_neg (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = -e.orientation ↔ (f : M →ₗ[R] M).det < 0 := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] /-- Negating a single basis vector (represented using `units_smul`) negates the corresponding orientation. -/ @[simp] lemma orientation_neg_single [nontrivial R] (e : basis ι R M) (i : ι) : (e.units_smul (function.update 1 i (-1))).orientation = -e.orientation := begin rw [orientation_units_smul, finset.prod_update_of_mem (finset.mem_univ _)], simp end /-- Given a basis and an orientation, return a basis giving that orientation: either the original basis, or one constructed by negating a single (arbitrary) basis vector. -/ def adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : basis ι R M := by haveI := classical.dec_eq (orientation R M ι); exact if e.orientation = x then e else (e.units_smul (function.update 1 (classical.arbitrary ι) (-1))) /-- `adjust_to_orientation` gives a basis with the required orientation. -/ @[simp] lemma orientation_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).orientation = x := begin rw adjust_to_orientation, split_ifs with h, { exact h }, { rw [orientation_neg_single, eq_comm, ←orientation_ne_iff_eq_neg, ne_comm], exact h } end /-- Every basis vector from `adjust_to_orientation` is either that from the original basis or its negation. -/ lemma adjust_to_orientation_apply_eq_or_eq_neg [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (i : ι) : e.adjust_to_orientation x i = e i ∨ e.adjust_to_orientation x i = -(e i) := begin rw adjust_to_orientation, split_ifs with h, { simp }, { by_cases hi : i = classical.arbitrary ι; simp [units_smul_apply, hi] } end end basis end linear_ordered_comm_ring section linear_ordered_field variables (R : Type*) [linear_ordered_field R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} [decidable_eq ι] /-- `same_ray` is equivalent to membership of `mul_action.orbit` for the `units.pos_subgroup`. -/ lemma same_ray_iff_mem_orbit (v₁ v₂ : M) : same_ray R v₁ v₂ ↔ v₁ ∈ mul_action.orbit (units.pos_subgroup R) v₂ := begin split, { rintros ⟨r₁, r₂, hr₁, hr₂, h⟩, rw mul_action.mem_orbit_iff, have h' : (r₁⁻¹ * r₂) • v₂ = v₁, { rw [mul_smul, ←h, ←mul_smul, inv_mul_cancel (ne_of_lt hr₁).symm, one_smul] }, have hr' : 0 < (r₁⁻¹ * r₂) := mul_pos (inv_pos.2 hr₁) hr₂, change (⟨units.mk0 (r₁⁻¹ * r₂) (ne_of_lt hr').symm, hr'⟩ : units.pos_subgroup R) • v₂ = v₁ at h', exact ⟨_, h'⟩ }, { exact same_ray_of_mem_orbit } end /-- `same_ray_setoid` equals `mul_action.orbit_rel` for the `units.pos_subgroup`. -/ lemma same_ray_setoid_eq_orbit_rel : same_ray_setoid R M = mul_action.orbit_rel (units.pos_subgroup R) M := setoid.ext' $ same_ray_iff_mem_orbit R variables {R} namespace orientation variables [fintype ι] [finite_dimensional R M] open finite_dimensional /-- If the index type has cardinality equal to the finite dimension, any two orientations are equal or negations. -/ lemma eq_or_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ = x₂ ∨ x₁ = -x₂ := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, rcases e.orientation_eq_or_eq_neg x₁ with h₁|h₁; rcases e.orientation_eq_or_eq_neg x₂ with h₂|h₂; simp [h₁, h₂] end /-- If the index type has cardinality equal to the finite dimension, an orientation equals the negation of another orientation if and only if they are not equal. -/ lemma ne_iff_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ ≠ x₂ ↔ x₁ = -x₂ := ⟨λ hn, (eq_or_eq_neg x₁ x₂ h).resolve_left hn, λ he, he.symm ▸ (module.ray.ne_neg_self x₂).symm⟩ /-- The value of `orientation.map` when the index type has cardinality equal to the finite dimension, in terms of `f.det`. -/ lemma map_eq_det_inv_smul (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = (f.det)⁻¹ • x := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, exact e.map_orientation_eq_det_inv_smul x f end /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the same orientation if and only if the determinant is positive. -/ lemma map_eq_iff_det_pos (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = x ↔ 0 < (f : M →ₗ[R] M).det := by rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the negation of that orientation if and only if the determinant is negative. -/ lemma map_eq_neg_iff_det_neg (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = -x ↔ (f : M →ₗ[R] M).det < 0 := by rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] /-- If the index type has cardinality equal to the finite dimension, a basis with the given orientation. -/ def some_basis [nonempty ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : basis ι R M := ((fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm).adjust_to_orientation x /-- `some_basis` gives a basis with the required orientation. -/ @[simp] lemma some_basis_orientation [nonempty ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : (x.some_basis h).orientation = x := basis.orientation_adjust_to_orientation _ _ end orientation end linear_ordered_field
367f42e9b91474ba2ff5d661bc560a83df572c5e
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/order/filter/ultrafilter.lean
8e860e8031ae709b692706d978f172aff87be1e4
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
12,716
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, Jeremy Avigad -/ import order.filter.cofinite /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `is_ultrafilter`: a predicate stating that a given filter is an ultrafiler; * `ultrafilter_of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind` : operations on ultrafilters; * `hyperfilter`: the ultra-filter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} namespace filter open set zorn open_locale classical filter variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : g ⊓ f ≠ ⊥) : f ≤ g := by { rw inf_comm at h, exact le_of_inf_eq (ultrafilter_unique hf h inf_le_left) } /-- Equivalent characterization of ultrafilters: A filter f is an ultrafilter if and only if for each set s, -s belongs to f if and only if s does not belong to f. -/ lemma ultrafilter_iff_compl_mem_iff_not_mem : is_ultrafilter f ↔ (∀ s, sᶜ ∈ f ↔ s ∉ f) := ⟨assume hf s, ⟨assume hns hs, hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self], assume hs, have f ≤ 𝓟 sᶜ, from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_eq_bot $ by rwa inf_comm, by simp only [le_principal_iff] at this; assumption⟩, assume hf, ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])), assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $ assume : sᶜ ∈ f, have s ∩ sᶜ ∈ g, from inter_mem_sets hs (g_le this), by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩ lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) : s ∈ f ∨ sᶜ ∈ f := classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) : s ∈ f ∨ t ∈ f := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : sᶜ ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma is_ultrafilter.em (hf : is_ultrafilter f) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := mem_or_compl_mem_of_ultrafilter hf {x | p x} lemma is_ultrafilter.eventually_or (hf : is_ultrafilter f) {p q : α → Prop} : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := ⟨mem_or_mem_of_ultrafilter hf, λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩ lemma is_ultrafilter.eventually_not (hf : is_ultrafilter f) {p : α → Prop} : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := ultrafilter_iff_compl_mem_iff_not_mem.1 hf {x | p x} lemma is_ultrafilter.eventually_imp (hf : is_ultrafilter f) {p q : α → Prop} : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, hf.eventually_or, hf.eventually_not] lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f → ∃t∈s, t ∈ f := finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty, forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $ λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f := have his : finite (image s is), from his.image s, have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) := by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s) lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) := begin rw ultrafilter_iff_compl_mem_iff_not_mem, intro s, rw [mem_pure_sets, mem_pure_sets], exact iff.rfl end lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β} (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) := begin simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s, dsimp [bind, join, map, preimage], simp only [hm], apply hf end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := nonempty_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_ne_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff], simp only at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp only [ultrafilter_of, h, dif_pos, le_bot_iff] else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g := begin refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H), intros s hs, -- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s. by_contradiction hs', let j : sᶜ → α := subtype.val, have j_inv_s : j ⁻¹' s = ∅, by erw [←preimage_inter_range, subtype.range_coe, inter_compl_self, preimage_empty], let f' := comap j f, have : f' ≠ ⊥, { apply mt empty_in_sets_eq_bot.mpr, rintro ⟨t, htf, ht⟩, suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs', rw [subset_empty_iff] at ht, have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty], erw [image_preimage_eq_inter_range, subtype.range_coe, ←subset_compl_iff_disjoint, set.compl_compl] at this, exact this }, rcases exists_ultrafilter this with ⟨g', g'f', u'⟩, simp only [supr_sets_eq, mem_Inter] at hs, have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'), rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty, le_bot_iff] at this, exact absurd this u'.1 end /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ := ⟨assume h g u gx, le_trans (map_mono gx) h, assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩ /-- The ultrafilter monad. The monad structure on ultrafilters is the restriction of the one on filters. -/ def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f} /-- Push-forward for ultra-filters. -/ def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ /-- The principal ultra-filter associated to a point `x`. -/ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ /-- Monadic bind for ultra-filters, coming from the one on filters defined in terms of map and join.-/ def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := ⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩ instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩ instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } instance ultrafilter.inhabited [inhabited α] : inhabited (ultrafilter α) := ⟨pure (default _)⟩ /-- The ultra-filter extending the cofinite filter. -/ noncomputable def hyperfilter : filter α := ultrafilter_of cofinite lemma hyperfilter_le_cofinite : @hyperfilter α ≤ cofinite := ultrafilter_of_le lemma is_ultrafilter_hyperfilter [infinite α] : is_ultrafilter (@hyperfilter α) := (ultrafilter_of_spec cofinite_ne_bot).2 @[simp] lemma hyperfilter_ne_bot [infinite α] : @hyperfilter α ≠ ⊥ := is_ultrafilter_hyperfilter.1 @[simp] lemma bot_ne_hyperfilter [infinite α] : ⊥ ≠ @hyperfilter α := is_ultrafilter_hyperfilter.1.symm theorem nmem_hyperfilter_of_finite [infinite α] {s : set α} (hf : s.finite) : s ∉ @hyperfilter α := λ hy, have hx : sᶜ ∉ hyperfilter := λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp is_ultrafilter_hyperfilter s).mp hs hy, have ht : sᶜ ∈ cofinite.sets := by show sᶜ ∈ {s | _}; rwa [set.mem_set_of_eq, compl_compl], hx $ hyperfilter_le_cofinite ht theorem compl_mem_hyperfilter_of_finite [infinite α] {s : set α} (hf : set.finite s) : sᶜ ∈ @hyperfilter α := (ultrafilter_iff_compl_mem_iff_not_mem.mp is_ultrafilter_hyperfilter s).mpr $ nmem_hyperfilter_of_finite hf theorem mem_hyperfilter_of_finite_compl [infinite α] {s : set α} (hf : set.finite sᶜ) : s ∈ @hyperfilter α := s.compl_compl ▸ compl_mem_hyperfilter_of_finite hf section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, subtype.eq (id_map f.val), pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)), bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map f x.val) } end lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val := ⟨assume h, by rw h; exact le_refl _, assume h, by rw subtype.ext_iff_val; apply ultrafilter_unique v.property u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ := ⟨assume ⟨u, uf⟩, ne_bot_of_le_ne_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩ end filter
4e78a92a97f11c548c6ac242dc02ed710655c4cb
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/nat/choose/dvd.lean
6278e650fd7ca51760a33b736465ff9bc538f751
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,957
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import data.nat.choose.basic import data.nat.prime import data.rat.floor /-! # Divisibility properties of binomial coefficients -/ namespace nat namespace prime open_locale nat lemma dvd_choose_add {p a b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b) (hp : prime p) : p ∣ choose (a + b) a := have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h, have h₂ : ¬p ∣ a!, from mt hp.dvd_factorial.1 (not_le_of_gt hap), have h₃ : ¬p ∣ b!, from mt hp.dvd_factorial.1 (not_le_of_gt hbp), by rw [← choose_mul_factorial_mul_factorial (le.intro rfl), mul_assoc, hp.dvd_mul, hp.dvd_mul, nat.add_sub_cancel_left a b] at h₁; exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩) lemma dvd_choose_self {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) : p ∣ choose p k := begin have r : k + (p - k) = p, by rw [← nat.add_sub_assoc (nat.le_of_lt hkp) k, nat.add_sub_cancel_left], have e : p ∣ choose (k + (p - k)) k, by exact dvd_choose_add hkp (sub_lt (hk.trans hkp) hk) (by rw r) hp, rwa r at e, end lemma choose_eq_factorial_div_factorial' {a b : ℕ} (hab : a ≤ b) : (b.choose a : ℚ) = b! / (a! * (b - a)!) := begin field_simp [mul_ne_zero, factorial_ne_zero], norm_cast, rw ← choose_mul_factorial_mul_factorial hab, ring, end lemma choose_mul {n k s : ℕ} (hn : k ≤ n) (hs : s ≤ k) : (n.choose k : ℚ) * k.choose s = n.choose s * (n - s).choose (k - s) := begin rw [choose_eq_factorial_div_factorial' hn, choose_eq_factorial_div_factorial' hs, choose_eq_factorial_div_factorial' (le_trans hs hn), choose_eq_factorial_div_factorial' ], swap, { exact nat.sub_le_sub_right hn s, }, { field_simp [mul_ne_zero, factorial_ne_zero], rw sub_sub_sub_cancel_right hs, ring, }, end end prime end nat
fbaa8a7f1b27b645523f45c24eccccb3b32e115c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/symm_diff.lean
401c9105dc451cab8b3e0d801ca21d6d68011cc1
[ "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,517
lean
/- Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Bryan Gin-ge Chen, Yaël Dillies -/ import order.boolean_algebra import logic.equiv.basic /-! # Symmetric difference and bi-implication This file defines the symmetric difference and bi-implication operators in (co-)Heyting algebras. ## Examples Some examples are * The symmetric difference of two sets is the set of elements that are in either but not both. * The symmetric difference on propositions is `xor`. * The symmetric difference on `bool` is `bxor`. * The equivalence of propositions. Two propositions are equivalent if they imply each other. * The symmetric difference translates to addition when considering a Boolean algebra as a Boolean ring. ## Main declarations * `symm_diff`: The symmetric difference operator, defined as `(a \ b) ⊔ (b \ a)` * `bihimp`: The bi-implication operator, defined as `(b ⇨ a) ⊓ (a ⇨ b)` In generalized Boolean algebras, the symmetric difference operator is: * `symm_diff_comm`: commutative, and * `symm_diff_assoc`: associative. ## Notations * `a ∆ b`: `symm_diff a b` * `a ⇔ b`: `bihimp a b` ## References The proof of associativity follows the note "Associativity of the Symmetric Difference of Sets: A Proof from the Book" by John McCuan: * <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf> ## Tags boolean ring, generalized boolean algebra, boolean algebra, symmetric difference, bi-implication, Heyting -/ open function order_dual variables {ι α β : Type*} {π : ι → Type*} /-- The symmetric difference operator on a type with `⊔` and `\` is `(A \ B) ⊔ (B \ A)`. -/ def symm_diff [has_sup α] [has_sdiff α] (a b : α) : α := a \ b ⊔ b \ a /-- The Heyting bi-implication is `(b ⇨ a) ⊓ (a ⇨ b)`. This generalizes equivalence of propositions. -/ def bihimp [has_inf α] [has_himp α] (a b : α) : α := (b ⇨ a) ⊓ (a ⇨ b) /- This notation might conflict with the Laplacian once we have it. Feel free to put it in locale `order` or `symm_diff` if that happens. -/ infix ` ∆ `:100 := symm_diff infix ` ⇔ `:100 := bihimp lemma symm_diff_def [has_sup α] [has_sdiff α] (a b : α) : a ∆ b = (a \ b) ⊔ (b \ a) := rfl lemma bihimp_def [has_inf α] [has_himp α] (a b : α) : a ⇔ b = (b ⇨ a) ⊓ (a ⇨ b):= rfl lemma symm_diff_eq_xor (p q : Prop) : p ∆ q = xor p q := rfl @[simp] lemma bihimp_iff_iff {p q : Prop} : p ⇔ q ↔ (p ↔ q) := (iff_iff_implies_and_implies _ _).symm.trans iff.comm @[simp] lemma bool.symm_diff_eq_bxor : ∀ p q : bool, p ∆ q = bxor p q := dec_trivial section generalized_coheyting_algebra variables [generalized_coheyting_algebra α] (a b c d : α) @[simp] lemma to_dual_symm_diff : to_dual (a ∆ b) = to_dual a ⇔ to_dual b := rfl @[simp] lemma of_dual_bihimp (a b : αᵒᵈ) : of_dual (a ⇔ b) = of_dual a ∆ of_dual b := rfl lemma symm_diff_comm : a ∆ b = b ∆ a := by simp only [(∆), sup_comm] instance symm_diff_is_comm : is_commutative α (∆) := ⟨symm_diff_comm⟩ @[simp] lemma symm_diff_self : a ∆ a = ⊥ := by rw [(∆), sup_idem, sdiff_self] @[simp] lemma symm_diff_bot : a ∆ ⊥ = a := by rw [(∆), sdiff_bot, bot_sdiff, sup_bot_eq] @[simp] lemma bot_symm_diff : ⊥ ∆ a = a := by rw [symm_diff_comm, symm_diff_bot] @[simp] lemma symm_diff_eq_bot {a b : α} : a ∆ b = ⊥ ↔ a = b := by simp_rw [symm_diff, sup_eq_bot_iff, sdiff_eq_bot_iff, le_antisymm_iff] lemma symm_diff_of_le {a b : α} (h : a ≤ b) : a ∆ b = b \ a := by rw [symm_diff, sdiff_eq_bot_iff.2 h, bot_sup_eq] lemma symm_diff_of_ge {a b : α} (h : b ≤ a) : a ∆ b = a \ b := by rw [symm_diff, sdiff_eq_bot_iff.2 h, sup_bot_eq] lemma symm_diff_le {a b c : α} (ha : a ≤ b ⊔ c) (hb : b ≤ a ⊔ c) : a ∆ b ≤ c := sup_le (sdiff_le_iff.2 ha) $ sdiff_le_iff.2 hb lemma symm_diff_le_iff {a b c : α} : a ∆ b ≤ c ↔ a ≤ b ⊔ c ∧ b ≤ a ⊔ c := by simp_rw [symm_diff, sup_le_iff, sdiff_le_iff] @[simp] lemma symm_diff_le_sup {a b : α} : a ∆ b ≤ a ⊔ b := sup_le_sup sdiff_le sdiff_le lemma symm_diff_eq_sup_sdiff_inf : a ∆ b = (a ⊔ b) \ (a ⊓ b) := by simp [sup_sdiff, symm_diff] lemma disjoint.symm_diff_eq_sup {a b : α} (h : disjoint a b) : a ∆ b = a ⊔ b := by rw [(∆), h.sdiff_eq_left, h.sdiff_eq_right] lemma symm_diff_sdiff : (a ∆ b) \ c = a \ (b ⊔ c) ⊔ b \ (a ⊔ c) := by rw [symm_diff, sup_sdiff_distrib, sdiff_sdiff_left, sdiff_sdiff_left] @[simp] lemma symm_diff_sdiff_inf : a ∆ b \ (a ⊓ b) = a ∆ b := by { rw symm_diff_sdiff, simp [symm_diff] } @[simp] lemma symm_diff_sdiff_eq_sup : a ∆ (b \ a) = a ⊔ b := begin rw [symm_diff, sdiff_idem], exact le_antisymm (sup_le_sup sdiff_le sdiff_le) (sup_le le_sdiff_sup $ le_sdiff_sup.trans $ sup_le le_sup_right le_sdiff_sup), end @[simp] lemma sdiff_symm_diff_eq_sup : (a \ b) ∆ b = a ⊔ b := by rw [symm_diff_comm, symm_diff_sdiff_eq_sup, sup_comm] @[simp] lemma symm_diff_sup_inf : a ∆ b ⊔ a ⊓ b = a ⊔ b := begin refine le_antisymm (sup_le symm_diff_le_sup inf_le_sup) _, rw [sup_inf_left, symm_diff], refine sup_le (le_inf le_sup_right _) (le_inf _ le_sup_right), { rw sup_right_comm, exact le_sup_of_le_left le_sdiff_sup }, { rw sup_assoc, exact le_sup_of_le_right le_sdiff_sup } end @[simp] lemma inf_sup_symm_diff : a ⊓ b ⊔ a ∆ b = a ⊔ b := by rw [sup_comm, symm_diff_sup_inf] @[simp] lemma symm_diff_symm_diff_inf : a ∆ b ∆ (a ⊓ b) = a ⊔ b := by rw [←symm_diff_sdiff_inf a, sdiff_symm_diff_eq_sup, symm_diff_sup_inf] @[simp] lemma inf_symm_diff_symm_diff : (a ⊓ b) ∆ (a ∆ b) = a ⊔ b := by rw [symm_diff_comm, symm_diff_symm_diff_inf] lemma symm_diff_triangle : a ∆ c ≤ a ∆ b ⊔ b ∆ c := begin refine (sup_le_sup (sdiff_triangle a b c) $ sdiff_triangle _ b _).trans_eq _, rw [@sup_comm _ _ (c \ b), sup_sup_sup_comm, symm_diff, symm_diff], end end generalized_coheyting_algebra section generalized_heyting_algebra variables [generalized_heyting_algebra α] (a b c d : α) @[simp] lemma to_dual_bihimp : to_dual (a ⇔ b) = to_dual a ∆ to_dual b := rfl @[simp] lemma of_dual_symm_diff (a b : αᵒᵈ) : of_dual (a ∆ b) = of_dual a ⇔ of_dual b := rfl lemma bihimp_comm : a ⇔ b = b ⇔ a := by simp only [(⇔), inf_comm] instance bihimp_is_comm : is_commutative α (⇔) := ⟨bihimp_comm⟩ @[simp] lemma bihimp_self : a ⇔ a = ⊤ := by rw [(⇔), inf_idem, himp_self] @[simp] lemma bihimp_top : a ⇔ ⊤ = a := by rw [(⇔), himp_top, top_himp, inf_top_eq] @[simp] lemma top_bihimp : ⊤ ⇔ a = a := by rw [bihimp_comm, bihimp_top] @[simp] lemma bihimp_eq_top {a b : α} : a ⇔ b = ⊤ ↔ a = b := @symm_diff_eq_bot αᵒᵈ _ _ _ lemma bihimp_of_le {a b : α} (h : a ≤ b) : a ⇔ b = b ⇨ a := by rw [bihimp, himp_eq_top_iff.2 h, inf_top_eq] lemma bihimp_of_ge {a b : α} (h : b ≤ a) : a ⇔ b = a ⇨ b := by rw [bihimp, himp_eq_top_iff.2 h, top_inf_eq] lemma le_bihimp {a b c : α} (hb : a ⊓ b ≤ c) (hc : a ⊓ c ≤ b) : a ≤ b ⇔ c := le_inf (le_himp_iff.2 hc) $ le_himp_iff.2 hb lemma le_bihimp_iff {a b c : α} : a ≤ b ⇔ c ↔ a ⊓ b ≤ c ∧ a ⊓ c ≤ b := by simp_rw [bihimp, le_inf_iff, le_himp_iff, and.comm] @[simp] lemma inf_le_bihimp {a b : α} : a ⊓ b ≤ a ⇔ b := inf_le_inf le_himp le_himp lemma bihimp_eq_inf_himp_inf : a ⇔ b = (a ⊔ b) ⇨ (a ⊓ b) := by simp [himp_inf_distrib, bihimp] lemma codisjoint.bihimp_eq_inf {a b : α} (h : codisjoint a b) : a ⇔ b = a ⊓ b := by rw [(⇔), h.himp_eq_left, h.himp_eq_right] lemma himp_bihimp : a ⇨ (b ⇔ c) = ((a ⊓ c) ⇨ b) ⊓ ((a ⊓ b) ⇨ c) := by rw [bihimp, himp_inf_distrib, himp_himp, himp_himp] @[simp] lemma sup_himp_bihimp : (a ⊔ b) ⇨ (a ⇔ b) = a ⇔ b := by { rw himp_bihimp, simp [bihimp] } @[simp] lemma bihimp_himp_eq_inf : a ⇔ (a ⇨ b) = a ⊓ b := @symm_diff_sdiff_eq_sup αᵒᵈ _ _ _ @[simp] lemma himp_bihimp_eq_inf : (b ⇨ a) ⇔ b = a ⊓ b := @sdiff_symm_diff_eq_sup αᵒᵈ _ _ _ @[simp] lemma bihimp_inf_sup : a ⇔ b ⊓ (a ⊔ b) = a ⊓ b := @symm_diff_sup_inf αᵒᵈ _ _ _ @[simp] lemma sup_inf_bihimp : (a ⊔ b) ⊓ a ⇔ b = a ⊓ b := @inf_sup_symm_diff αᵒᵈ _ _ _ @[simp] lemma bihimp_bihimp_sup : a ⇔ b ⇔ (a ⊔ b) = a ⊓ b := @symm_diff_symm_diff_inf αᵒᵈ _ _ _ @[simp] lemma sup_bihimp_bihimp : (a ⊔ b) ⇔ (a ⇔ b) = a ⊓ b := @inf_symm_diff_symm_diff αᵒᵈ _ _ _ lemma bihimp_triangle : a ⇔ b ⊓ b ⇔ c ≤ a ⇔ c := @symm_diff_triangle αᵒᵈ _ _ _ _ end generalized_heyting_algebra section coheyting_algebra variables [coheyting_algebra α] (a : α) @[simp] lemma symm_diff_top' : a ∆ ⊤ = ¬a := by simp [symm_diff] @[simp] lemma top_symm_diff' : ⊤ ∆ a = ¬a := by simp [symm_diff] @[simp] lemma hnot_symm_diff_self : (¬a) ∆ a = ⊤ := begin rw [eq_top_iff, symm_diff, hnot_sdiff, sup_sdiff_self], exact codisjoint.top_le codisjoint_hnot_left end @[simp] lemma symm_diff_hnot_self : a ∆ ¬a = ⊤ := by rw [symm_diff_comm, hnot_symm_diff_self] lemma is_compl.symm_diff_eq_top {a b : α} (h : is_compl a b) : a ∆ b = ⊤ := by rw [h.eq_hnot, hnot_symm_diff_self] end coheyting_algebra section heyting_algebra variables [heyting_algebra α] (a : α) @[simp] lemma bihimp_bot : a ⇔ ⊥ = aᶜ := by simp [bihimp] @[simp] lemma bot_bihimp : ⊥ ⇔ a = aᶜ := by simp [bihimp] @[simp] lemma compl_bihimp_self : aᶜ ⇔ a = ⊥ := @hnot_symm_diff_self αᵒᵈ _ _ @[simp] lemma bihimp_hnot_self : a ⇔ aᶜ = ⊥ := @symm_diff_hnot_self αᵒᵈ _ _ lemma is_compl.bihimp_eq_bot {a b : α} (h : is_compl a b) : a ⇔ b = ⊥ := by rw [h.eq_compl, compl_bihimp_self] end heyting_algebra section generalized_boolean_algebra variables [generalized_boolean_algebra α] (a b c d : α) @[simp] lemma sup_sdiff_symm_diff : (a ⊔ b) \ (a ∆ b) = a ⊓ b := sdiff_eq_symm inf_le_sup (by rw symm_diff_eq_sup_sdiff_inf) lemma disjoint_symm_diff_inf : disjoint (a ∆ b) (a ⊓ b) := begin rw [symm_diff_eq_sup_sdiff_inf], exact disjoint_sdiff_self_left, end lemma inf_symm_diff_distrib_left : a ⊓ (b ∆ c) = (a ⊓ b) ∆ (a ⊓ c) := by rw [symm_diff_eq_sup_sdiff_inf, inf_sdiff_distrib_left, inf_sup_left, inf_inf_distrib_left, symm_diff_eq_sup_sdiff_inf] lemma inf_symm_diff_distrib_right : (a ∆ b) ⊓ c = (a ⊓ c) ∆ (b ⊓ c) := by simp_rw [@inf_comm _ _ _ c, inf_symm_diff_distrib_left] lemma sdiff_symm_diff : c \ (a ∆ b) = (c ⊓ a ⊓ b) ⊔ ((c \ a) ⊓ (c \ b)) := by simp only [(∆), sdiff_sdiff_sup_sdiff'] lemma sdiff_symm_diff' : c \ (a ∆ b) = (c ⊓ a ⊓ b) ⊔ (c \ (a ⊔ b)) := by rw [sdiff_symm_diff, sdiff_sup, sup_comm] @[simp] lemma symm_diff_sdiff_left : (a ∆ b) \ a = b \ a := by rw [symm_diff_def, sup_sdiff, sdiff_idem, sdiff_sdiff_self, bot_sup_eq] @[simp] lemma symm_diff_sdiff_right : (a ∆ b) \ b = a \ b := by rw [symm_diff_comm, symm_diff_sdiff_left] @[simp] lemma sdiff_symm_diff_left : a \ (a ∆ b) = a ⊓ b := by simp [sdiff_symm_diff] @[simp] lemma sdiff_symm_diff_right : b \ (a ∆ b) = a ⊓ b := by rw [symm_diff_comm, inf_comm, sdiff_symm_diff_left] lemma symm_diff_eq_sup : a ∆ b = a ⊔ b ↔ disjoint a b := begin refine ⟨λ h, _, disjoint.symm_diff_eq_sup⟩, rw [symm_diff_eq_sup_sdiff_inf, sdiff_eq_self_iff_disjoint] at h, exact h.of_disjoint_inf_of_le le_sup_left, end @[simp] lemma le_symm_diff_iff_left : a ≤ a ∆ b ↔ disjoint a b := begin refine ⟨λ h, _, λ h, h.symm_diff_eq_sup.symm ▸ le_sup_left⟩, rw symm_diff_eq_sup_sdiff_inf at h, exact disjoint_iff_inf_le.mpr (le_sdiff_iff.1 $ inf_le_of_left_le h).le, end @[simp] lemma le_symm_diff_iff_right : b ≤ a ∆ b ↔ disjoint a b := by rw [symm_diff_comm, le_symm_diff_iff_left, disjoint.comm] lemma symm_diff_symm_diff_left : a ∆ b ∆ c = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) := calc a ∆ b ∆ c = ((a ∆ b) \ c) ⊔ (c \ (a ∆ b)) : symm_diff_def _ _ ... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ ((c \ (a ⊔ b)) ⊔ (c ⊓ a ⊓ b)) : by rw [sdiff_symm_diff', @sup_comm _ _ (c ⊓ a ⊓ b), symm_diff_sdiff] ... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) : by ac_refl lemma symm_diff_symm_diff_right : a ∆ (b ∆ c) = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) := calc a ∆ (b ∆ c) = (a \ (b ∆ c)) ⊔ ((b ∆ c) \ a) : symm_diff_def _ _ ... = (a \ (b ⊔ c)) ⊔ (a ⊓ b ⊓ c) ⊔ (b \ (c ⊔ a) ⊔ c \ (b ⊔ a)) : by rw [sdiff_symm_diff', @sup_comm _ _ (a ⊓ b ⊓ c), symm_diff_sdiff] ... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) : by ac_refl lemma symm_diff_assoc : a ∆ b ∆ c = a ∆ (b ∆ c) := by rw [symm_diff_symm_diff_left, symm_diff_symm_diff_right] instance symm_diff_is_assoc : is_associative α (∆) := ⟨symm_diff_assoc⟩ lemma symm_diff_left_comm : a ∆ (b ∆ c) = b ∆ (a ∆ c) := by simp_rw [←symm_diff_assoc, symm_diff_comm] lemma symm_diff_right_comm : a ∆ b ∆ c = a ∆ c ∆ b := by simp_rw [symm_diff_assoc, symm_diff_comm] lemma symm_diff_symm_diff_symm_diff_comm : (a ∆ b) ∆ (c ∆ d) = (a ∆ c) ∆ (b ∆ d) := by simp_rw [symm_diff_assoc, symm_diff_left_comm] @[simp] lemma symm_diff_symm_diff_cancel_left : a ∆ (a ∆ b) = b := by simp [←symm_diff_assoc] @[simp] lemma symm_diff_symm_diff_cancel_right : b ∆ a ∆ a = b := by simp [symm_diff_assoc] @[simp] lemma symm_diff_symm_diff_self' : a ∆ b ∆ a = b := by rw [symm_diff_comm,symm_diff_symm_diff_cancel_left] lemma symm_diff_left_involutive (a : α) : involutive (∆ a) := symm_diff_symm_diff_cancel_right _ lemma symm_diff_right_involutive (a : α) : involutive ((∆) a) := symm_diff_symm_diff_cancel_left _ lemma symm_diff_left_injective (a : α) : injective (∆ a) := (symm_diff_left_involutive _).injective lemma symm_diff_right_injective (a : α) : injective ((∆) a) := (symm_diff_right_involutive _).injective lemma symm_diff_left_surjective (a : α) : surjective (∆ a) := (symm_diff_left_involutive _).surjective lemma symm_diff_right_surjective (a : α) : surjective ((∆) a) := (symm_diff_right_involutive _).surjective variables {a b c} @[simp] lemma symm_diff_left_inj : a ∆ b = c ∆ b ↔ a = c := (symm_diff_left_injective _).eq_iff @[simp] lemma symm_diff_right_inj : a ∆ b = a ∆ c ↔ b = c := (symm_diff_right_injective _).eq_iff @[simp] lemma symm_diff_eq_left : a ∆ b = a ↔ b = ⊥ := calc a ∆ b = a ↔ a ∆ b = a ∆ ⊥ : by rw symm_diff_bot ... ↔ b = ⊥ : by rw symm_diff_right_inj @[simp] lemma symm_diff_eq_right : a ∆ b = b ↔ a = ⊥ := by rw [symm_diff_comm, symm_diff_eq_left] protected lemma disjoint.symm_diff_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ∆ b) c := by { rw symm_diff_eq_sup_sdiff_inf, exact (ha.sup_left hb).disjoint_sdiff_left } protected lemma disjoint.symm_diff_right (ha : disjoint a b) (hb : disjoint a c) : disjoint a (b ∆ c) := (ha.symm.symm_diff_left hb.symm).symm lemma symm_diff_eq_iff_sdiff_eq (ha : a ≤ c) : a ∆ b = c ↔ c \ a = b := begin rw ←symm_diff_of_le ha, exact ((symm_diff_right_involutive a).to_perm _).apply_eq_iff_eq_symm_apply.trans eq_comm, end end generalized_boolean_algebra section boolean_algebra variables [boolean_algebra α] (a b c d : α) /- `cogeneralized_boolean_algebra` isn't actually a typeclass, but the lemmas in here are dual to the `generalized_boolean_algebra` ones -/ section cogeneralized_boolean_algebra @[simp] lemma inf_himp_bihimp : (a ⇔ b) ⇨ (a ⊓ b) = a ⊔ b := @sup_sdiff_symm_diff αᵒᵈ _ _ _ lemma codisjoint_bihimp_sup : codisjoint (a ⇔ b) (a ⊔ b) := @disjoint_symm_diff_inf αᵒᵈ _ _ _ @[simp] lemma himp_bihimp_left : a ⇨ (a ⇔ b) = a ⇨ b := @symm_diff_sdiff_left αᵒᵈ _ _ _ @[simp] lemma himp_bihimp_right : b ⇨ (a ⇔ b) = b ⇨ a := @symm_diff_sdiff_right αᵒᵈ _ _ _ @[simp] lemma bihimp_himp_left : (a ⇔ b) ⇨ a = a ⊔ b := @sdiff_symm_diff_left αᵒᵈ _ _ _ @[simp] lemma bihimp_himp_right : (a ⇔ b) ⇨ b = a ⊔ b := @sdiff_symm_diff_right αᵒᵈ _ _ _ @[simp] lemma bihimp_eq_inf : a ⇔ b = a ⊓ b ↔ codisjoint a b := @symm_diff_eq_sup αᵒᵈ _ _ _ @[simp] lemma bihimp_le_iff_left : a ⇔ b ≤ a ↔ codisjoint a b := @le_symm_diff_iff_left αᵒᵈ _ _ _ @[simp] lemma bihimp_le_iff_right : a ⇔ b ≤ b ↔ codisjoint a b := @le_symm_diff_iff_right αᵒᵈ _ _ _ lemma bihimp_assoc : a ⇔ b ⇔ c = a ⇔ (b ⇔ c) := @symm_diff_assoc αᵒᵈ _ _ _ _ instance bihimp_is_assoc : is_associative α (⇔) := ⟨bihimp_assoc⟩ lemma bihimp_left_comm : a ⇔ (b ⇔ c) = b ⇔ (a ⇔ c) := by simp_rw [←bihimp_assoc, bihimp_comm] lemma bihimp_right_comm : a ⇔ b ⇔ c = a ⇔ c ⇔ b := by simp_rw [bihimp_assoc, bihimp_comm] lemma bihimp_bihimp_bihimp_comm : (a ⇔ b) ⇔ (c ⇔ d) = (a ⇔ c) ⇔ (b ⇔ d) := by simp_rw [bihimp_assoc, bihimp_left_comm] @[simp] lemma bihimp_bihimp_cancel_left : a ⇔ (a ⇔ b) = b := by simp [←bihimp_assoc] @[simp] lemma bihimp_bihimp_cancel_right : b ⇔ a ⇔ a = b := by simp [bihimp_assoc] @[simp] lemma bihimp_bihimp_self : a ⇔ b ⇔ a = b := by rw [bihimp_comm, bihimp_bihimp_cancel_left] lemma bihimp_left_involutive (a : α) : involutive (⇔ a) := bihimp_bihimp_cancel_right _ lemma bihimp_right_involutive (a : α) : involutive ((⇔) a) := bihimp_bihimp_cancel_left _ lemma bihimp_left_injective (a : α) : injective (⇔ a) := @symm_diff_left_injective αᵒᵈ _ _ lemma bihimp_right_injective (a : α) : injective ((⇔) a) := @symm_diff_right_injective αᵒᵈ _ _ lemma bihimp_left_surjective (a : α) : surjective (⇔ a) := @symm_diff_left_surjective αᵒᵈ _ _ lemma bihimp_right_surjective (a : α) : surjective ((⇔) a) := @symm_diff_right_surjective αᵒᵈ _ _ variables {a b c} @[simp] lemma bihimp_left_inj : a ⇔ b = c ⇔ b ↔ a = c := (bihimp_left_injective _).eq_iff @[simp] lemma bihimp_right_inj : a ⇔ b = a ⇔ c ↔ b = c := (bihimp_right_injective _).eq_iff @[simp] lemma bihimp_eq_left : a ⇔ b = a ↔ b = ⊤ := @symm_diff_eq_left αᵒᵈ _ _ _ @[simp] lemma bihimp_eq_right : a ⇔ b = b ↔ a = ⊤ := @symm_diff_eq_right αᵒᵈ _ _ _ protected lemma codisjoint.bihimp_left (ha : codisjoint a c) (hb : codisjoint b c) : codisjoint (a ⇔ b) c := (ha.inf_left hb).mono_left inf_le_bihimp protected lemma codisjoint.bihimp_right (ha : codisjoint a b) (hb : codisjoint a c) : codisjoint a (b ⇔ c) := (ha.inf_right hb).mono_right inf_le_bihimp end cogeneralized_boolean_algebra lemma symm_diff_eq : a ∆ b = (a ⊓ bᶜ) ⊔ (b ⊓ aᶜ) := by simp only [(∆), sdiff_eq] lemma bihimp_eq : a ⇔ b = (a ⊔ bᶜ) ⊓ (b ⊔ aᶜ) := by simp only [(⇔), himp_eq] lemma symm_diff_eq' : a ∆ b = (a ⊔ b) ⊓ (aᶜ ⊔ bᶜ) := by rw [symm_diff_eq_sup_sdiff_inf, sdiff_eq, compl_inf] lemma bihimp_eq' : a ⇔ b = (a ⊓ b) ⊔ (aᶜ ⊓ bᶜ) := @symm_diff_eq' αᵒᵈ _ _ _ lemma symm_diff_top : a ∆ ⊤ = aᶜ := symm_diff_top' _ lemma top_symm_diff : ⊤ ∆ a = aᶜ := top_symm_diff' _ @[simp] lemma compl_symm_diff : (a ∆ b)ᶜ = a ⇔ b := by simp_rw [symm_diff, compl_sup_distrib, compl_sdiff, bihimp, inf_comm] @[simp] lemma compl_bihimp : (a ⇔ b)ᶜ = a ∆ b := @compl_symm_diff αᵒᵈ _ _ _ @[simp] lemma compl_symm_diff_compl : aᶜ ∆ bᶜ = a ∆ b := sup_comm.trans $ by simp_rw [compl_sdiff_compl, sdiff_eq, symm_diff_eq] @[simp] lemma compl_bihimp_compl : aᶜ ⇔ bᶜ = a ⇔ b := @compl_symm_diff_compl αᵒᵈ _ _ _ @[simp] lemma symm_diff_eq_top : a ∆ b = ⊤ ↔ is_compl a b := by rw [symm_diff_eq', ←compl_inf, inf_eq_top_iff, compl_eq_top, is_compl_iff, disjoint_iff, codisjoint_iff, and.comm] @[simp] lemma bihimp_eq_bot : a ⇔ b = ⊥ ↔ is_compl a b := by rw [bihimp_eq', ←compl_sup, sup_eq_bot_iff, compl_eq_bot, is_compl_iff, disjoint_iff, codisjoint_iff] @[simp] lemma compl_symm_diff_self : aᶜ ∆ a = ⊤ := hnot_symm_diff_self _ @[simp] lemma symm_diff_compl_self : a ∆ aᶜ = ⊤ := symm_diff_hnot_self _ lemma symm_diff_symm_diff_right' : a ∆ (b ∆ c) = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (aᶜ ⊓ b ⊓ cᶜ) ⊔ (aᶜ ⊓ bᶜ ⊓ c) := calc a ∆ (b ∆ c) = (a ⊓ ((b ⊓ c) ⊔ (bᶜ ⊓ cᶜ))) ⊔ (((b ⊓ cᶜ) ⊔ (c ⊓ bᶜ)) ⊓ aᶜ) : by rw [symm_diff_eq, compl_symm_diff, bihimp_eq', symm_diff_eq] ... = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊓ aᶜ) ⊔ (c ⊓ bᶜ ⊓ aᶜ) : by rw [inf_sup_left, inf_sup_right, ←sup_assoc, ←inf_assoc, ←inf_assoc] ... = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (aᶜ ⊓ b ⊓ cᶜ) ⊔ (aᶜ ⊓ bᶜ ⊓ c) : begin congr' 1, { congr' 1, rw [inf_comm, inf_assoc], }, { apply inf_left_right_swap } end variables {a b c} lemma disjoint.le_symm_diff_sup_symm_diff_left (h : disjoint a b) : c ≤ a ∆ c ⊔ b ∆ c := begin transitivity c \ (a ⊓ b), { rw [h.eq_bot, sdiff_bot] }, { rw sdiff_inf, exact sup_le_sup le_sup_right le_sup_right } end lemma disjoint.le_symm_diff_sup_symm_diff_right (h : disjoint b c) : a ≤ a ∆ b ⊔ a ∆ c := by { simp_rw symm_diff_comm a, exact h.le_symm_diff_sup_symm_diff_left } lemma codisjoint.bihimp_inf_bihimp_le_left (h : codisjoint a b) : a ⇔ c ⊓ b ⇔ c ≤ c := h.dual.le_symm_diff_sup_symm_diff_left lemma codisjoint.bihimp_inf_bihimp_le_right (h : codisjoint b c) : a ⇔ b ⊓ a ⇔ c ≤ a := h.dual.le_symm_diff_sup_symm_diff_right end boolean_algebra /-! ### Prod -/ section prod @[simp] lemma symm_diff_fst [generalized_coheyting_algebra α] [generalized_coheyting_algebra β] (a b : α × β) : (a ∆ b).1 = a.1 ∆ b.1 := rfl @[simp] lemma symm_diff_snd [generalized_coheyting_algebra α] [generalized_coheyting_algebra β] (a b : α × β) : (a ∆ b).2 = a.2 ∆ b.2 := rfl @[simp] lemma bihimp_fst [generalized_heyting_algebra α] [generalized_heyting_algebra β] (a b : α × β) : (a ⇔ b).1 = a.1 ⇔ b.1 := rfl @[simp] lemma bihimp_snd [generalized_heyting_algebra α] [generalized_heyting_algebra β] (a b : α × β) : (a ⇔ b).2 = a.2 ⇔ b.2 := rfl end prod /-! ### Pi -/ namespace pi lemma symm_diff_def [Π i, generalized_coheyting_algebra (π i)] (a b : Π i, π i) : a ∆ b = λ i, a i ∆ b i := rfl lemma bihimp_def [Π i, generalized_heyting_algebra (π i)] (a b : Π i, π i) : a ⇔ b = λ i, a i ⇔ b i := rfl @[simp] lemma symm_diff_apply [Π i, generalized_coheyting_algebra (π i)] (a b : Π i, π i) (i : ι) : (a ∆ b) i = a i ∆ b i := rfl @[simp] lemma bihimp_apply [Π i, generalized_heyting_algebra (π i)] (a b : Π i, π i) (i : ι) : (a ⇔ b) i = a i ⇔ b i := rfl end pi
98a6501f985d14ad754e5c4f9a9368ff1573c288
367134ba5a65885e863bdc4507601606690974c1
/src/topology/algebra/continuous_functions.lean
f34ccf6863545fac2756fbae7f18ad3d8207cc43
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
14,533
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Nicolò Cavalleri -/ import topology.algebra.module import topology.continuous_map /-! # Algebraic structures over continuous functions In this file we define instances of algebraic structures over continuous functions. Instances are present both in the case of the subtype of continuous functions and the type of continuous bundled functions. Both implementations have advantages and disadvantages, but many experienced people in Zulip have expressed a preference towards continuous bundled maps, so when there is no particular reason to use the subtype, continuous bundled functions should be used for the sake of uniformity. -/ local attribute [elab_simple] continuous.comp namespace continuous_functions variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {f g : {f : α → β | continuous f }} instance : has_coe_to_fun {f : α → β | continuous f} := ⟨_, subtype.val⟩ end continuous_functions namespace continuous_map @[to_additive] instance has_mul {α : Type*} {β : Type*} [topological_space α] [topological_space β] [has_mul β] [has_continuous_mul β] : has_mul C(α, β) := ⟨λ f g, ⟨f * g, continuous_mul.comp (f.continuous.prod_mk g.continuous : _)⟩⟩ @[to_additive] instance {α : Type*} {β : Type*} [topological_space α] [topological_space β] [has_one β] : has_one C(α, β) := ⟨const (1 : β)⟩ end continuous_map section group_structure /-! ### Group stucture In this section we show that continuous functions valued in a topological group inherit the structure of a group. -/ section subtype @[to_additive] instance continuous_submonoid (α : Type*) (β : Type*) [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : is_submonoid { f : α → β | continuous f } := { one_mem := @continuous_const _ _ _ _ 1, mul_mem := λ f g fc gc, continuous.comp has_continuous_mul.continuous_mul (continuous.prod_mk fc gc : _) } @[to_additive] instance continuous_subgroup (α : Type*) (β : Type*) [topological_space α] [topological_space β] [group β] [topological_group β] : is_subgroup { f : α → β | continuous f } := { inv_mem := λ f fc, continuous.comp (@topological_group.continuous_inv β _ _ _) fc, ..continuous_submonoid α β, }. @[to_additive] instance continuous_monoid {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid { f : α → β | continuous f } := subtype.monoid @[to_additive] instance continuous_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group { f : α → β | continuous f } := subtype.group @[to_additive] instance continuous_comm_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group { f : α → β | continuous f } := @subtype.comm_group _ _ _ (continuous_subgroup α β) -- infer_instance doesn't work?! end subtype section continuous_map @[to_additive] instance continuous_map_semigroup {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup β] [has_continuous_mul β] : semigroup C(α, β) := { mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _, ..continuous_map.has_mul} @[to_additive] instance continuous_map_monoid {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid C(α, β) := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, ..continuous_map_semigroup, ..continuous_map.has_one } @[to_additive] instance continuous_map_comm_monoid {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid β] [has_continuous_mul β] : comm_monoid C(α, β) := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, mul_comm := λ a b, by ext; exact mul_comm _ _, ..continuous_map_semigroup, ..continuous_map.has_one } @[to_additive] instance continuous_map_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group C(α, β) := { inv := λ f, ⟨λ x, (f x)⁻¹, continuous_inv.comp f.continuous⟩, mul_left_inv := λ a, by ext; exact mul_left_inv _, ..continuous_map_monoid } @[to_additive] instance continuous_map_comm_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group C(α, β) := { ..continuous_map_group, ..continuous_map_comm_monoid } end continuous_map end group_structure section ring_structure /-! ### Ring stucture In this section we show that continuous functions valued in a topological ring `R` inherit the structure of a ring. -/ section subtype instance continuous_subring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [ring R] [topological_ring R] : is_subring { f : α → R | continuous f } := { ..continuous_add_subgroup α R, ..continuous_submonoid α R }. instance continuous_ring {α : Type*} {R : Type*} [topological_space α] [topological_space R] [ring R] [topological_ring R] : ring { f : α → R | continuous f } := @subtype.ring _ _ _ (continuous_subring α R) -- infer_instance doesn't work?! instance continuous_comm_ring {α : Type*} {R : Type*} [topological_space α] [topological_space R] [comm_ring R] [topological_ring R] : comm_ring { f : α → R | continuous f } := @subtype.comm_ring _ _ _ (continuous_subring α R) -- infer_instance doesn't work?! end subtype section continuous_map instance continuous_map_semiring {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] : semiring C(α, β) := { left_distrib := λ a b c, by ext; exact left_distrib _ _ _, right_distrib := λ a b c, by ext; exact right_distrib _ _ _, zero_mul := λ a, by ext; exact zero_mul _, mul_zero := λ a, by ext; exact mul_zero _, ..continuous_map_add_comm_monoid, ..continuous_map_monoid } instance continuous_map_ring {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : ring C(α, β) := { ..continuous_map_semiring, ..continuous_map_add_comm_group, } instance continuous_map_comm_ring {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_ring β] [topological_ring β] : comm_ring C(α, β) := { ..continuous_map_semiring, ..continuous_map_add_comm_group, ..continuous_map_comm_monoid,} end continuous_map end ring_structure local attribute [ext] subtype.eq section semimodule_structure /-! ### Semiodule stucture In this section we show that continuous functions valued in a topological semimodule `M` over a topological semiring `R` inherit the structure of a semimodule. -/ section subtype instance continuous_has_scalar {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] [semimodule R M] [topological_semimodule R M] : has_scalar R { f : α → M | continuous f } := ⟨λ r f, ⟨r • f, continuous_const.smul f.property⟩⟩ instance continuous_semimodule {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] [topological_add_group M] [semimodule R M] [topological_semimodule R M] : semimodule R { f : α → M | continuous f } := semimodule.of_core $ { smul := (•), smul_add := λ c f g, by ext x; exact smul_add c (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul c₁ c₂ (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul c₁ c₂ (f x), one_smul := λ f, by ext x; exact one_smul R (f x) } end subtype section continuous_map instance continuous_map_has_scalar {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] : has_scalar R C(α, M) := ⟨λ r f, ⟨r • f, continuous_const.smul f.continuous⟩⟩ instance continuous_map_semimodule {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [has_continuous_add M] [semimodule R M] [topological_semimodule R M] : semimodule R C(α, M) := { smul := (•), smul_add := λ c f g, by { ext, exact smul_add c (f x) (g x) }, add_smul := λ c₁ c₂ f, by { ext, exact add_smul c₁ c₂ (f x) }, mul_smul := λ c₁ c₂ f, by { ext, exact mul_smul c₁ c₂ (f x) }, one_smul := λ f, by { ext, exact one_smul R (f x) }, zero_smul := λ f, by { ext, exact zero_smul _ _ }, smul_zero := λ r, by { ext, exact smul_zero _ } } end continuous_map end semimodule_structure section algebra_structure /-! ### Algebra structure In this section we show that continuous functions valued in a topological algebra `A` over a ring `R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra is obtained by requiring that `A` be both a `topological_semimodule` and a `topological_semiring` (by now we require `topological_ring`: see TODO below).-/ section subtype variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [ring A] [algebra R A] [topological_ring A] /-- Continuous constant functions as a `ring_hom`. -/ def continuous.C : R →+* { f : α → A | continuous f } := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } variables [topological_space R] [topological_semimodule R A] instance : algebra R { f : α → A | continuous f } := { to_ring_hom := continuous.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, ..continuous_semimodule, ..continuous_ring } /- TODO: We are assuming `A` to be a ring and not a semiring just because there is not yet an instance of semiring. In turn, we do not want to define yet an instance of semiring because there is no `is_subsemiring` but only `subsemiring`, and it will make sense to change this when the whole file will have no more `is_subobject`s but only `subobject`s. It does not make sense to change it yet in this direction as `subring` does not exist yet, so everything is being blocked by `subring`: afterwards everything will need to be updated to the new conventions of Mathlib. Then the instance of `topological_ring` can also be removed, as it is below for `continuous_map`. -/ end subtype section continuous_map variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] /-- Continuous constant functions as a `ring_hom`. -/ def continuous_map.C : R →+* C(α, A) := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } variables [topological_space R] [topological_semimodule R A] instance continuous_map_algebra : algebra R C(α, A) := { to_ring_hom := continuous_map.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, ..continuous_map_semiring } end continuous_map end algebra_structure section module_over_continuous_functions /-! ### Structure as module over scalar functions If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M` is naturally a module over the ring of continuous functions from `α` to `M`. -/ section subtype instance continuous_has_scalar' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] [semimodule R M] [topological_semimodule R M] : has_scalar { f : α → R | continuous f } { f : α → M | continuous f } := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance continuous_module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_group M] [topological_add_group M] [module R M] [topological_module R M] : module { f : α → R | continuous f } { f : α → M | continuous f } := semimodule.of_core $ { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x) } end subtype section continuous_map instance continuous_map_has_scalar' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] : has_scalar C(α, R) C(α, M) := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance continuous_map_module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_monoid M] [has_continuous_add M] [semimodule R M] [topological_semimodule R M] : semimodule C(α, R) C(α, M) := { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x), zero_smul := λ f, by ext x; exact zero_smul _ _, smul_zero := λ r, by ext x; exact smul_zero _, } end continuous_map end module_over_continuous_functions
aba15b6761c5b6e2b371b83122fa461f1e49f035
137c667471a40116a7afd7261f030b30180468c2
/src/analysis/calculus/parametric_integral.lean
5db27ab9e8b4c20c1a918bfe17c0b94dcd38822f
[ "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
14,753
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import measure_theory.set_integral import analysis.calculus.mean_value /-! # Derivatives of integrals depending on parameters A parametric integral is a function with shape `f = λ x : H, ∫ a : α, F x a ∂μ` for some `F : H → α → E`, where `H` and `E` are normed spaces and `α` is a measured space with measure `μ`. We already know from `continuous_of_dominated` in `measure_theory.bochner_integral` how to guarantee that `f` is continuous using the dominated convergence theorem. In this file, we want to express the derivative of `f` as the integral of the derivative of `F` with respect to `x`. ## Main results As explained above, all results express the derivative of a parametric integral as the integral of a derivative. The variations come from the assumptions and from the different ways of expressing derivative, especially Fréchet derivatives vs elementary derivative of function of one real variable. * `has_fderiv_at_of_dominated_loc_of_lip`: this version assumes `F x` is ae-measurable for x near `x₀`, `F x₀` is integrable, `λ x, F x a` has derivative `F' a : H →L[ℝ] E` at `x₀` which is ae-measurable, `λ x, F x a` is locally Lipschitz near `x₀` for almost every `a`, with a Lipschitz bound which is integrable with respect to `a`. A subtle point is that the "near x₀" in the last condition has to be uniform in `a`. This is controlled by a positive number `ε`. * `has_fderiv_at_of_dominated_of_fderiv_le`: this version assume `λ x, F x a` has derivative `F' x a` for `x` near `x₀` and `F' x` is bounded by an integrable function independent from `x` near `x₀`. `has_deriv_at_of_dominated_loc_of_lip` and `has_deriv_at_of_dominated_loc_of_deriv_le ` are versions of the above two results that assume `H = ℝ` and use the high-school derivative `deriv` instead of Fréchet derivative `fderiv`. -/ noncomputable theory open topological_space measure_theory filter metric open_locale topological_space filter variables {α : Type*} [measurable_space α] {μ : measure α} {E : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [second_countable_topology E] [measurable_space E] [borel_space E] {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H →L[ℝ] E] /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` with integrable Lipschitz bound (with a ball radius independent of `a`), and `F x` is ae-measurable for `x` in the same ball. See `has_fderiv_at_of_dominated_loc_of_lip` for a slightly more general version. -/ lemma has_fderiv_at_of_dominated_loc_of_lip' {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ x ∈ ball x₀ ε, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have nneg : ∀ x, 0 ≤ ∥x - x₀∥⁻¹ := λ x, inv_nonneg.mpr (norm_nonneg _) , set b : α → ℝ := λ a, abs (bound a), have b_int : integrable b μ := bound_integrable.norm, have b_nonneg : ∀ a, 0 ≤ b a := λ a, abs_nonneg _, have hF_int' : ∀ x ∈ ball x₀ ε, integrable (F x) μ, { intros x x_in, have : ∀ᵐ a ∂μ, ∥F x₀ a - F x a∥ ≤ ε * ∥(bound a : ℝ)∥, { apply h_lipsch.mono, intros a ha, rw lipschitz_on_with_iff_norm_sub_le at ha, apply (ha x₀ x₀_in x x_in).trans, rw [mul_comm, nnreal.coe_nnabs, real.norm_eq_abs], rw [mem_ball, dist_eq_norm, norm_sub_rev] at x_in, exact mul_le_mul_of_nonneg_right (le_of_lt x_in) (abs_nonneg _) }, exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int (integrable.const_mul bound_integrable.norm ε) this }, have hF'_int : integrable F' μ, { have : ∀ᵐ a ∂μ, ∥F' a∥ ≤ b a, { apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_diff, ha_lip⟩, exact ha_diff.le_of_lip (ball_mem_nhds _ ε_pos) ha_lip }, exact b_int.mono' hF'_meas this }, refine ⟨hF'_int, _⟩, have h_ball: ball x₀ ε ∈ 𝓝 x₀ := ball_mem_nhds x₀ ε_pos, have : ∀ᶠ x in 𝓝 x₀, ∥x - x₀∥⁻¹ * ∥∫ a, F x a ∂μ - ∫ a, F x₀ a ∂μ - (∫ a, F' a ∂μ) (x - x₀)∥ = ∥∫ a, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀)) ∂μ∥, { apply mem_sets_of_superset (ball_mem_nhds _ ε_pos), intros x x_in, rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul, integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int], exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int, hF'_int.apply_continuous_linear_map _] }, rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero, ← show ∫ (a : α), ∥x₀ - x₀∥⁻¹ • (F x₀ a - F x₀ a - (F' a) (x₀ - x₀)) ∂μ = 0, by simp], apply tendsto_integral_filter_of_dominated_convergence, { apply is_countably_generated_nhds }, { filter_upwards [h_ball], intros x x_in, apply ae_measurable.const_smul, exact ((hF_meas _ x_in).sub (hF_meas _ x₀_in)).sub (hF'_meas.apply_continuous_linear_map _) }, { simp [measurable_const] }, { apply mem_sets_of_superset h_ball, intros x hx, apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_deriv, ha_bound⟩, show ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ ≤ b a + ∥F' a∥, replace ha_bound : ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥, { rw lipschitz_on_with_iff_norm_sub_le at ha_bound, exact ha_bound _ hx _ x₀_in }, calc ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ = ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a) - ∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : by rw smul_sub ... ≤ ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a)∥ + ∥∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : norm_sub_le _ _ ... = ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a∥ + ∥x - x₀∥⁻¹ * ∥F' a (x - x₀)∥ : by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _} ... ≤ ∥x - x₀∥⁻¹ * (b a * ∥x - x₀∥) + ∥x - x₀∥⁻¹ * (∥F' a∥ * ∥x - x₀∥) : add_le_add _ _ ... ≤ b a + ∥F' a∥ : _, exact mul_le_mul_of_nonneg_left ha_bound (nneg _), apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _), by_cases h : ∥x - x₀∥ = 0, { simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) }, { field_simp [h] } }, { exact b_int.add hF'_int.norm }, { apply h_diff.mono, intros a ha, suffices : tendsto (λ x, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))) (𝓝 x₀) (𝓝 0), by simpa, rw tendsto_zero_iff_norm_tendsto_zero, have : (λ x, ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a - F' a (x - x₀)∥) = λ x, ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥, { ext x, rw norm_smul_of_nonneg (nneg _) }, rwa [has_fderiv_at_iff_tendsto, this] at ha }, end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_loc_of_lip {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lip : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin obtain ⟨ε', ε'_pos, h'⟩ : ∃ ε' > 0, ∀ x ∈ ball x₀ ε', ae_measurable (F x) μ, by simpa using nhds_basis_ball.eventually_iff.mp hF_meas, set δ := min ε ε', have δ_pos : 0 < δ := lt_min ε_pos ε'_pos, replace h' : ∀ x, x ∈ ball x₀ δ → ae_measurable (F x) μ, { intros x x_in, exact h' _ (ball_subset_ball (min_le_right ε ε') x_in) }, replace h_lip : ∀ᵐ (a : α) ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ δ), { apply h_lip.mono, intros a lip, exact lip.mono (ball_subset_ball $ min_le_left ε ε') }, apply has_fderiv_at_of_dominated_loc_of_lip' δ_pos ; assumption end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_of_fderiv_le {F : H → α → E} {F' : H → α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x a) (F' x a) x) : has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ x, F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, have bound_nonneg : 0 ≤ bound a := (norm_nonneg (F' x₀ a)).trans (ha_bound x₀ x₀_in), rw show real.nnabs (bound a) = real.to_nnreal (bound a), by simp [bound_nonneg], apply convex.lipschitz_on_with_of_norm_has_fderiv_within_le _ ha_bound (convex_ball _ _), intros x x_in, exact (ha_deriv x x_in).has_fderiv_within_at, }, exact (has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀).2 end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_lip {F : ℝ → α → E} {F' : α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) {bound : α → ℝ} (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' a) x₀) : (integrable F' μ) ∧ has_deriv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have hm := (continuous_linear_map.smul_rightL ℝ ℝ E 1).continuous.measurable.comp_ae_measurable hF'_meas, cases has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hm h_lipsch bound_integrable h_diff with hF'_int key, replace hF'_int : integrable F' μ, { rw [← integrable_norm_iff hm] at hF'_int, simpa only [integrable_norm_iff, hF'_meas, one_mul, continuous_linear_map.norm_id_field', continuous_linear_map.norm_smul_rightL_apply] using hF'_int}, refine ⟨hF'_int, _⟩, simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊢, rwa continuous_linear_map.integral_comp_comm _ hF'_int at key, all_goals { apply_instance, }, end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_deriv_le {F : ℝ → α → E} {F' : ℝ → α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) {bound : α → ℝ} (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x a) (F' x a) x) : (integrable (F' x₀) μ) ∧ has_deriv_at (λn, ∫ a, F n a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ (x : ℝ), F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, have bound_nonneg : 0 ≤ bound a := (norm_nonneg (F' x₀ a)).trans (ha_bound x₀ x₀_in), rw show real.nnabs (bound a) = real.to_nnreal (bound a), by simp [bound_nonneg], apply convex.lipschitz_on_with_of_norm_has_deriv_within_le (convex_ball _ _) (λ x x_in, (ha_deriv x x_in).has_deriv_within_at) ha_bound }, exact has_deriv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀ end
857c645646756f477b6fc798e412424a132f009f
4727251e0cd73359b15b664c3170e5d754078599
/src/control/equiv_functor.lean
5305c7e0136e6eeea1926d4cb72e975b9167c9e7
[ "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
3,278
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.equiv.basic /-! # Functions functorial with respect to equivalences An `equiv_functor` is a function from `Type → Type` equipped with the additional data of coherently mapping equivalences to equivalences. In categorical language, it is an endofunctor of the "core" of the category `Type`. -/ universes u₀ u₁ u₂ v₀ v₁ v₂ open function /-- An `equiv_functor` is only functorial with respect to equivalences. To construct an `equiv_functor`, it suffices to supply just the function `f α → f β` from an equivalence `α ≃ β`, and then prove the functor laws. It's then a consequence that this function is part of an equivalence, provided by `equiv_functor.map_equiv`. -/ class equiv_functor (f : Type u₀ → Type u₁) := (map : Π {α β}, (α ≃ β) → (f α → f β)) (map_refl' : Π α, map (equiv.refl α) = @id (f α) . obviously) (map_trans' : Π {α β γ} (k : α ≃ β) (h : β ≃ γ), map (k.trans h) = (map h) ∘ (map k) . obviously) restate_axiom equiv_functor.map_refl' restate_axiom equiv_functor.map_trans' attribute [simp] equiv_functor.map_refl namespace equiv_functor section variables (f : Type u₀ → Type u₁) [equiv_functor f] {α β : Type u₀} (e : α ≃ β) /-- An `equiv_functor` in fact takes every equiv to an equiv. -/ def map_equiv : f α ≃ f β := { to_fun := equiv_functor.map e, inv_fun := equiv_functor.map e.symm, left_inv := λ x, by { convert (congr_fun (equiv_functor.map_trans e e.symm) x).symm, simp, }, right_inv := λ y, by { convert (congr_fun (equiv_functor.map_trans e.symm e) y).symm, simp, }, } @[simp] lemma map_equiv_apply (x : f α) : map_equiv f e x = equiv_functor.map e x := rfl lemma map_equiv_symm_apply (y : f β) : (map_equiv f e).symm y = equiv_functor.map e.symm y := rfl @[simp] lemma map_equiv_refl (α) : map_equiv f (equiv.refl α) = equiv.refl (f α) := by simpa [equiv_functor.map_equiv] @[simp] lemma map_equiv_symm : (map_equiv f e).symm = map_equiv f e.symm := equiv.ext $ map_equiv_symm_apply f e /-- The composition of `map_equiv`s is carried over the `equiv_functor`. For plain `functor`s, this lemma is named `map_map` when applied or `map_comp_map` when not applied. -/ @[simp] lemma map_equiv_trans {γ : Type u₀} (ab : α ≃ β) (bc : β ≃ γ) : (map_equiv f ab).trans (map_equiv f bc) = map_equiv f (ab.trans bc) := equiv.ext $ λ x, by simp [map_equiv, map_trans'] end @[priority 100] instance of_is_lawful_functor (f : Type u₀ → Type u₁) [functor f] [is_lawful_functor f] : equiv_functor f := { map := λ α β e, functor.map e, map_refl' := λ α, by { ext, apply is_lawful_functor.id_map, }, map_trans' := λ α β γ k h, by { ext x, apply (is_lawful_functor.comp_map k h x), } } lemma map_equiv.injective (f : Type u₀ → Type u₁) [applicative f] [is_lawful_applicative f] {α β : Type u₀} (h : ∀ γ, function.injective (pure : γ → f γ)) : function.injective (@equiv_functor.map_equiv f _ α β) := λ e₁ e₂ H, equiv.ext $ λ x, h β (by simpa [equiv_functor.map] using equiv.congr_fun H (pure x)) end equiv_functor
a699b1f3224a99d922115306c3ce73d521982f5e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/229.lean
3653a727c507b02b3f4a5c7113ade338868f68bc
[ "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
693
lean
def f1 (xs : Option (Array Nat)) : Nat := match xs with | some #[x, y] => x | _ => 0 def f2 (xs : Option (Array Nat)) : Nat := match xs with | some #[0, y] => y | some #[x+1, y] => x | _ => 0 theorem ex1 : f2 (some #[0, 2]) = 2 := rfl theorem ex2 : f2 (some #[10, 2]) = 9 := rfl def f3 (xs : Option (Array (Array Nat))) : Nat := match xs with | some #[#[0], #[x]] => x | some #[#[x+1], #[y]] => x | _ => 0 theorem ex3 : f3 (some #[#[10], #[5]]) = 9 := rfl theorem ex4 : f3 (some #[#[0], #[5]]) = 5 := rfl theorem ex5 : f3 (some #[#[0], #[5], #[4]]) = 0 := rfl #check match some #[1, 2] with | some #[x, y] => x | _ => 0
44ea99810bb9747211d773ac91b0797bd54893b9
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/class2.lean
434df42a9b4a33670f4ea3c1d0a9d172f893bcfc
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
190
lean
import logic data.prod data.num open prod nonempty inhabited theorem H {A B : Type} (H1 : inhabited A) : inhabited (Prop × A × (B → num)) := _ (* print(get_env():find("H"):value()) *)
5c618172708ab285589bc17ae5877fc7648334bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/extension/well.lean
76c290e56f5d060990c7e3228c661a6967b4f236
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,271
lean
/- Copyright (c) 2022 Yaël Dillies, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Junyan Xu -/ import data.prod.lex import set_theory.ordinal.arithmetic /-! # Extend a well-founded order to a well-order This file constructs a well-order (linear well-founded order) which is an extension of a given well-founded order. ## Proof idea We can map our order into two well-orders: * the first map respects the order but isn't necessarily injective. Namely, this is the *rank* function `rank : α → ordinal`. * the second map is injective but doesn't necessarily respect the order. This is an arbitrary well-order on `α`. Then their lexicographic product is a well-founded linear order which our original order injects in. -/ universe u variables {α : Type u} {r : α → α → Prop} namespace well_founded variable (hwf : well_founded r) include hwf /-- An arbitrary well order on `α` that extends `r`. The construction maps `r` into two well-orders: the first map is `well_founded.rank`, which is not necessarily injective but respects the order `r`; the other map is the identity (with an arbitrarily chosen well-order on `α`), which is injective but doesn't respect `r`. By taking the lexicographic product of the two, we get both properties, so we can pull it back and get an well-order that extend our original order `r`. Another way to view this is that we choose an arbitrary well-order to serve as a tiebreak between two elements of same rank. -/ noncomputable def well_order_extension : linear_order α := let l : linear_order α := is_well_order.linear_order well_ordering_rel in by exactI @linear_order.lift' α (ordinal ×ₗ α) _ (λ a : α, (well_founded.rank.{u u} hwf a, a)) (λ _ _, congr_arg prod.snd) instance well_order_extension.is_well_founded_lt : is_well_founded α hwf.well_order_extension.lt := ⟨inv_image.wf _ $ prod.lex_wf ordinal.well_founded_lt.wf well_ordering_rel.is_well_order.wf⟩ /-- Any well-founded relation can be extended to a well-ordering on that type. -/ lemma exists_well_order_ge : ∃ s, r ≤ s ∧ is_well_order α s := ⟨hwf.well_order_extension.lt, λ a b h, prod.lex.left _ _ (hwf.rank_lt_of_rel h), by split⟩ end well_founded /-- A type alias for `α`, intended to extend a well-founded order on `α` to a well-order. -/ def well_order_extension (α) : Type* := α instance [inhabited α] : inhabited (well_order_extension α) := ‹inhabited (well_order_extension α)› /-- "Identity" equivalence between a well-founded order and its well-order extension. -/ def to_well_order_extension : α ≃ well_order_extension α := equiv.refl _ noncomputable instance [has_lt α] [well_founded_lt α] : linear_order (well_order_extension α) := (is_well_founded.wf : @well_founded α (<)).well_order_extension instance well_order_extension.well_founded_lt [has_lt α] [well_founded_lt α] : well_founded_lt (well_order_extension α) := well_founded.well_order_extension.is_well_founded_lt _ lemma to_well_order_extension_strict_mono [preorder α] [well_founded_lt α] : strict_mono (to_well_order_extension : α → well_order_extension α) := λ a b h, prod.lex.left _ _ $ well_founded.rank_lt_of_rel _ h
f2845a6a773adcdf0308533a214b3aadb121e7f8
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Elab/App.lean
920273258df72f12ec9c055b952eed2d3d34e5d4
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,019
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindMVar import Lean.Parser.Term import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.Arg namespace Lean.Elab.Term open Meta builtin_initialize elabWithoutExpectedTypeAttr : TagAttribute ← registerTagAttribute `elabWithoutExpectedType "mark that applications of the given declaration should be elaborated without the expected type" def hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool := elabWithoutExpectedTypeAttr.hasTag env declName instance : ToString Arg := ⟨fun | Arg.stx val => toString val | Arg.expr val => toString val⟩ instance : ToString NamedArg where toString s := "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")" def throwInvalidNamedArg {α} (namedArg : NamedArg) (fn? : Option Name) : TermElabM α := withRef namedArg.ref <| match fn? with | some fn => throwError "invalid argument name '{namedArg.name}' for function '{fn}'" | none => throwError "invalid argument name '{namedArg.name}' for function" private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do let argType ← inferType arg ensureHasTypeAux expectedType argType arg f /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun? (α : Expr) (a : Expr) : TermElabM (Option Expr) := do let v ← mkFreshLevelMVar let type ← mkArrow α (mkSort v) let γ ← mkFreshExprMVar type let u ← getLevel α let coeFunInstType := mkAppN (Lean.mkConst ``CoeFun [u, v]) #[α, γ] let mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``coeFun [u, v]) #[α, γ, a, mvar] else return none catch _ => return none def synthesizeAppInstMVars (instMVars : Array MVarId) : TermElabM Unit := for mvarId in instMVars do unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass namespace ElabAppArgs /- Auxiliary structure for elaborating the application `f args namedArgs`. -/ structure State where explicit : Bool -- true if `@` modifier was used f : Expr fType : Expr args : List Arg -- remaining regular arguments namedArgs : List NamedArg -- remaining named arguments to be processed ellipsis : Bool := false expectedType? : Option Expr etaArgs : Array Expr := #[] toSetErrorCtx : Array MVarId := #[] -- metavariables that we need the set the error context using the application being built instMVars : Array MVarId := #[] -- metavariables for the instance implicit arguments that have already been processed -- The following field is used to implement the `propagateExpectedType` heuristic. propagateExpected : Bool -- true when expectedType has not been propagated yet abbrev M := StateRefT State TermElabM /- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/ private def addInstMVar (mvarId : MVarId) : M Unit := modify fun s => { s with instMVars := s.instMVars.push mvarId } /- Try to synthesize metavariables are `instMVars` using type class resolution. The ones that cannot be synthesized yet are registered. Remark: we use this method before trying to apply coercions to function. -/ def synthesizeAppInstMVars : M Unit := do let s ← get let instMVars := s.instMVars modify fun s => { s with instMVars := #[] } Lean.Elab.Term.synthesizeAppInstMVars instMVars /- fType may become a forallE after we synthesize pending metavariables. -/ private def synthesizePendingAndNormalizeFunType : M Unit := do synthesizeAppInstMVars synthesizeSyntheticMVars let s ← get let fType ← whnfForall s.fType if fType.isForall then modify fun s => { s with fType := fType } else match (← tryCoeFun? fType s.f) with | some f => let fType ← inferType f modify fun s => { s with f := f, fType := fType } | none => for namedArg in s.namedArgs do let f := s.f.getAppFn if f.isConst then throwInvalidNamedArg namedArg f.constName! else throwInvalidNamedArg namedArg none throwError "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}" /- Normalize and return the function type. -/ private def normalizeFunType : M Expr := do let s ← get let fType ← whnfForall s.fType modify fun s => { s with fType := fType } pure fType /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! def eraseNamedArgCore (namedArgs : List NamedArg) (binderName : Name) : List NamedArg := namedArgs.filter (·.name != binderName) /- Remove named argument with name `binderName` from `namedArgs`. -/ def eraseNamedArg (binderName : Name) : M Unit := modify fun s => { s with namedArgs := eraseNamedArgCore s.namedArgs binderName } /- Add a new argument to the result. That is, `f := f arg`, update `fType`. This method assumes `fType` is a function type. -/ private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /- Elaborate the given `Arg` and add it to the result. See `addNewArg`. Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/ private def elabAndAddNewArg (arg : Arg) : M Unit := do let s ← get let expectedType ← getArgExpectedType match arg with | Arg.expr val => let arg ← ensureArgType s.f val expectedType addNewArg arg | Arg.stx val => let val ← elabTerm val expectedType let arg ← ensureArgType s.f val expectedType addNewArg arg /- Return true if the given type contains `OptParam` or `AutoParams` -/ private def hasOptAutoParams (type : Expr) : M Bool := do forallTelescopeReducing type fun xs type => xs.anyM fun x => do let xType ← inferType x return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome /- Return true if `fType` contains `OptParam` or `AutoParams` -/ private def fTypeHasOptAutoParams : M Bool := do hasOptAutoParams (← get).fType /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. Remark: `(explicit : Bool) == true` when `@` modifier is used. -/ private partial def getForallBody (explicit : Bool) : Nat → List NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == n with | some _ => getForallBody explicit i (eraseNamedArgCore namedArgs n) b | none => if !explicit && !c.binderInfo.isExplicit then getForallBody explicit i namedArgs b else if i > 0 then getForallBody explicit (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody explicit i namedArgs b else some type | 0, [], type => some type | _, _, _ => none private def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool := match nextArg with | Arg.expr _ => false -- it has already been elaborated | Arg.stx stx => -- TODO: make this configurable? stx.getKind != ``Lean.Parser.Term.hole && stx.getKind != ``Lean.Parser.Term.syntheticHole && stx.getKind != ``Lean.Parser.Term.byTactic /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean Add.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`). 2- The resultant type contains optional/auto params. We have considered adding the following extra conditions a) The resultant type does not contain any type metavariable. b) The resultant type contains a nontype metavariable. These two conditions would restrict the method to simple functions that are "morally" in the Hindley&Milner fragment. If users need to disable expected type propagation, we can add an attribute `[elabWithoutExpectedType]`. -/ private def propagateExpectedType (arg : Arg) : M Unit := do if shouldPropagateExpectedTypeFor arg then let s ← get -- TODO: handle s.etaArgs.size > 0 unless !s.etaArgs.isEmpty || !s.propagateExpected do match s.expectedType? with | none => pure () | some expectedType => /- We don't propagate `Prop` because we often use `Prop` as a more general "Bool" (e.g., `if-then-else`). If we propagate `expectedType == Prop` in the following examples, the elaborator would fail ``` def f1 (s : Nat × Bool) : Bool := if s.2 then false else true def f2 (s : List Bool) : Bool := if s.head! then false else true def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true ``` They would all fail for the same reason. So, let's focus on the first one. We would elaborate `s.2` with `expectedType == Prop`. Before we elaborate `s`, this method would be invoked, and `s.fType` is `?α × ?β → ?β` and after propagation we would have `?α × Prop → Prop`. Then, when we would try to elaborate `s`, and get a type error because `?α × Prop` cannot be unified with `Nat × Bool` Most users would have a hard time trying to understand why these examples failed. Here is a possible alternative workarounds. We give up the idea of using `Prop` at `if-then-else`. Drawback: users use `if-then-else` with conditions that are not Decidable. So, users would have to embrace `propDecidable` and `choice`. This may not be that bad since the developers and users don't seem to care about constructivism. We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/ if expectedType.isProp then modify fun s => { s with propagateExpected := false } else let numRemainingArgs := s.args.length trace[Elab.app.propagateExpectedType] "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}" match getForallBody s.explicit numRemainingArgs s.namedArgs s.fType with | none => pure () | some fTypeBody => unless fTypeBody.hasLooseBVars do unless (← hasOptAutoParams fTypeBody) do trace[Elab.app.propagateExpectedType] "{expectedType} =?= {fTypeBody}" if (← isDefEq expectedType fTypeBody) then /- Note that we only set `propagateExpected := false` when propagation has succeeded. -/ modify fun s => { s with propagateExpected := false } /- Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`, and then execute the continuation `k`.-/ private def addEtaArg (k : M Expr) : M Expr := do let n ← getBindingName let type ← getArgExpectedType withLocalDeclD n type fun x => do modify fun s => { s with etaArgs := s.etaArgs.push x } addNewArg x k /- This method execute after all application arguments have been processed. -/ private def finalize : M Expr := do let s ← get let mut e := s.f -- all user explicit arguments have been consumed trace[Elab.app.finalize] e let ref ← getRef -- Register the error context of implicits for mvarId in s.toSetErrorCtx do registerMVarErrorImplicitArgInfo mvarId ref e if !s.etaArgs.isEmpty then e ← mkLambdaFVars s.etaArgs e /- Remark: we should not use `s.fType` as `eType` even when `s.etaArgs.isEmpty`. Reason: it may have been unfolded. -/ let eType ← inferType e trace[Elab.app.finalize] "after etaArgs, {e} : {eType}" match s.expectedType? with | none => pure () | some expectedType => trace[Elab.app.finalize] "expected type: {expectedType}" -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. discard <| isDefEq expectedType eType synthesizeAppInstMVars pure e private def addImplicitArg (k : M Expr) : M Expr := do let argType ← getArgExpectedType let arg ← mkFreshExprMVar argType modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! } addNewArg arg k /- Return true if there is a named argument that depends on the next argument. -/ private def anyNamedArgDependsOnCurrent : M Bool := do let s ← get if s.namedArgs.isEmpty then return false else forallTelescopeReducing s.fType fun xs _ => do let curr := xs[0] for i in [1:xs.size] do let xDecl ← getLocalDecl xs[i].fvarId! if s.namedArgs.any fun arg => arg.name == xDecl.userName then if (← getMCtx).localDeclDependsOn xDecl curr.fvarId! then return true return false /- Process a `fType` of the form `(x : A) → B x`. This method assume `fType` is a function type -/ private def processExplictArg (k : M Expr) : M Expr := do let s ← get match s.args with | arg::args => propagateExpectedType arg modify fun s => { s with args := args } elabAndAddNewArg arg k | _ => let argType ← getArgExpectedType match s.explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with | false, some defVal, _ => addNewArg defVal; k | false, _, some (Expr.const tacticDecl _ _) => let env ← getEnv let opts ← getOptions match evalSyntaxConstant env opts tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => -- TODO(Leo): does this work correctly for tactic sequences? let tacticBlock ← `(by $tacticSyntax) let argType := argType.getArg! 0 -- `autoParam type := by tactic` ==> `type` let argNew := Arg.stx tacticBlock propagateExpectedType argNew elabAndAddNewArg argNew k | false, _, some _ => throwError "invalid autoParam, argument must be a constant" | _, _, _ => if !s.namedArgs.isEmpty then if (← anyNamedArgDependsOnCurrent) then addImplicitArg k else addEtaArg k else if !s.explicit then if (← fTypeHasOptAutoParams) then addEtaArg k else if (← get).ellipsis then addImplicitArg k else finalize else finalize /- Process a `fType` of the form `{x : A} → B x`. This method assume `fType` is a function type -/ private def processImplicitArg (k : M Expr) : M Expr := do if (← get).explicit then processExplictArg k else addImplicitArg k /- Return true if the next argument at `args` is of the form `_` -/ private def isNextArgHole : M Bool := do match (← get).args with | Arg.stx (Syntax.node ``Lean.Parser.Term.hole _) :: _ => pure true | _ => pure false /- Process a `fType` of the form `[x : A] → B x`. This method assume `fType` is a function type -/ private def processInstImplicitArg (k : M Expr) : M Expr := do if (← get).explicit then if (← isNextArgHole) then /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic modify fun s => { s with args := s.args.tail! } addInstMVar arg.mvarId! addNewArg arg k else processExplictArg k else let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic addInstMVar arg.mvarId! addNewArg arg k /- Return true if there are regular or named arguments to be processed. -/ private def hasArgsToProcess : M Bool := do let s ← get pure $ !s.args.isEmpty || !s.namedArgs.isEmpty /- Elaborate function application arguments. -/ partial def main : M Expr := do let s ← get let fType ← normalizeFunType if fType.isForall then let binderName := fType.bindingName! let binfo := fType.bindingInfo! let s ← get match s.namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == binderName with | some namedArg => propagateExpectedType namedArg.val eraseNamedArg binderName elabAndAddNewArg namedArg.val main | none => match binfo with | BinderInfo.implicit => processImplicitArg main | BinderInfo.instImplicit => processInstImplicitArg main | _ => processExplictArg main else if (← hasArgsToProcess) then synthesizePendingAndNormalizeFunType main else finalize end ElabAppArgs private def propagateExpectedTypeFor (f : Expr) : TermElabM Bool := match f.getAppFn.constName? with | some declName => return !hasElabWithoutExpectedType (← getEnv) declName | _ => return true def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do let fType ← inferType f let fType ← instantiateMVars fType trace[Elab.app.args] "explicit: {explicit}, {f} : {fType}" unless namedArgs.isEmpty && args.isEmpty do tryPostponeIfMVar fType ElabAppArgs.main.run' { args := args.toList, expectedType? := expectedType?, explicit := explicit, ellipsis := ellipsis, namedArgs := namedArgs.toList, f := f, fType := fType propagateExpected := (← propagateExpectedTypeFor f) } /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution where | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseStructName : Name) (structName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError "{msg}{indentExpr e}\nhas type{indentExpr eType}" /-- `findMethod? env S fName`. 1- If `env` contains `S ++ fName`, return `(S, S++fName)` 2- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o 3- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/ private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name × Name) := let fullName := structName ++ fieldName match env.find? fullName with | some _ => some (structName, fullName) | none => let fullNamePrv := mkPrivateName env fullName match env.find? fullNamePrv with | some _ => some (structName, fullNamePrv) | none => if isStructure env structName then (getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName else none private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do match eType.getAppFn.constName?, lval with | some structName, LVal.fieldIdx _ idx => if idx == 0 then throwError "invalid projection, index must be greater than 0" let env ← getEnv unless isStructureLike env structName do throwLValError e eType "invalid projection, structure expected" let numFields := getStructureLikeNumFields env structName if idx - 1 < numFields then if isStructure env structName then let fieldNames := getStructureFields env structName return LValResolution.projFn structName structName fieldNames[idx - 1] else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ return LValResolution.projIdx structName (idx - 1) else throwLValError e eType m!"invalid projection, structure has only {numFields} field(s)" | some structName, LVal.fieldName _ fieldName _ _ => let env ← getEnv let searchEnv : Unit → TermElabM LValResolution := fun _ => do match findMethod? env structName (Name.mkSimple fieldName) with | some (baseStructName, fullName) => pure $ LValResolution.const baseStructName structName fullName | none => throwLValError e eType m!"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'" -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do let fullName := Name.mkStr structName fieldName let currNamespace ← getCurrNamespace let localName := fullName.replacePrefix currNamespace Name.anonymous let lctx ← getLCtx match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv () | none => searchEnv () if isStructure env structName then match findField? env structName (Name.mkSimple fieldName) with | some baseStructName => pure $ LValResolution.projFn baseStructName structName (Name.mkSimple fieldName) | none => searchCtx () else searchCtx () | some structName, LVal.getOp _ idx => let env ← getEnv let fullName := Name.mkStr structName "getOp" match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError e eType m!"invalid [..] notation because environment does not contain '{fullName}'" | none, LVal.fieldName _ _ (some suffix) _ => if e.isConst then throwUnknownConstant (e.constName! ++ suffix) else throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" | _, LVal.getOp _ idx => throwLValError e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" /- whnfCore + implicit consumption. Example: given `e` with `eType := {α : Type} → (fun β => List β) α `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/ private partial def consumeImplicits (stx : Syntax) (e eType : Expr) : TermElabM (Expr × Expr) := do let eType ← whnfCore eType match eType with | Expr.forallE n d b c => if c.binderInfo.isImplicit then let mvar ← mkFreshExprMVar d registerMVarErrorHoleInfo mvar.mvarId! stx consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) else if c.binderInfo.isInstImplicit then let mvar ← mkInstMVar d consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) else match d.getOptParamDefault? with | some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal) -- TODO: we do not handle autoParams here. | _ => pure (e, eType) | _ => pure (e, eType) private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) : TermElabM (Expr × LValResolution) := do let (e, eType) ← consumeImplicits lval.getRef e eType tryPostponeIfMVar eType try let lvalRes ← resolveLValAux e eType lval pure (e, lvalRes) catch | ex@(Exception.error _ _) => let eType? ← unfoldDefinition? eType match eType? with | some eType => resolveLValLoop lval e eType (previousExceptions.push ex) | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(Exception.internal _ _) => throw ex private def resolveLVal (e : Expr) (lval : LVal) : TermElabM (Expr × LValResolution) := do let eType ← inferType e resolveLValLoop lval e eType #[] private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do let env ← getEnv match getPathToBaseStructure? env baseStructName structName with | none => throwError "failed to access field in parent structure" | some path => let mut e := e for projFunName in path do let projFn ← mkConst projFunName e ← elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false) return e /- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`. This method first finds the parameter with a type of the form `(baseName ...)`. When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`. Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`. Remark: `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr) : TermElabM (Array Arg × Array NamedArg) := forallTelescopeReducing fType fun xs _ => do let mut argIdx := 0 -- position of the next explicit argument let mut remainingNamedArgs := namedArgs for i in [:xs.size] do let x := xs[i] let xDecl ← getLocalDecl x.fvarId! /- If there is named argument with name `xDecl.userName`, then we skip it. -/ match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with | some idx => remainingNamedArgs := remainingNamedArgs.eraseIdx idx | none => let mut foundIt := false let type := xDecl.type if type.consumeMData.isAppOf baseName then foundIt := true if !foundIt then /- Normalize type and try again -/ let type ← withReducible $ whnf type if type.consumeMData.isAppOf baseName then foundIt := true if foundIt then /- We found a type of the form (baseName ...). First, we check if the current argument is an explicit one, and the current explicit position "fits" at `args` (i.e., it must be ≤ arg.size) -/ if argIdx ≤ args.size && xDecl.binderInfo.isExplicit then /- We insert `e` as an explicit argument -/ return (args.insertAt argIdx (Arg.expr e), namedArgs) /- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible if there isn't an argument with the same name occurring before it. -/ for j in [:i] do let prev := xs[j] let prevDecl ← getLocalDecl prev.fvarId! if prevDecl.userName == xDecl.userName then throwError "invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\nbut it cannot be used" return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e }) if xDecl.binderInfo.isExplicit then -- advance explicit argument position argIdx := argIdx + 1 throwError "invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with an unique name" private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (f : Expr) (lvals : List LVal) : TermElabM Expr := let rec loop : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis | f, lval::lvals => do if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then addDotCompletionInfo targetStx f expectedType? fieldStx let (f, lvalRes) ← resolveLVal f lval match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f addTermInfo lval.getRef f loop f lvals | LValResolution.projFn baseStructName structName fieldName => let f ← mkBaseProjections baseStructName structName f if let some info := getFieldInfo? (← getEnv) baseStructName fieldName then if isPrivateNameFromImportedModule (← getEnv) info.projFn then throwError "field '{fieldName}' from structure '{structName}' is private" let projFn ← mkConst info.projFn addTermInfo lval.getRef projFn if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals else unreachable! | LValResolution.const baseStructName structName constName => let f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f let projFn ← mkConst constName addTermInfo lval.getRef projFn if lvals.isEmpty then let projFnType ← inferType projFn let (args, namedArgs) ← addLValArg baseStructName constName f args namedArgs projFnType elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.localRec baseName fullName fvar => addTermInfo lval.getRef fvar if lvals.isEmpty then let fvarType ← inferType fvar let (args, namedArgs) ← addLValArg baseName fullName f args namedArgs fvarType elabAppArgs fvar namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.getOp fullName idx => let getOpFn ← mkConst fullName addTermInfo lval.getRef getOpFn if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } let namedArgs ← addNamedArg namedArgs { name := `idx, val := Arg.stx idx } elabAppArgs getOpFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals loop f lvals private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do if !lvals.isEmpty && explicit then throwError "invalid use of field notation with `@` modifier" elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do lvls.foldrM (fun stx lvls => do pure ((← elabLevel stx)::lvls)) [] /- Interaction between `errToSorry` and `observing`. - The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true). - When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator. The `observing x` executes `x` and returns a `TermElabResult`. `observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution because it would not be clear to decide what the "main" error message for the alternative is. When the result contains a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`. Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols. Important: we rely on the property that after `errToSorry` is set to false, no elaboration function executed by `x` will reset it to `true`. -/ private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do let funLVals ← withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType? let overloaded := overloaded || funLVals.length > 1 -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do let lvals' := toLVals fields (first := true) let s ← observing do addTermInfo fIdent f expectedType? let e ← elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else pure e return acc.push s where toName : List Syntax → Name | [] => Name.anonymous | field :: fields => Name.mkStr (toName fields) field.getId.toString toLVals : List Syntax → (first : Bool) → List LVal | [], _ => [] | field::fields, true => LVal.fieldName field field.getId.toString (toName (field::fields)) fIdent :: toLVals fields false | field::fields, false => LVal.fieldName field field.getId.toString none fIdent :: toLVals fields false private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := if f.getKind == choiceKind then -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := false }) do f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc) acc else let elabFieldName (e field : Syntax) := do let newLVals := field.identComponents.map fun comp => -- We use `none` in `suffix?` since `field` can't be part of a composite name LVal.fieldName comp (toString comp.getId) none e elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc let elabFieldIdx (e idxStx : Syntax) := do let idx := idxStx.isFieldIdx?.get! elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc match f with | `($(e).$idx:fieldIdx) => elabFieldIdx e idx | `($e |>.$idx:fieldIdx) => elabFieldIdx e idx | `($(e).$field:ident) => elabFieldName e field | `($e |>.$field:ident) => elabFieldName e field | `($e[%$bracket $idx]) => elabAppFn e (LVal.getOp bracket idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident@$t:term) => throwError "unexpected occurrence of named pattern" | `($id:ident) => do elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident.{$us,*}) => do let us ← elabExplicitUnivs us elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `(@$id:ident) => elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$id:ident.{$us,*}) => elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | `(_) => throwError "placeholders '_' cannot be used where a function is expected" | _ => do let catchPostpone := !overloaded /- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms. Recall that `observing` does not catch `postponeExceptionId`. -/ if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then /- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/ let s ← if overloaded then observing <| elabTermEnsuringType f expectedType? catchPostpone else observing <| elabTerm f expectedType? return acc.push s else let s ← observing do let f ← elabTerm f none catchPostpone let e ← elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else pure e return acc.push s private def isSuccess (candidate : TermElabResult Expr) : Bool := match candidate with | EStateM.Result.ok _ _ => true | _ => false private def getSuccess (candidates : Array (TermElabResult Expr)) : Array (TermElabResult Expr) := candidates.filter isSuccess private def toMessageData (ex : Exception) : TermElabM MessageData := do let pos ← getRefPos match ex.getRef.getPos? with | none => return ex.toMessageData | some exPos => if pos == exPos then return ex.toMessageData else let exPosition := (← getFileMap).toPosition exPos return m!"{exPosition.line}:{exPosition.column} {ex.toMessageData}" private def toMessageList (msgs : Array MessageData) : MessageData := indentD (MessageData.joinSep msgs.toList m!"\n\n") private def mergeFailures {α} (failures : Array (TermElabResult Expr)) : TermElabM α := do let msgs ← failures.mapM fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error ex _ => toMessageData ex throwError "overloaded, errors {toMessageList msgs}" private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do let candidates ← elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[] if candidates.size == 1 then applyResult candidates[0] else let successes := getSuccess candidates if successes.size == 1 then applyResult successes[0] else if successes.size > 1 then let lctx ← getLCtx let opts ← getOptions let msgs : Array MessageData := successes.map fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.meta.core.env, mctx := s.meta.meta.mctx, lctx := lctx, opts := opts } e | _ => unreachable! throwErrorAt f "ambiguous, possible interpretations {toMessageList msgs}" else withRef f <| mergeFailures candidates @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => withoutPostponingUniverseConstraints do let (f, namedArgs, args, ellipsis) ← expandApp stx elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType? private def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx #[] #[] (ellipsis := false) expectedType? @[builtinTermElab ident] def elabIdent : TermElab := elabAtom @[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom @[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom @[builtinTermElab pipeProj] def elabPipeProj : TermElab | `($e |>.$f $args*), expectedType? => withoutPostponingUniverseConstraints do let (namedArgs, args, ellipsis) ← expandArgs args elabAppAux (← `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType? | _, _ => throwUnsupportedSyntax @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match stx with | `(@$id:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@$id:ident.{$us,*}) => elabAtom stx expectedType? | `(@($t)) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom builtin_initialize registerTraceClass `Elab.app end Lean.Elab.Term
e9cb7a8ed1ff03d2b0aded6ed26648137264d91b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/projective_space/basic.lean
78593079ab34d81fa6826a13271c1891dce3dd90
[ "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,164
lean
/- Copyright (c) 2022 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import linear_algebra.finite_dimensional /-! # Projective Spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definition of the projectivization of a vector space over a field, as well as the bijection between said projectivization and the collection of all one dimensional subspaces of the vector space. ## Notation `ℙ K V` is notation for `projectivization K V`, the projectivization of a `K`-vector space `V`. ## Constructing terms of `ℙ K V`. We have three ways to construct terms of `ℙ K V`: - `projectivization.mk K v hv` where `v : V` and `hv : v ≠ 0`. - `projectivization.mk' K v` where `v : { w : V // w ≠ 0 }`. - `projectivization.mk'' H h` where `H : submodule K V` and `h : finrank H = 1`. ## Other definitions - For `v : ℙ K V`, `v.submodule` gives the corresponding submodule of `V`. - `projectivization.equiv_submodule` is the equivalence between `ℙ K V` and `{ H : submodule K V // finrank H = 1 }`. - For `v : ℙ K V`, `v.rep : V` is a representative of `v`. -/ variables (K V : Type*) [division_ring K] [add_comm_group V] [module K V] /-- The setoid whose quotient is the projectivization of `V`. -/ def projectivization_setoid : setoid { v : V // v ≠ 0 } := (mul_action.orbit_rel Kˣ V).comap coe /-- The projectivization of the `K`-vector space `V`. The notation `ℙ K V` is preferred. -/ @[nolint has_nonempty_instance] def projectivization := quotient (projectivization_setoid K V) notation `ℙ` := projectivization namespace projectivization variables {V} /-- Construct an element of the projectivization from a nonzero vector. -/ def mk (v : V) (hv : v ≠ 0) : ℙ K V := quotient.mk' ⟨v,hv⟩ /-- A variant of `projectivization.mk` in terms of a subtype. `mk` is preferred. -/ def mk' (v : { v : V // v ≠ 0 }) : ℙ K V := quotient.mk' v @[simp] lemma mk'_eq_mk (v : { v : V // v ≠ 0}) : mk' K v = mk K v v.2 := by { dsimp [mk, mk'], congr' 1, simp } instance [nontrivial V] : nonempty (ℙ K V) := let ⟨v, hv⟩ := exists_ne (0 : V) in ⟨mk K v hv⟩ variable {K} /-- Choose a representative of `v : projectivization K V` in `V`. -/ protected noncomputable def rep (v : ℙ K V) : V := v.out' lemma rep_nonzero (v : ℙ K V) : v.rep ≠ 0 := v.out'.2 @[simp] lemma mk_rep (v : ℙ K V) : mk K v.rep v.rep_nonzero = v := by { dsimp [mk, projectivization.rep], simp } open finite_dimensional /-- Consider an element of the projectivization as a submodule of `V`. -/ protected def submodule (v : ℙ K V) : submodule K V := quotient.lift_on' v (λ v, K ∙ (v : V)) $ begin rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨x, (rfl : x • b = a)⟩, exact (submodule.span_singleton_group_smul_eq _ x _), end variable (K) lemma mk_eq_mk_iff (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) : mk K v hv = mk K w hw ↔ ∃ (a : Kˣ), a • w = v := quotient.eq' /-- Two nonzero vectors go to the same point in projective space if and only if one is a scalar multiple of the other. -/ lemma mk_eq_mk_iff' (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) : mk K v hv = mk K w hw ↔ ∃ (a : K), a • w = v := begin rw mk_eq_mk_iff K v w hv hw, split, { rintro ⟨a, ha⟩, exact ⟨a, ha⟩ }, { rintro ⟨a, ha⟩, refine ⟨units.mk0 a (λ c, hv.symm _), ha⟩, rwa [c, zero_smul] at ha } end lemma exists_smul_eq_mk_rep (v : V) (hv : v ≠ 0) : ∃ (a : Kˣ), a • v = (mk K v hv).rep := show (projectivization_setoid K V).rel _ _, from quotient.mk_out' ⟨v, hv⟩ variable {K} /-- An induction principle for `projectivization`. Use as `induction v using projectivization.ind`. -/ @[elab_as_eliminator] lemma ind {P : ℙ K V → Prop} (h : ∀ (v : V) (h : v ≠ 0), P (mk K v h)) : ∀ p, P p := quotient.ind' $ subtype.rec $ by exact h @[simp] lemma submodule_mk (v : V) (hv : v ≠ 0) : (mk K v hv).submodule = K ∙ v := rfl lemma submodule_eq (v : ℙ K V) : v.submodule = K ∙ v.rep := by { conv_lhs { rw ← v.mk_rep }, refl } lemma finrank_submodule (v : ℙ K V) : finrank K v.submodule = 1 := begin rw submodule_eq, exact finrank_span_singleton v.rep_nonzero, end instance (v : ℙ K V) : finite_dimensional K v.submodule := by { rw ← v.mk_rep, change finite_dimensional K (K ∙ v.rep), apply_instance } lemma submodule_injective : function.injective (projectivization.submodule : ℙ K V → submodule K V) := begin intros u v h, replace h := le_of_eq h, simp only [submodule_eq] at h, rw submodule.le_span_singleton_iff at h, rw [← mk_rep v, ← mk_rep u], apply quotient.sound', obtain ⟨a,ha⟩ := h u.rep (submodule.mem_span_singleton_self _), have : a ≠ 0 := λ c, u.rep_nonzero (by simpa [c] using ha.symm), use [units.mk0 a this, ha], end variables (K V) /-- The equivalence between the projectivization and the collection of subspaces of dimension 1. -/ noncomputable def equiv_submodule : ℙ K V ≃ { H : submodule K V // finrank K H = 1 } := equiv.of_bijective (λ v, ⟨v.submodule, v.finrank_submodule⟩) begin split, { intros u v h, apply_fun (λ e, e.val) at h, apply submodule_injective h }, { rintros ⟨H, h⟩, rw finrank_eq_one_iff' at h, obtain ⟨v, hv, h⟩ := h, have : (v : V) ≠ 0 := λ c, hv (subtype.coe_injective c), use mk K v this, symmetry, ext x, revert x, erw ← set.ext_iff, ext x, dsimp [-set_like.mem_coe], rw [submodule.span_singleton_eq_range], refine ⟨λ hh, _, _⟩, { obtain ⟨c,hc⟩ := h ⟨x,hh⟩, exact ⟨c, congr_arg coe hc⟩ }, { rintros ⟨c,rfl⟩, refine submodule.smul_mem _ _ v.2 } } end variables {K V} /-- Construct an element of the projectivization from a subspace of dimension 1. -/ noncomputable def mk'' (H : _root_.submodule K V) (h : finrank K H = 1) : ℙ K V := (equiv_submodule K V).symm ⟨H,h⟩ @[simp] lemma submodule_mk'' (H : _root_.submodule K V) (h : finrank K H = 1) : (mk'' H h).submodule = H := begin suffices : (equiv_submodule K V) (mk'' H h) = ⟨H,h⟩, by exact congr_arg coe this, dsimp [mk''], simp end @[simp] lemma mk''_submodule (v : ℙ K V) : mk'' v.submodule v.finrank_submodule = v := show (equiv_submodule K V).symm (equiv_submodule K V _) = _, by simp section map variables {L W : Type*} [division_ring L] [add_comm_group W] [module L W] /-- An injective semilinear map of vector spaces induces a map on projective spaces. -/ def map {σ : K →+* L} (f : V →ₛₗ[σ] W) (hf : function.injective f) : ℙ K V → ℙ L W := quotient.map' (λ v, ⟨f v, λ c, v.2 (hf (by simp [c]))⟩) begin rintros ⟨u,hu⟩ ⟨v,hv⟩ ⟨a,ha⟩, use units.map σ.to_monoid_hom a, dsimp at ⊢ ha, erw [← f.map_smulₛₗ, ha], end /-- Mapping with respect to a semilinear map over an isomorphism of fields yields an injective map on projective spaces. -/ lemma map_injective {σ : K →+* L} {τ : L →+* K} [ring_hom_inv_pair σ τ] (f : V →ₛₗ[σ] W) (hf : function.injective f) : function.injective (map f hf) := begin intros u v h, rw [← u.mk_rep, ← v.mk_rep] at *, apply quotient.sound', dsimp [map, mk] at h, simp only [quotient.eq'] at h, obtain ⟨a,ha⟩ := h, use units.map τ.to_monoid_hom a, dsimp at ⊢ ha, have : (a : L) = σ (τ a), by rw ring_hom_inv_pair.comp_apply_eq₂, change (a : L) • f v.rep = f u.rep at ha, rw [this, ← f.map_smulₛₗ] at ha, exact hf ha, end @[simp] lemma map_id : map (linear_map.id : V →ₗ[K] V) (linear_equiv.refl K V).injective = id := by { ext v, induction v using projectivization.ind, refl } @[simp] lemma map_comp {F U : Type*} [field F] [add_comm_group U] [module F U] {σ : K →+* L} {τ : L →+* F} {γ : K →+* F} [ring_hom_comp_triple σ τ γ] (f : V →ₛₗ[σ] W) (hf : function.injective f) (g : W →ₛₗ[τ] U) (hg : function.injective g) : map (g.comp f) (hg.comp hf) = map g hg ∘ map f hf := by { ext v, induction v using projectivization.ind, refl } end map end projectivization
8b7c1b9f199e893bc2b2546398815fe9d75b0c2a
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/groupoid.lean
ef96cfba620bd4eacb370bc8c616354474528f61
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
1,573
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import category_theory.category import category_theory.isomorphism import data.equiv.basic namespace category_theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation section prio set_option default_priority 100 -- see Note [default priority] /-- A `groupoid` is a category such that all morphisms are isomorphisms. -/ class groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) := (inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X)) (inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously) (comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously) end prio restate_axiom groupoid.inv_comp' restate_axiom groupoid.comp_inv' attribute [simp] groupoid.inv_comp groupoid.comp_inv abbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C section variables {C : Type u} [𝒞 : groupoid.{v} C] {X Y : C} include 𝒞 @[priority 100] -- see Note [lower instance priority] instance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f := { inv := groupoid.inv f } variables (X Y) /-- In a groupoid, isomorphisms are equivalent to morphisms. -/ def groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) := { to_fun := iso.hom, inv_fun := λ f, as_iso f, left_inv := λ i, iso.ext rfl, right_inv := λ f, rfl } end end category_theory
1d555ab0b70a0beeba080c60cd116c5bc2e0d7cc
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/sec_param_pp2.lean
770b29f4d9459291704ed3025cd0cbfab7b24d35
[ "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
234
lean
section parameters {A : Type} (a : A) section parameters {B : Type} (b : B) variable f : A → B → A definition id2 := f a b #check id2 set_option pp.universes true #check id2 end #check id2 end #check id2
70928715ed1667410f7cf3c054071b0161c179f9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/widget/widget5.lean
b89c06dd821ddf3e07b0dd26dbbd2c2ef5116550
[ "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
99
lean
open tactic widget #html (component.pure $ λ _, [h "p" [attr.style [("color", "blue")]] ["hi"]])
2f43701c23c6f01eb5b9b54bc7c2959890c1d6b5
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/homology/exact.lean
086f111614d16a078455a57155f0e88de83991a3
[ "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
9,617
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.homology.image_to_kernel /-! # Exact sequences In a category with zero morphisms, images, and equalizers we say that `f : A ⟶ B` and `g : B ⟶ C` are exact if `f ≫ g = 0` and the natural map `image f ⟶ kernel g` is an epimorphism. In any preadditive category this is equivalent to the homology at `B` vanishing. However in general it is weaker than other reasonable definitions of exactness, particularly that 1. the inclusion map `image.ι f` is a kernel of `g` or 2. `image f ⟶ kernel g` is an isomorphism or 3. `image_subobject f = kernel_subobject f`. However when the category is abelian, these all become equivalent; these results are found in `category_theory/abelian/exact.lean`. # Main results * Suppose that cokernels exist and that `f` and `g` are exact. If `s` is any kernel fork over `g` and `t` is any cokernel cofork over `f`, then `fork.ι s ≫ cofork.π t = 0`. * Precomposing the first morphism with an epimorphism retains exactness. Postcomposing the second morphism with a monomorphism retains exactness. * If `f` and `g` are exact and `i` is an isomorphism, then `f ≫ i.hom` and `i.inv ≫ g` are also exact. # Future work * Short exact sequences, split exact sequences, the splitting lemma (maybe only for abelian categories?) * Two adjacent maps in a chain complex are exact iff the homology vanishes -/ universes v u open category_theory open category_theory.limits variables {V : Type u} [category.{v} V] variables [has_images V] namespace category_theory /-- Two morphisms `f : A ⟶ B`, `g : B ⟶ C` are called exact if `w : f ≫ g = 0` and the natural map `image_to_kernel f g w : image_subobject f ⟶ kernel_subobject g` is an epimorphism. In any preadditive category, this is equivalent to `w : f ≫ g = 0` and `homology f g w ≅ 0`. In an abelian category, this is equivalent to `image_to_kernel f g w` being an isomorphism, and hence equivalent to the usual definition, `image_subobject f = kernel_subobject g`. -/ -- One nice feature of this definition is that we have -- `epi f → exact g h → exact (f ≫ g) h` and `exact f g → mono h → exact f (g ≫ h)`, -- which do not necessarily hold in a non-abelian category with the usual definition of `exact`. class exact [has_zero_morphisms V] [has_kernels V] {A B C : V} (f : A ⟶ B) (g : B ⟶ C) : Prop := (w : f ≫ g = 0) (epi : epi (image_to_kernel f g w)) attribute [instance] exact.epi attribute [simp, reassoc] exact.w section variables [has_zero_object V] [preadditive V] [has_kernels V] [has_cokernels V] open_locale zero_object /-- In any preadditive category, composable morphisms `f g` are exact iff they compose to zero and the homology vanishes. -/ lemma preadditive.exact_iff_homology_zero {A B C : V} (f : A ⟶ B) (g : B ⟶ C) : exact f g ↔ ∃ w : f ≫ g = 0, nonempty (homology f g w ≅ 0) := ⟨λ h, ⟨h.w, ⟨cokernel.of_epi _⟩⟩, λ h, begin obtain ⟨w, ⟨i⟩⟩ := h, exact ⟨w, preadditive.epi_of_cokernel_zero ((cancel_mono i.hom).mp (by ext))⟩, end⟩ end section variables [has_zero_morphisms V] [has_kernels V] lemma comp_eq_zero_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (p : image_subobject f = kernel_subobject g) : f ≫ g = 0 := begin rw [←image_subobject_arrow_comp f, category.assoc], convert comp_zero, rw p, simp, end lemma image_to_kernel_is_iso_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (p : image_subobject f = kernel_subobject g) : is_iso (image_to_kernel f g (comp_eq_zero_of_image_eq_kernel f g p)) := begin refine ⟨⟨subobject.of_le _ _ p.ge, _⟩⟩, dsimp [image_to_kernel], simp only [subobject.of_le_comp_of_le, subobject.of_le_refl], simp, end -- We'll prove the converse later, when `V` is abelian. lemma exact_of_image_eq_kernel {A B C : V} (f : A ⟶ B) (g : B ⟶ C) (p : image_subobject f = kernel_subobject g) : exact f g := { w := comp_eq_zero_of_image_eq_kernel f g p, epi := begin haveI := image_to_kernel_is_iso_of_image_eq_kernel f g p, apply_instance, end } end variables {A B C D : V} {f : A ⟶ B} {g : B ⟶ C} {h : C ⟶ D} local attribute [instance] epi_comp section variables [has_zero_morphisms V] [has_equalizers V] instance exact_comp_hom_inv_comp [exact f g] (i : B ≅ D) : exact (f ≫ i.hom) (i.inv ≫ g) := begin refine ⟨by simp, _⟩, rw image_to_kernel_comp_hom_inv_comp, apply_instance, end instance exact_comp_inv_hom_comp [exact f g] (i : D ≅ B) : exact (f ≫ i.inv) (i.hom ≫ g) := category_theory.exact_comp_hom_inv_comp i.symm lemma exact_comp_hom_inv_comp_iff (i : B ≅ D) : exact (f ≫ i.hom) (i.inv ≫ g) ↔ exact f g := begin refine ⟨_, by { introI, apply_instance }⟩, introI, have : exact ((f ≫ i.hom) ≫ i.inv) (i.hom ≫ i.inv ≫ g) := infer_instance, simpa using this end lemma exact_epi_comp [exact g h] [epi f] : exact (f ≫ g) h := begin refine ⟨by simp, _⟩, rw image_to_kernel_comp_left, apply_instance, end @[simp] lemma exact_iso_comp [is_iso f] : exact (f ≫ g) h ↔ exact g h := ⟨λ w, by { rw ←is_iso.inv_hom_id_assoc f g, exactI exact_epi_comp, }, λ w, by exactI exact_epi_comp⟩ lemma exact_comp_mono [exact f g] [mono h] : exact f (g ≫ h) := begin refine ⟨by simp, _⟩, rw image_to_kernel_comp_right f g h exact.w, apply_instance, end @[simp] lemma exact_comp_iso [is_iso h] : exact f (g ≫ h) ↔ exact f g := ⟨λ w, begin rw [←category.comp_id g, ←is_iso.hom_inv_id h, ←category.assoc], exactI exact_comp_mono, end, λ w, by exactI exact_comp_mono⟩ lemma exact_kernel_subobject_arrow : exact (kernel_subobject f).arrow f := begin refine ⟨by simp, _⟩, apply @is_iso.epi_of_iso _ _ _ _ _ _, exact ⟨⟨factor_thru_image_subobject _, by { ext, simp, }, by { ext, simp, }⟩⟩, end lemma exact_kernel_ι : exact (kernel.ι f) f := by { rw [←kernel_subobject_arrow', exact_iso_comp], exact exact_kernel_subobject_arrow } instance [exact f g] : epi (factor_thru_kernel_subobject g f (by simp)) := begin rw ←factor_thru_image_subobject_comp_image_to_kernel, apply epi_comp, end instance [exact f g] : epi (kernel.lift g f (by simp)) := begin rw ←factor_thru_kernel_subobject_comp_kernel_subobject_iso, apply epi_comp end variables (A) lemma kernel_subobject_arrow_eq_zero_of_exact_zero_left [exact (0 : A ⟶ B) g] : (kernel_subobject g).arrow = 0 := begin rw [←cancel_epi (image_to_kernel (0 : A ⟶ B) g exact.w), ←cancel_epi (factor_thru_image_subobject (0 : A ⟶ B))], simp end lemma kernel_ι_eq_zero_of_exact_zero_left [exact (0 : A ⟶ B) g] : kernel.ι g = 0 := by { rw ←kernel_subobject_arrow', simp [kernel_subobject_arrow_eq_zero_of_exact_zero_left A], } lemma exact_zero_left_of_mono [has_zero_object V] [mono g] : exact (0 : A ⟶ B) g := ⟨by simp, image_to_kernel_epi_of_zero_of_mono _⟩ end section has_cokernels variables [has_zero_morphisms V] [has_equalizers V] [has_cokernels V] (f g) @[simp, reassoc] lemma kernel_comp_cokernel [exact f g] : kernel.ι g ≫ cokernel.π f = 0 := begin rw [←kernel_subobject_arrow', category.assoc], convert comp_zero, apply zero_of_epi_comp (image_to_kernel f g exact.w) _, rw [image_to_kernel_arrow_assoc, ←image_subobject_arrow, category.assoc, ←iso.eq_inv_comp], ext, simp, end lemma comp_eq_zero_of_exact [exact f g] {X Y : V} {ι : X ⟶ B} (hι : ι ≫ g = 0) {π : B ⟶ Y} (hπ : f ≫ π = 0) : ι ≫ π = 0 := by rw [←kernel.lift_ι _ _ hι, ←cokernel.π_desc _ _ hπ, category.assoc, kernel_comp_cokernel_assoc, zero_comp, comp_zero] @[simp, reassoc] lemma fork_ι_comp_cofork_π [exact f g] (s : kernel_fork g) (t : cokernel_cofork f) : fork.ι s ≫ cofork.π t = 0 := comp_eq_zero_of_exact f g (kernel_fork.condition s) (cokernel_cofork.condition t) end has_cokernels section variables [has_zero_object V] open_locale zero_object section variables [has_zero_morphisms V] [has_kernels V] instance exact_of_zero {A C : V} (f : A ⟶ 0) (g : 0 ⟶ C) : exact f g := begin obtain rfl : f = 0 := by ext, obtain rfl : g = 0 := by ext, fsplit, { simp, }, { exact image_to_kernel_epi_of_zero_of_mono 0, }, end instance exact_zero_mono {B C : V} (f : B ⟶ C) [mono f] : exact (0 : (0 ⟶ B)) f := ⟨by simp, infer_instance⟩ instance exact_epi_zero {A B : V} (f : A ⟶ B) [epi f] : exact f (0 : (B ⟶ 0)) := ⟨by simp, infer_instance⟩ end section variables [preadditive V] lemma mono_iff_exact_zero_left [has_kernels V]{B C : V} (f : B ⟶ C) : mono f ↔ exact (0 : (0 ⟶ B)) f := ⟨λ h, by { resetI, apply_instance, }, λ h, preadditive.mono_of_kernel_iso_zero ((kernel_subobject_iso f).symm ≪≫ iso_zero_of_epi_zero (by simpa using h.epi))⟩ lemma epi_iff_exact_zero_right [has_equalizers V] {A B : V} (f : A ⟶ B) : epi f ↔ exact f (0 : (B ⟶ 0)) := ⟨λ h, by { resetI, apply_instance, }, λ h, begin have e₁ := h.epi, rw image_to_kernel_zero_right at e₁, have e₂ : epi (((image_subobject f).arrow ≫ inv (kernel_subobject 0).arrow) ≫ (kernel_subobject 0).arrow) := @epi_comp _ _ _ _ _ _ e₁ _ _, rw [category.assoc, is_iso.inv_hom_id, category.comp_id] at e₂, rw [←image_subobject_arrow] at e₂, resetI, haveI : epi (image.ι f) := epi_of_epi (image_subobject_iso f).hom (image.ι f), apply epi_of_epi_image, end⟩ end end end category_theory
48bf3d3a4657e6f8d975f7f97f3664b189c4f2d2
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/data/int/basic.lean
2b2bd2ca4acd78c8bdcb7804e5528776f5c2f1b5
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
43,279
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic algebra.char_zero algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨0⟩ meta instance : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-("++↑k++"+1)")⟩ attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] @[simp] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_le_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i, p i → p (i + 1)) (hn : ∀i, p i → p (i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { have := hn _ n_ih, simpa } }, exact this (i + 1) } end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : b > 0) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) : a / b ≥ 0 := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : a ≥ 0) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : b > 0) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end @[simp] protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, c > 0 → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : b > 0) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) @[simp] theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ @[simp] theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ @[simp] theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → a % b ≥ 0 | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] @[simp] theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] lemma mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b > 0) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : a > 0) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : b > 0) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : a ≥ 0) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] /- dvd -/ theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem dvd_antisymm {a b : ℤ} (H1 : a ≥ 0) (H2 : b ≥ 0) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : b > 0) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ 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 (by rw [mul_comm, H']) /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : c > 0) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : c > 0) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : c > 0) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : c > 0) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : c > 0) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : c > 0) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : c > 0) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : c > 0) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : c > 0) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : b ≥ 0) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : c > 0) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : a > 0) (H2 : b ≥ 0) (H3 : b ∣ a) : a / b > 0 := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H1 : b ∣ a) (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : m ≥ n.succ) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have, { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : nat) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp [(*), int.mul, nat_abs_neg_of_nat] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq] /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le (a : ℤ) (n : ℕ) : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros i m; simp [bodd]; cases i.bodd; cases m.bodd; refl @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; unfold has_neg.neg; simp [int.coe_nat_eq, int.neg, bodd] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, bodd]; cases m.bodd; cases n.bodd; refl @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, bodd]; cases m.bodd; cases n.bodd; refl theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) @[priority 0] instance cast_coe : has_coe ℤ α := ⟨int.cast⟩ @[simp] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl @[simp] theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl @[simp] theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ nat.cast_coe)) n : α) = n := by simp @[simp] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), by rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add]; apply congr_arg (λ x:ℕ, -(x:α)); simp @[simp] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 @[simp] theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] theorem eq_cast [add_group α] [has_one α] (f : ℤ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (n : ℤ) : f n = n := begin have H : ∀ (n : ℕ), f n = n := nat.eq_cast' (λ n, f n) H1 (λ x y, Hadd x y), cases n, {apply H}, apply eq_neg_of_add_eq_zero, rw [← nat.cast_zero, ← H 0, int.coe_nat_zero, ← show -[1+ n] + (↑n + 1) = 0, from neg_add_self (↑n+1), Hadd, show f (n+1) = n+1, from H (n+1)] end @[simp] theorem cast_id (n : ℤ) : ↑n = n := (eq_cast id rfl (λ _ _, rfl) n).symm @[simp] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast end int
7ca935bc2134d2cd0bd27633dc47510f8d701ec5
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/order/ring.lean
cb5de550c1e54a068ca0e95d9e980c16be56ab77
[ "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
68,748
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.invertible import algebra.order.group import algebra.order.sub import data.set.intervals.basic /-! # Ordered rings and semirings This file develops the basics of ordered (semi)rings. Each typeclass here comprises * an algebraic class (`semiring`, `comm_semiring`, `ring`, `comm_ring`) * an order class (`partial_order`, `linear_order`) * assumptions on how both interact ((strict) monotonicity, canonicity) For short, * "`+` respects `≤`" means "monotonicity of addition" * "`*` respects `<`" means "strict monotonicity of multiplication by a positive number". ## Typeclasses * `ordered_semiring`: Semiring with a partial order such that `+` respects `≤` and `*` respects `<`. * `ordered_comm_semiring`: Commutative semiring with a partial order such that `+` respects `≤` and `*` respects `<`. * `ordered_ring`: Ring with a partial order such that `+` respects `≤` and `*` respects `<`. * `ordered_comm_ring`: Commutative ring with a partial order such that `+` respects `≤` and `*` respects `<`. * `linear_ordered_semiring`: Semiring with a linear order such that `+` respects `≤` and `*` respects `<`. * `linear_ordered_ring`: Ring with a linear order such that `+` respects `≤` and `*` respects `<`. * `linear_ordered_comm_ring`: Commutative ring with a linear order such that `+` respects `≤` and `*` respects `<`. * `canonically_ordered_comm_semiring`: Commutative semiring with a partial order such that `+` respects `≤`, `*` respects `<`, and `a ≤ b ↔ ∃ c, b = a + c`. and some typeclasses to define ordered rings by specifying their nonegative elements: * `nonneg_ring`: To define `ordered_ring`s. * `linear_nonneg_ring`: To define `linear_ordered_ring`s. ## Hierarchy The hardest part of proving order lemmas might be to figure out the correct generality and its corresponding typeclass. Here's an attempt at demystifying it. For each typeclass, we list its immediate predecessors and what conditions are added to each of them. * `ordered_semiring` - `ordered_cancel_add_comm_monoid` & multiplication & `*` respects `<` - `semiring` & partial order structure & `+` respects `≤` & `*` respects `<` * `ordered_comm_semiring` - `ordered_semiring` & commutativity of multiplication - `comm_semiring` & partial order structure & `+` respects `≤` & `*` respects `<` * `ordered_ring` - `ordered_semiring` & additive inverses - `ordered_add_comm_group` & multiplication & `*` respects `<` - `ring` & partial order structure & `+` respects `≤` & `*` respects `<` * `ordered_comm_ring` - `ordered_ring` & commutativity of multiplication - `ordered_comm_semiring` & additive inverses - `comm_ring` & partial order structure & `+` respects `≤` & `*` respects `<` * `linear_ordered_semiring` - `ordered_semiring` & totality of the order & nontriviality - `linear_ordered_add_comm_monoid` & multiplication & nontriviality & `*` respects `<` * `linear_ordered_ring` - `ordered_ring` & totality of the order & nontriviality - `linear_ordered_semiring` & additive inverses - `linear_ordered_add_comm_group` & multiplication & `*` respects `<` - `domain` & linear order structure * `linear_ordered_comm_ring` - `ordered_comm_ring` & totality of the order & nontriviality - `linear_ordered_ring` & commutativity of multiplication - `integral_domain` & linear order structure * `canonically_ordered_comm_semiring` - `canonically_ordered_add_monoid` & multiplication & `*` respects `<` & no zero divisors - `comm_semiring` & `a ≤ b ↔ ∃ c, b = a + c` & no zero divisors ## TODO We're still missing some typeclasses, like * `linear_ordered_comm_semiring` * `canonically_ordered_semiring` They have yet to come up in practice. -/ set_option old_structure_cmd true universe u variable {α : Type u} lemma add_one_le_two_mul [preorder α] [semiring α] [covariant_class α α (+) (≤)] {a : α} (a1 : 1 ≤ a) : a + 1 ≤ 2 * a := calc a + 1 ≤ a + a : add_le_add_left a1 a ... = 2 * a : (two_mul _).symm /-- An `ordered_semiring α` is a semiring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (zero_le_one : 0 ≤ (1 : α)) (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} @[simp] lemma zero_le_one : 0 ≤ (1:α) := ordered_semiring.zero_le_one lemma zero_le_two : 0 ≤ (2:α) := add_nonneg zero_le_one zero_le_one lemma one_le_two : 1 ≤ (2:α) := calc (1:α) = 0 + 1 : (zero_add _).symm ... ≤ 1 + 1 : add_le_add_right zero_le_one _ section nontrivial variables [nontrivial α] @[simp] lemma zero_lt_one : 0 < (1 : α) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two end nontrivial lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin by_cases ba : b ≤ a, { simp [ba.antisymm h₁] }, by_cases c0 : c ≤ 0, { simp [c0.antisymm h₂] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le ba) (h₂.lt_of_not_le c0)).le, end lemma mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonneg_right -- TODO: there are four variations, depending on which variables we assume to be nonneg -- See Note [decidable namespace] protected lemma decidable.mul_le_mul [@decidable_rel α (≤)] (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_le_mul : a ≤ c → b ≤ d → 0 ≤ b → 0 ≤ c → a * b ≤ c * d := by classical; exact decidable.mul_le_mul -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] [@decidable_rel α (≤)] {a b c : α} (h₁ : 0 ≤ c) (h₂ : a ≤ c) (h₃ : 0 ≤ b) (h₄ : b ≤ 1) : a * b ≤ c := by simpa only [mul_one] using decidable.mul_le_mul h₂ h₄ h₃ h₁ lemma mul_nonneg_le_one_le {α : Type*} [ordered_semiring α] {a b c : α} : 0 ≤ c → a ≤ c → 0 ≤ b → b ≤ 1 → a * b ≤ c := by classical; exact decidable.mul_nonneg_le_one_le -- See Note [decidable namespace] protected lemma decidable.mul_nonneg [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonneg_of_nonpos [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from decidable.mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonneg_of_nonpos : 0 ≤ a → b ≤ 0 → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonneg_of_nonpos -- See Note [decidable namespace] protected lemma decidable.mul_nonpos_of_nonpos_of_nonneg [@decidable_rel α (≤)] (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from decidable.mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_nonpos_of_nonpos_of_nonneg : a ≤ 0 → 0 ≤ b → a * b ≤ 0 := by classical; exact decidable.mul_nonpos_of_nonpos_of_nonneg -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul [@decidable_rel α (≤)] (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : decidable.mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul : a < c → b ≤ d → 0 < b → 0 ≤ c → a * b < c * d := by classical; exact decidable.mul_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul' [@decidable_rel α (≤)] (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : decidable.mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_lt_mul' : a ≤ c → b < d → 0 ≤ b → 0 < c → a * b < c * d := by classical; exact decidable.mul_lt_mul' lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h -- See Note [decidable namespace] protected lemma decidable.mul_self_lt_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := decidable.mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 -- See Note [decidable namespace] protected lemma decidable.strict_mono_on_mul_self [@decidable_rel α (≤)] : strict_mono_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, decidable.mul_self_lt_mul_self hx hxy lemma strict_mono_on_mul_self : strict_mono_on (λ x : α, x * x) (set.Ici 0) := λ x hx y hy hxy, mul_self_lt_mul_self hx hxy -- See Note [decidable namespace] protected lemma decidable.mul_self_le_mul_self [@decidable_rel α (≤)] (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := decidable.mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 -- See Note [decidable namespace] protected lemma decidable.mul_lt_mul'' [@decidable_rel α (≤)] (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := h4.lt_or_eq_dec.elim (λ b0, decidable.mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma mul_lt_mul'' : a < c → b < d → 0 ≤ a → 0 ≤ b → a * b < c * d := by classical; exact decidable.mul_lt_mul'' -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_right [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, decidable.mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_right : 0 ≤ b → 1 ≤ a → b ≤ b * a := by classical; exact decidable.le_mul_of_one_le_right -- See Note [decidable namespace] protected lemma decidable.le_mul_of_one_le_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, decidable.mul_le_mul_of_nonneg_right h hb lemma le_mul_of_one_le_left : 0 ≤ b → 1 ≤ a → b ≤ a * b := by classical; exact decidable.le_mul_of_one_le_left -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_right [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, decidable.mul_lt_mul' (le_refl _) h zero_le_one hb lemma lt_mul_of_one_lt_right : 0 < b → 1 < a → b < b * a := by classical; exact decidable.lt_mul_of_one_lt_right -- See Note [decidable namespace] protected lemma decidable.lt_mul_of_one_lt_left [@decidable_rel α (≤)] (hb : 0 < b) (h : 1 < a) : b < a * b := suffices 1 * b < a * b, by rwa one_mul at this, decidable.mul_lt_mul h (le_refl _) hb (zero_le_one.trans h.le) lemma lt_mul_of_one_lt_left : 0 < b → 1 < a → b < a * b := by classical; exact decidable.lt_mul_of_one_lt_left -- See Note [decidable namespace] protected lemma decidable.add_le_mul_two_add [@decidable_rel α (≤)] {a b : α} (a2 : 2 ≤ a) (b0 : 0 ≤ b) : a + (2 + b) ≤ a * (2 + b) := calc a + (2 + b) ≤ a + (a + a * b) : add_le_add_left (add_le_add a2 (decidable.le_mul_of_one_le_left b0 (one_le_two.trans a2))) a ... ≤ a * (2 + b) : by rw [mul_add, mul_two, add_assoc] lemma add_le_mul_two_add {a b : α} : 2 ≤ a → 0 ≤ b → a + (2 + b) ≤ a * (2 + b) := by classical; exact decidable.add_le_mul_two_add -- See Note [decidable namespace] protected lemma decidable.one_le_mul_of_one_le_of_one_le [@decidable_rel α (≤)] {a b : α} (a1 : 1 ≤ a) (b1 : 1 ≤ b) : (1 : α) ≤ a * b := (mul_one (1 : α)).symm.le.trans (decidable.mul_le_mul a1 b1 zero_le_one (zero_le_one.trans a1)) lemma one_le_mul_of_one_le_of_one_le {a b : α} : 1 ≤ a → 1 ≤ b → (1 : α) ≤ a * b := by classical; exact decidable.one_le_mul_of_one_le_of_one_le /-- Pullback an `ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_semiring β := { zero_le_one := show f 0 ≤ f 1, by simp only [zero, one, zero_le_one], mul_lt_mul_of_pos_left := λ a b c ab c0, show f (c * a) < f (c * b), begin rw [mul, mul], refine mul_lt_mul_of_pos_left ab _, rwa ← zero, end, mul_lt_mul_of_pos_right := λ a b c ab c0, show f (a * c) < f (b * c), begin rw [mul, mul], refine mul_lt_mul_of_pos_right ab _, rwa ← zero, end, ..hf.ordered_cancel_add_comm_monoid f zero add, ..hf.semiring f zero one add mul } section variable [nontrivial α] lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end -- See Note [decidable namespace] protected lemma decidable.one_lt_mul [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : α)) ▸ decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul -- See Note [decidable namespace] protected lemma decidable.mul_le_one [@decidable_rel α (≤)] (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply decidable.mul_le_mul; {assumption <|> apply zero_le_one} end lemma mul_le_one : a ≤ 1 → 0 ≤ b → b ≤ 1 → a * b ≤ 1 := by classical; exact decidable.mul_le_one -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_le_of_lt [@decidable_rel α (≤)] (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_le_of_lt : 1 ≤ a → 1 < b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_le_of_lt -- See Note [decidable namespace] protected lemma decidable.one_lt_mul_of_lt_of_le [@decidable_rel α (≤)] (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : decidable.mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma one_lt_mul_of_lt_of_le : 1 < a → 1 ≤ b → 1 < a * b := by classical; exact decidable.one_lt_mul_of_lt_of_le -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_right [@decidable_rel α (≤)] (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : decidable.mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_right : 0 ≤ a → b ≤ 1 → a * b ≤ a := by classical; exact decidable.mul_le_of_le_one_right -- See Note [decidable namespace] protected lemma decidable.mul_le_of_le_one_left [@decidable_rel α (≤)] (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : decidable.mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_le_of_le_one_left : 0 ≤ b → a ≤ 1 → a * b ≤ b := by classical; exact decidable.mul_le_of_le_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_left [@decidable_rel α (≤)] (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : decidable.mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_left : 0 ≤ a → a < 1 → b ≤ 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_left -- See Note [decidable namespace] protected lemma decidable.mul_lt_one_of_nonneg_of_lt_one_right [@decidable_rel α (≤)] (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : decidable.mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_lt_one_of_nonneg_of_lt_one_right : a ≤ 1 → 0 ≤ b → b < 1 → a * b < 1 := by classical; exact decidable.mul_lt_one_of_nonneg_of_lt_one_right end ordered_semiring section ordered_comm_semiring /-- An `ordered_comm_semiring α` is a commutative semiring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_comm_semiring (α : Type u) extends ordered_semiring α, comm_semiring α /-- Pullback an `ordered_comm_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_semiring [ordered_comm_semiring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_comm_semiring β := { ..hf.comm_semiring f zero one add mul, ..hf.ordered_semiring f zero one add mul } end ordered_comm_semiring /-- A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_ordered_add_comm_monoid α, nontrivial α section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from decidable.mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from decidable.mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin haveI := @linear_order.decidable_le α _, rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonneg_of_nonpos ha.le hb }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, lt_imp_lt_of_le_imp_le (λ hb, _) hab⟩, exact decidable.mul_nonpos_of_nonpos_of_nonneg ha.le hb } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) : (0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) := begin haveI := @linear_order.decidable_le α _, refine decidable.or_iff_not_and_not.2 _, simp only [not_and, not_le], intros ab nab, apply not_lt_of_le hab _, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (ab ha.le), ((ab le_rfl).asymm (nab le_rfl)).elim, mul_neg_of_neg_of_pos ha (nab ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1 @[simp] lemma inv_of_pos [invertible a] : 0 < ⅟a ↔ 0 < a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, pos_of_mul_pos_right this h.le, λ h, pos_of_mul_pos_left this h.le⟩ end @[simp] lemma inv_of_nonpos [invertible a] : ⅟a ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_of_pos] lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) @[simp] lemma inv_of_nonneg [invertible a] : 0 ≤ ⅟a ↔ 0 ≤ a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, (pos_of_mul_pos_right this h).le, λ h, (pos_of_mul_pos_left this h).le⟩ end @[simp] lemma inv_of_lt_zero [invertible a] : ⅟a < 0 ↔ a < 0 := by simp only [← not_le, inv_of_nonneg] @[simp] lemma inv_of_le_one [invertible a] (h : 1 ≤ a) : ⅟a ≤ 1 := by haveI := @linear_order.decidable_le α _; exact mul_inv_of_self a ▸ decidable.le_mul_of_one_le_left (inv_of_nonneg.2 $ zero_le_one.trans h) h lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h2 : b ≥ 0, (decidable.mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (assume h2 : a ≥ 0, (decidable.mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_left h' h, λ h', decidable.mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h', le_of_mul_le_mul_right h' h, λ h', decidable.mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_left h' h.le, λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := by haveI := @linear_order.decidable_le α _; exact ⟨lt_imp_lt_of_le_imp_le $ λ h', decidable.mul_le_mul_of_nonneg_right h' h.le, λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } lemma add_le_mul_of_left_le_right (a2 : 2 ≤ a) (ab : a ≤ b) : a + b ≤ a * b := have 0 < b, from calc 0 < 2 : zero_lt_two ... ≤ a : a2 ... ≤ b : ab, calc a + b ≤ b + b : add_le_add_right ab b ... = 2 * b : (two_mul b).symm ... ≤ a * b : (mul_le_mul_right this).mpr a2 lemma add_le_mul_of_right_le_left (b2 : 2 ≤ b) (ba : b ≤ a) : a + b ≤ a * b := have 0 < a, from calc 0 < 2 : zero_lt_two ... ≤ b : b2 ... ≤ a : ba, calc a + b ≤ a + a : add_le_add_left ba a ... = a * 2 : (mul_two a).symm ... ≤ a * b : (mul_le_mul_left this).mpr b2 lemma add_le_mul (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ a * b := if hab : a ≤ b then add_le_mul_of_left_le_right a2 hab else add_le_mul_of_right_le_left b2 (le_of_not_le hab) lemma add_le_mul' (a2 : 2 ≤ a) (b2 : 2 ≤ b) : a + b ≤ b * a := (le_of_eq (add_comm _ _)).trans (add_le_mul b2 a2) section variables [nontrivial α] @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb theorem mul_nonneg_iff_right_nonneg_of_pos (ha : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := by haveI := @linear_order.decidable_le α _; exact ⟨λ h, nonneg_of_mul_nonneg_right h ha, λ h, decidable.mul_nonneg h ha.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ /-- Pullback a `linear_ordered_semiring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_semiring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_semiring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_semiring f zero one add mul } end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := by haveI := @linear_order.decidable_le α _; exact assume b c b_le_c, decidable.mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := by haveI := @linear_order.decidable_le α _; exact λ x y h, decidable.mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (zero_le_one : 0 ≤ (1 : α)) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_nonneg [@decidable_rel α (≤)] {a b : α} (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin by_cases ha : a ≤ 0, { simp [le_antisymm ha h₁] }, by_cases hb : b ≤ 0, { simp [le_antisymm hb h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le ha) (h₂.lt_of_not_le hb))).1, end lemma ordered_ring.mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by classical; exact decidable.ordered_ring.mul_nonneg -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_left [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin rw [← sub_nonneg, ← mul_sub], exact decidable.ordered_ring.mul_nonneg h₂ (sub_nonneg.2 h₁), end lemma ordered_ring.mul_le_mul_of_nonneg_left : a ≤ b → 0 ≤ c → c * a ≤ c * b := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_left -- See Note [decidable namespace] protected lemma decidable.ordered_ring.mul_le_mul_of_nonneg_right [@decidable_rel α (≤)] (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin rw [← sub_nonneg, ← sub_mul], exact decidable.ordered_ring.mul_nonneg (sub_nonneg.2 h₁) h₂, end lemma ordered_ring.mul_le_mul_of_nonneg_right : a ≤ b → 0 ≤ c → a * c ≤ b * c := by classical; exact decidable.ordered_ring.mul_le_mul_of_nonneg_right lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := begin rw [← sub_pos, ← mul_sub], exact ordered_ring.mul_pos _ _ h₂ (sub_pos.2 h₁), end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := begin rw [← sub_pos, ← sub_mul], exact ordered_ring.mul_pos _ _ (sub_pos.2 h₁) h₂, end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_left [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from decidable.mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_left {a b c : α} : b ≤ a → c ≤ 0 → c * a ≤ c * b := by classical; exact decidable.mul_le_mul_of_nonpos_left -- See Note [decidable namespace] protected lemma decidable.mul_le_mul_of_nonpos_right [@decidable_rel α (≤)] {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from decidable.mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} : b ≤ a → c ≤ 0 → a * c ≤ b * c := by classical; exact decidable.mul_le_mul_of_nonpos_right -- See Note [decidable namespace] protected lemma decidable.mul_nonneg_of_nonpos_of_nonpos [@decidable_rel α (≤)] {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from decidable.mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} : a ≤ 0 → b ≤ 0 → 0 ≤ a * b := by classical; exact decidable.mul_nonneg_of_nonpos_of_nonpos lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this /-- Pullback an `ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) : ordered_ring β := { mul_pos := λ a b a0 b0, show f 0 < f (a * b), by { rw [zero, mul], apply mul_pos; rwa ← zero }, ..hf.ordered_semiring f zero one add mul, ..hf.ring f zero one add mul neg sub } end ordered_ring section ordered_comm_ring /-- An `ordered_comm_ring α` is a commutative ring `α` with a partial order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class ordered_comm_ring (α : Type u) extends ordered_ring α, comm_ring α @[priority 100] -- See note [lower instance priority] instance ordered_comm_ring.to_ordered_comm_semiring {α : Type u} [ordered_comm_ring α] : ordered_comm_semiring α := { .. (by apply_instance : ordered_semiring α), .. ‹ordered_comm_ring α› } /-- Pullback an `ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.ordered_comm_ring [ordered_comm_ring α] {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (- x) = - f x) (sub : ∀ x y, f (x - y) = f x - f y) : ordered_comm_ring β := { ..hf.ordered_ring f zero one add mul neg sub, ..hf.comm_ring f zero one add mul neg sub } end ordered_comm_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α, nontrivial α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] : linear_ordered_add_comm_group α := { .. s } section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _ _ _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, refine decidable.or_iff_not_and_not.2 (λ h, _), revert hab, cases lt_or_gt_of_ne h.1 with ha ha; cases lt_or_gt_of_ne h.2 with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. ‹linear_ordered_ring α› } @[simp] lemma abs_one : |(1 : α)| = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : |(2 : α)| = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : |a * b| = |a| * |b| := begin haveI := @linear_order.decidable_le α _, rw [abs_eq (decidable.mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp only [abs_of_nonpos, abs_of_nonneg, true_or, or_true, eq_self_iff_true, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, neg_neg, *] end /-- `abs` as a `monoid_with_zero_hom`. -/ def abs_hom : monoid_with_zero_hom α α := ⟨abs, abs_zero, abs_one, abs_mul⟩ @[simp] lemma abs_mul_abs_self (a : α) : |a| * |a| = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) @[simp] lemma abs_mul_self (a : α) : |a * a| = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by haveI := @linear_order.decidable_le α _; exact ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, λ h, h.elim (and_imp.2 decidable.mul_nonneg) (and_imp.2 decidable.mul_nonneg_of_nonpos_of_nonpos)⟩ /-- Out of three elements of a `linear_ordered_ring`, two must have the same sign. -/ lemma mul_nonneg_of_three (a b c : α) : 0 ≤ a * b ∨ 0 ≤ b * c ∨ 0 ≤ c * a := by iterate 3 { rw mul_nonneg_iff }; have := le_total 0 a; have := le_total 0 b; have := le_total 0 c; itauto lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : α) : 0 ≤ a * a := abs_mul_self a ▸ abs_nonneg _ @[simp] lemma neg_le_self_iff : -a ≤ a ↔ 0 ≤ a := by simp [neg_le_iff_add_nonneg, ← two_mul, mul_nonneg_iff, zero_le_one, (@zero_lt_two α _ _).not_le] @[simp] lemma neg_lt_self_iff : -a < a ↔ 0 < a := by simp [neg_lt_iff_pos_add, ← two_mul, mul_pos_iff, zero_lt_one, (@zero_lt_two α _ _).not_lt] @[simp] lemma le_neg_self_iff : a ≤ -a ↔ a ≤ 0 := calc a ≤ -a ↔ -(-a) ≤ -a : by rw neg_neg ... ↔ 0 ≤ -a : neg_le_self_iff ... ↔ a ≤ 0 : neg_nonneg @[simp] lemma lt_neg_self_iff : a < -a ↔ a < 0 := calc a < -a ↔ -(-a) < -a : by rw neg_neg ... ↔ 0 < -a : neg_lt_self_iff ... ↔ a < 0 : neg_pos @[simp] lemma abs_eq_self : |a| = a ↔ 0 ≤ a := by simp [abs_eq_max_neg] @[simp] lemma abs_eq_neg_self : |a| = -a ↔ a ≤ 0 := by simp [abs_eq_max_neg] /-- For an element `a` of a linear ordered ring, either `abs a = a` and `0 ≤ a`, or `abs a = -a` and `a < 0`. Use cases on this lemma to automate linarith in inequalities -/ lemma abs_cases (a : α) : (|a| = a ∧ 0 ≤ a) ∨ (|a| = -a ∧ a < 0) := begin by_cases 0 ≤ a, { left, exact ⟨abs_eq_self.mpr h, h⟩ }, { right, push_neg at h, exact ⟨abs_eq_neg_self.mpr (le_of_lt h), h⟩ } end lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := neg_lt_zero.2 zero_lt_one lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := by haveI := @linear_order.decidable_le α _; exact have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : decidable.mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_sq_le_sq {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := by haveI := @linear_order.decidable_le α _; exact le_of_not_gt (λhab, (decidable.mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := by haveI := @linear_order.decidable_le α _; exact ⟨decidable.mul_self_le_mul_self h1, nonneg_le_nonneg_of_sq_le_sq h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := by haveI := @linear_order.decidable_le α _; exact ((@decidable.strict_mono_on_mul_self α _ _).lt_iff_lt h1 h2).symm lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b := by haveI := @linear_order.decidable_le α _; exact (@decidable.strict_mono_on_mul_self α _ _).inj_on.eq_iff h1 h2 @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', decidable.mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := by haveI := @linear_order.decidable_le α _; exact ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', decidable.mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin haveI := @linear_order.decidable_le α _, rw [← abs_mul_abs_self x], exact decidable.mul_self_le_mul_self (abs_nonneg x) (abs_le.2 ⟨neg_le.2 h₂, h₁⟩) end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ ha, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := by haveI := @linear_order.decidable_le α _; exact lt_of_not_ge (λ hb, absurd h (decidable.mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := by rw [add_eq_zero_iff', mul_self_eq_zero, mul_self_eq_zero]; apply mul_self_nonneg lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : |a| = |b| ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : |a| < |b| ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : |a| ≤ |b| ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_one_iff_mul_self_le_one : |a| ≤ 1 ↔ a * a ≤ 1 := by simpa only [abs_one, one_mul] using @abs_le_iff_mul_self_le α _ a 1 /-- Pullback a `linear_ordered_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : linear_ordered_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_ring f zero one add mul neg sub } end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that addition is monotone and multiplication by a positive number is strictly monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_ordered_comm_ring [d : linear_ordered_comm_ring α] : ordered_comm_ring α := { ..d } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring α] : integral_domain α := { ..linear_ordered_ring.to_domain, ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] : linear_ordered_semiring α := { .. d, ..linear_ordered_ring.to_linear_ordered_semiring } section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := by haveI := @linear_order.decidable_le α _; exact have ba : b * a ≤ max d b * max c a, from decidable.mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from decidable.mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_sq (a b : α) : |a - b| * |a - b| = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp only [mul_add, add_comm, add_left_comm, mul_comm, sub_eq_add_neg, mul_one, mul_neg_eq_neg_mul_symm, neg_add_rev, neg_neg], end end linear_ordered_comm_ring section variables [ring α] [linear_order α] {a b : α} @[simp] lemma abs_dvd (a b : α) : |a| ∣ b ↔ a ∣ b := by { cases abs_choice a with h h; simp only [h, neg_dvd] } lemma abs_dvd_self (a : α) : |a| ∣ a := (abs_dvd a a).mpr (dvd_refl a) @[simp] lemma dvd_abs (a b : α) : a ∣ |b| ↔ a ∣ b := by { cases abs_choice b with h h; simp only [h, dvd_neg] } lemma self_dvd_abs (a : α) : a ∣ |a| := (dvd_abs a a).mpr (dvd_refl a) lemma abs_dvd_abs (a b : α) : |a| ∣ |b| ↔ a ∣ b := (abs_dvd _ _).trans (dvd_abs _ _) lemma even_abs {a : α} : even (|a|) ↔ even a := dvd_abs _ _ lemma odd_abs {a : α} : odd (abs a) ↔ odd a := by { cases abs_choice a with h h; simp only [h, odd_neg] } end section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] /-- Pullback a `linear_ordered_comm_ring` under an injective map. See note [reducible non-instances]. -/ @[reducible] def function.injective.linear_ordered_comm_ring {β : Type*} [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [nontrivial β] (f : β → α) (hf : function.injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : linear_ordered_comm_ring β := { ..linear_order.lift f hf, ..‹nontrivial β›, ..hf.ordered_comm_ring f zero one add mul neg sub } end linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α := (one_nonneg : nonneg 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (one_pos : pos 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) [dec_nonneg : decidable_pred nonneg] namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a linear order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring [nontrivial α] [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { one_pos := (pos_iff 1).mpr ⟨one_nonneg, λ h, zero_ne_one (nonneg_antisymm one_nonneg h).symm⟩, nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, decidable.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, decidable.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nontrivial α›, ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { one_nonneg := ((pos_iff _).mp one_pos).1, mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } /-- Construct `linear_order` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_order [decidable_pred (nonneg : α → Prop)] : linear_order α := { le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α) } /-- Construct `linear_ordered_ring` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_ordered_ring [decidable_pred (nonneg : α → Prop)] : linear_ordered_ring α := { mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_le_one := le_of_lt $ lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α), ..(infer_instance : linear_order α) } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `linear_ordered_comm_ring` -/ def to_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : linear_ordered_comm_ring α := { mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ @[protect_proj] class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) namespace canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring α] {a b : α} @[priority 100] -- see Note [lower instance priority] instance to_no_zero_divisors : no_zero_divisors α := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance to_covariant_mul_le : covariant_class α α (*) (≤) := begin refine ⟨λ a b c h, _⟩, rcases le_iff_exists_add.1 h with ⟨c, rfl⟩, rw mul_add, apply self_le_add_right end /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one @[simp] lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] variables [has_sub α] [has_ordered_sub α] [contravariant_class α α (+) (≤)] [is_total α (≤)] lemma _root_.mul_sub' (a b c : α) : a * (b - c) = a * b - a * c := begin cases total_of (≤) b c with hbc hcb, { rw [sub_eq_zero_iff_le.2 hbc, mul_zero, sub_eq_zero_iff_le.2 (mul_le_mul_left' hbc a)] }, { apply eq_sub_of_add_eq'', rw [← mul_add, sub_add_cancel_of_le hcb] } end lemma _root_.sub_mul' (a b c : α) : (a - b) * c = a * c - b * c := by simp only [← mul_comm c, mul_sub'] end canonically_ordered_comm_semiring /-! ### Structures involving `*` and `0` on `with_top` and `with_bot` The main results of this section are `with_top.canonically_ordered_comm_semiring` and `with_bot.comm_monoid_with_zero`. -/ namespace with_top instance [nonempty α] : nontrivial (with_top α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end lemma mul_lt_top [partial_order α] {a b : with_top α} (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a * b < ⊤ := begin lift a to α using ha, lift b to α using hb, simp only [← coe_mul, coe_lt_top] end end mul_zero_class /-- `nontrivial α` is needed here as otherwise we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`. -/ instance [mul_zero_one_class α] [nontrivial α] : mul_zero_one_class (with_top α) := { mul := (*), one := 1, zero := 0, one_mul := λ a, match a with | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one] end, mul_one := λ a, match a with | none := show ⊤ * ((1:α) : with_top α) = ⊤, by simp [-with_top.coe_one] | (some a) := show ↑a * ((1:α) : with_top α) = a, by simp [coe_mul.symm, -with_top.coe_one] end, .. with_top.mul_zero_class } instance [mul_zero_class α] [no_zero_divisors α] : no_zero_divisors (with_top α) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ instance [semigroup_with_zero α] [no_zero_divisors α] : semigroup_with_zero (with_top α) := { mul := (*), zero := 0, mul_assoc := λ a b c, begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end, .. with_top.mul_zero_class } instance [monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : monoid_with_zero (with_top α) := { .. with_top.mul_zero_one_class, .. with_top.semigroup_with_zero } instance [comm_monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : comm_monoid_with_zero (with_top α) := { mul := (*), zero := 0, mul_comm := λ a b, begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end, .. with_top.monoid_with_zero } variables [canonically_ordered_comm_semiring α] private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end /-- This instance requires `canonically_ordered_comm_semiring` as it is the smallest class that derives from both `non_assoc_non_unital_semiring` and `canonically_ordered_add_monoid`, both of which are required for distributivity. -/ instance [nontrivial α] : comm_semiring (with_top α) := { right_distrib := distrib', left_distrib := assume a b c, by rw [mul_comm, distrib', mul_comm b, mul_comm c]; refl, .. with_top.add_comm_monoid, .. with_top.comm_monoid_with_zero,} instance [nontrivial α] : canonically_ordered_comm_semiring (with_top α) := { .. with_top.comm_semiring, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, } end with_top namespace with_bot instance [nonempty α] : nontrivial (with_bot α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_bot α) := with_top.mul_zero_class lemma mul_def {a b : with_bot α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_bot {a : with_bot α} (h : a ≠ 0) : a * ⊥ = ⊥ := with_top.mul_top h @[simp] lemma bot_mul {a : with_bot α} (h : a ≠ 0) : ⊥ * a = ⊥ := with_top.top_mul h @[simp] lemma bot_mul_bot : (⊥ * ⊥ : with_bot α) = ⊥ := with_top.top_mul_top end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_bot α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) {a : with_bot α} : a * b = a.bind (λa:α, ↑(a * b)) := with_top.mul_coe hb @[simp] lemma mul_eq_bot_iff {a b : with_bot α} : a * b = ⊥ ↔ (a ≠ 0 ∧ b = ⊥) ∨ (a = ⊥ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma bot_lt_mul [partial_order α] {a b : with_bot α} (ha : ⊥ < a) (hb : ⊥ < b) : ⊥ < a * b := begin lift a to α using ne_bot_of_gt ha, lift b to α using ne_bot_of_gt hb, simp only [← coe_mul, bot_lt_coe], end end mul_zero_class /-- `nontrivial α` is needed here as otherwise we have `1 * ⊥ = ⊥` but also `= 0 * ⊥ = 0`. -/ instance [mul_zero_one_class α] [nontrivial α] : mul_zero_one_class (with_bot α) := with_top.mul_zero_one_class instance [mul_zero_class α] [no_zero_divisors α] : no_zero_divisors (with_bot α) := with_top.no_zero_divisors instance [semigroup_with_zero α] [no_zero_divisors α] : semigroup_with_zero (with_bot α) := with_top.semigroup_with_zero instance [monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : monoid_with_zero (with_bot α) := with_top.monoid_with_zero instance [comm_monoid_with_zero α] [no_zero_divisors α] [nontrivial α] : comm_monoid_with_zero (with_bot α) := with_top.comm_monoid_with_zero instance [canonically_ordered_comm_semiring α] [nontrivial α] : comm_semiring (with_bot α) := with_top.comm_semiring end with_bot
040850485a0ec07caa91f2c8207172874de61f9c
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/finset/basic.lean
0b7c23172100571daecd5a62108425d23ae822c8
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,120
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import data.list.basic data.list.perm order.boolean_algebra algebra.functions open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} def nodup_list (α : Type*) := {l : list α // nodup l} def to_nodup_list_of_nodup {l : list α} (n : nodup l) : nodup_list α := ⟨l, n⟩ def to_nodup_list [decidable_eq α] (l : list α) : nodup_list α := ⟨erase_dup l, nodup_erase_dup l⟩ private def eqv (l₁ l₂ : nodup_list α) := perm l₁.1 l₂.1 local infix ~ := eqv private def eqv.refl (l : nodup_list α) : l ~ l := perm.refl _ private def eqv.symm {l₁ l₂ : nodup_list α} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private def eqv.trans {l₁ l₂ l₃ : nodup_list α} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans instance finset.nodup_list_setoid (α : Type*) : setoid (nodup_list α) := setoid.mk (@eqv α) (mk_equivalence (@eqv α) (@eqv.refl α) (@eqv.symm α) (@eqv.trans α)) def {u} finset (α : Type u) : Type u := quotient (finset.nodup_list_setoid α) namespace finset def to_finset_of_nodup (l : list α) (n : nodup l) : finset α := ⟦to_nodup_list_of_nodup n⟧ @[elab_as_eliminator] protected theorem induction_on_to_finset {α : Type*} {p : finset α → Prop} (s : finset α) (h : ∀ (l : list α) (h : nodup l), p (to_finset_of_nodup l h)) : p s := quot.induction_on s $ assume ⟨l, hl⟩, h l hl def to_finset [decidable_eq α] (l : list α) : finset α := ⟦to_nodup_list l⟧ lemma to_finset_eq_of_nodup [decidable_eq α] {l : list α} (n : nodup l) : to_finset_of_nodup l n = to_finset l := quotient.sound $ show l.perm (erase_dup l), by rw erase_dup_eq_self.2 n instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff (l₁.1.perm l₂.1) ⟨λ e, quot.sound e, quotient.exact⟩ section mem def mem (a : α) (s : finset α) : Prop := quot.lift_on s (λ l, a ∈ l.1) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_iff_mem_of_perm e) instance : has_mem α (finset α) := ⟨mem⟩ @[simp] lemma mem_to_finset_of_nodup_eq {a : α} {l : list α} (n : nodup l) : (a ∈ to_finset_of_nodup l n) = (a ∈ l) := rfl theorem mem_of_mem_list {a : α} {l : nodup_list α} (h : a ∈ l.1) : a ∈ @id (finset α) ⟦l⟧ := h theorem mem_list_of_mem {a : α} {l : nodup_list α} (h : a ∈ @id (finset α) ⟦l⟧) : a ∈ l.1 := h theorem mem_to_finset_of_mem [decidable_eq α] {a : α} {l : list α} : a ∈ l → a ∈ to_finset l := mem_erase_dup.2 @[simp] theorem mem_to_finset [decidable_eq α] {a : α} {l : list α} : a ∈ to_finset l ↔ a ∈ l := mem_erase_dup instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ λ l, list.decidable_mem a l.1 /- extensionality -/ theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quotient.induction_on₂ s₁ s₂ $ λ l₁ l₂ e, quot.sound $ (perm_ext l₁.2 l₂.2).2 e end mem /- subset -/ section subset protected def subset (s₁ s₂ : finset α) : Prop := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, l₁.1 ⊆ l₂.1) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, mem_of_perm p₂ (s₁ (mem_of_perm p₁.symm i))) (λ s₂ a i, mem_of_perm p₂.symm (s₂ (mem_of_perm p₁ i))))) instance : has_subset (finset α) := ⟨finset.subset⟩ -- theorem subset_univ [h : fintype α] (s : finset α) : s ⊆ univ := -- quot.induction_on s (λ l a i, fintype.complete a) @[simp] theorem subset.refl (s : finset α) : s ⊆ s := quot.induction_on s (λ l, by refl) theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quotient.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃, list.subset.trans) theorem mem_of_subset_of_mem {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ h₂) theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (λ x, ⟨mem_of_subset_of_mem H₁, mem_of_subset_of_mem H₂⟩) theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ (∀x, x ∈ s₁ → x ∈ s₂) := ⟨λ s a, mem_of_subset_of_mem s, quotient.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H)⟩ end subset section empty variables {s : finset α} {a b : α} /- empty -/ protected def empty : finset α := to_finset_of_nodup [] nodup_nil instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem not_mem_empty : a ∉ (∅ : finset α) := id theorem empty_subset : ∅ ⊆ s := quot.induction_on s (λ l, list.nil_subset l.1) theorem eq_empty_of_forall_not_mem (H : ∀x, x ∉ s) : s = ∅ := ext (λ x, iff_false_intro (H x)) theorem eq_empty_of_subset_empty (h : s ⊆ ∅) : s = ∅ := subset.antisymm h empty_subset theorem subset_empty_iff (x : finset α) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (λ xeq, by rw xeq; apply subset.refl ∅) theorem exists_mem_of_ne_empty : s ≠ ∅ → ∃ a : α, a ∈ s := finset.induction_on_to_finset s $ assume l hl, match l, hl with | [] := assume _ h, false.elim $ h rfl | (a :: l) := assume _ _, ⟨a, by simp⟩ end end empty -- /- universe -/ -- def univ [h : fintype A] : finset A := -- to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) -- theorem mem_univ [fintype A] (x : A) : x ∈ univ := -- fintype.complete x -- theorem mem_univ_eq [fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- insert -/ section insert variables [decidable_eq α] {s t : finset α} {a b : α} protected def insert (a : α) (s : finset α) : finset α := quot.lift_on s (λ l, to_finset_of_nodup (insert a l.1) (nodup_insert l.2)) (λ (l₁ l₂ : nodup_list α) (p : l₁ ~ l₂), quot.sound (perm_insert a p)) instance : has_insert α (finset α) := ⟨finset.insert⟩ @[simp] theorem mem_insert : a ∈ insert b s ↔ (a = b ∨ a ∈ s) := finset.induction_on_to_finset s $ assume l hl, show a ∈ insert b l ↔ (a = b ∨ a ∈ l), by simp theorem mem_insert_self : a ∈ insert a s := by simp theorem mem_insert_of_mem : a ∈ s → a ∈ insert b s := by simp {contextual := tt} theorem mem_of_mem_insert_of_ne (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem insert_eq_of_mem (h : a ∈ s) : insert a s = s := ext (λ x, by rw mem_insert; apply or_iff_right_of_imp; intro eq; rw eq; assumption) @[simp] theorem insert.comm : insert a (insert b s) = insert b (insert a s) := ext $ by simp @[simp] theorem insert_idem : insert a (insert a s) = insert a s := ext $ by simp [mem_insert] @[simp] theorem insert_ne_empty : insert a s ≠ ∅ := assume h, @not_mem_empty α a $ h ▸ by simp theorem subset_insert [h : decidable_eq α] : s ⊆ insert a s := subset_iff.2 (λ x h, mem_insert_of_mem h) theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := subset_iff.2 $ assume x, by simp [-forall_or_distrib_left]; exact or.imp_right (subset_iff.1 h _) @[recursor 6] protected theorem induction {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) (s) : p s := finset.induction_on_to_finset s $ λl, list.rec_on l (assume _, h₁) (assume a l ih hal, let l' := to_finset_of_nodup l $ nodup_of_nodup_cons hal in have insert a l' = to_finset_of_nodup (a :: l) hal, from ext $ by simp, this ▸ @h₂ a l' (not_mem_of_nodup_cons hal) (ih _)) protected theorem induction_on {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s -- useful in proofs by induction theorem forall_of_forall_insert {p : α → Prop} (H : ∀ x, x ∈ insert a s → p x) : ∀ x, x ∈ s → p x := λ x xs, H x (mem_insert_of_mem xs) end insert section singleton variables [decidable_eq α] {a b : α} {s : finset α} @[simp] theorem mem_singleton : b ∈ ({a} : finset α) ↔ (b = a) := show b ∈ insert a ∅ ↔ b = a, by simp theorem mem_singleton_self : a ∈ ({a} : finset α) := mem_insert_self theorem singleton_inj (h : {a} = ({b}:finset α)) : a = b := have a ∈ ({b} : finset α), by rw ← h; apply mem_singleton_self, mem_singleton.1 this @[simp] theorem singleton_ne_empty : ({a} : finset α) ≠ ∅ := insert_ne_empty @[simp] theorem insert_singelton_self_eq : ({a, a} : finset α) = {a} := show insert a {a} = ({a} : finset α), by rw [insert_eq_of_mem]; apply mem_singleton_self end singleton /- section sep variables [decidable_eq α] instance : has_sep α (finset α) := ⟨λp s, quotient.lift_on s (λl, to_finset_of_nodup (l.val.filter p) _) _⟩ end sep -/ /- union -/ section union variable [decidable_eq α] protected def union (s₁ s₂ : finset α) : finset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union l₁.1 l₂.1) (nodup_union l₁.1 l₂.2)) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_union p₁ p₂)) instance : has_union (finset α) := ⟨finset.union⟩ @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂, list.mem_union) theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := by simp {contextual := tt} theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := by simp {contextual := tt} theorem mem_or_mem_of_mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := mem_union.1 theorem union_subset {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₃ → s₂ ⊆ s₃ → s₁ ∪ s₂ ⊆ s₃ := by simp [subset_iff] {contextual:=tt}; finish theorem subset_union_left {s₁ s₂ : finset α} : s₁ ⊆ s₁ ∪ s₂ := subset_iff.mpr $ assume x, mem_union_left _ theorem subset_union_right {s₁ s₂ : finset α} : s₂ ⊆ s₁ ∪ s₂ := subset_iff.mpr $ assume x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ by simp instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ by simp instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : (s ∪ s) = s := ext $ by simp instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ by simp theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ by simp @[simp] theorem union_self (s : finset α) : s ∪ s = s := ext $ by simp @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ by simp @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ by simp theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := ext $ by simp @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := ext $ by simp @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := ext $ by simp end union /- inter -/ section inter variable [decidable_eq α] protected def inter (s₁ s₂ : finset α) : finset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter l₁.1 l₂.1) (nodup_inter_of_nodup _ l₁.2)) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_inter p₁ p₂)) instance : has_inter (finset α) := ⟨finset.inter⟩ @[simp] theorem mem_inter (a : α) (s₁ s₂ : finset α) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := quotient.induction_on₂ s₁ s₂ (λ l₁ l₂, mem_inter) theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := by simp {contextual := tt} theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := by simp {contextual := tt} theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := by simp {contextual := tt} theorem inter_subset_left {s₁ s₂ : finset α} : s₁ ∩ s₂ ⊆ s₁ := by simp [subset_iff] {contextual:=tt}; finish theorem inter_subset_right {s₁ s₂ : finset α} : s₁ ∩ s₂ ⊆ s₂ := by simp [subset_iff] {contextual:=tt}; finish theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp [subset_iff] {contextual:=tt}; finish @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ by simp @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ by simp @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ by simp @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ by simp @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ by simp @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ by simp @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ by simp @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ by simp; intro x; constructor; finish @[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 $ assume a', by by_cases a' = a with h'; simp [mem_inter, mem_insert, h, h'] @[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 α} : a ∈ s → {a} ∩ s = {a} := show a ∈ s → insert a ∅ ∩ s = insert a ∅, by simp {contextual := tt} @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} : a ∉ s → {a} ∩ s = ∅ := show a ∉ s → insert a ∅ ∩ s = ∅, by simp {contextual := tt} @[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] end inter section lattice instance [decidable_eq α] : lattice (finset α) := { le := (⊆), le_refl := subset.refl, le_trans := assume a b c, subset.trans, le_antisymm := assume a b, subset.antisymm, sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := assume a b, subset_union_left, le_sup_right := assume a b, subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := assume a b, inter_subset_left, inf_le_right := assume a b, inter_subset_right } instance [decidable_eq α] : semilattice_inf_bot (finset α) := { finset.lattice.lattice with bot := ∅, bot_le := assume a, empty_subset } instance [decidable_eq α] : distrib_lattice (finset α) := { finset.lattice.lattice with le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp [subset_iff, and_imp, or_imp_distrib] {contextual:=tt} } end lattice /- distributivity laws -/ section inter variable [decidable_eq α] theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext $ by simp [mem_inter, mem_union]; intro; split; finish theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext $ by simp [mem_inter, mem_union]; intro; split; finish theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext $ by simp [mem_inter, mem_union]; intro; split; finish theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext $ by simp [mem_inter, mem_union]; intro; split; finish end inter /- erase -/ section erase variables [decidable_eq α] {a b c : α} {s t : finset α} def erase (a : α) (s : finset α) : finset α := quot.lift_on s (λ l, to_finset_of_nodup (l.1.erase a) (nodup_erase_of_nodup a l.2)) (λ (l₁ l₂ : nodup_list α) (p : l₁ ~ l₂), quot.sound (erase_perm_erase a p)) @[simp] theorem mem_erase : a ∈ erase b s ↔ a ≠ b ∧ a ∈ s := finset.induction_on_to_finset s $ λ l hl, mem_erase_iff_of_nodup hl theorem not_mem_erase : a ∉ erase a s := by simp @[simp] theorem erase_empty : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase : b ∈ erase a s → b ≠ a := by simp {contextual:=tt} theorem mem_of_mem_erase : b ∈ erase a s → b ∈ s := by simp {contextual:=tt} theorem mem_erase_of_ne_of_mem : a ≠ b → a ∈ s → a ∈ erase b s := by simp {contextual:=tt} theorem erase_insert (h : a ∉ s) : erase a (insert a s) = s := ext $ assume x, by simp; constructor; finish theorem insert_erase (h : a ∈ s) : insert a (erase a s) = s := ext $ assume x, by simp; constructor; finish theorem erase_subset_erase (h : s ⊆ t) : erase a s ⊆ erase a t := subset_iff.2 $ assume x, by simp [-and_imp]; exact and.imp_right (mem_of_subset_of_mem h) theorem erase_subset : erase a s ⊆ s := subset_iff.2 $ assume x, by simp {contextual:=tt} theorem erase_eq_of_not_mem (h : a ∉ s) : erase a s = s := ext $ assume b, by by_cases b = a; simp * theorem erase_insert_subset : erase a (insert a s) ⊆ s := by by_cases a ∈ s; simp [h, erase_subset, erase_insert, subset.refl] theorem erase_subset_of_subset_insert (h : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (erase_subset_erase h) erase_insert_subset theorem insert_erase_subset : s ⊆ insert a (erase a s) := decidable.by_cases (λ ains : a ∈ s, by rw [insert_erase ains]; apply subset.refl) (λ nains : a ∉ s, by rw[erase_eq_of_not_mem nains]; apply subset_insert) theorem subset_insert_of_erase_subset (h : erase a s ⊆ t) : s ⊆ insert a t := subset.trans insert_erase_subset (insert_subset_insert h) theorem subset_insert_iff (s t : finset α) (a : α) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro erase_subset_of_subset_insert subset_insert_of_erase_subset end erase section filter variables [decidable_eq α] {p : α → Prop} [decidable_pred p] {s s₁ s₂ : finset α} {a : α} protected def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := quotient.lift_on s (λl, to_finset_of_nodup (l.val.filter p) $ nodup_filter _ l.property) (assume l₁ l₂ (h : perm l₁.val l₂.val), quot.sound $ perm_filter _ h) @[simp] theorem mem_filter : a ∈ s.filter p ↔ (a ∈ s ∧ p a) := finset.induction_on_to_finset s $ λl₁ h₁, list.mem_filter theorem filter_subset : s.filter p ⊆ s := by simp [subset_iff] {contextual := tt} theorem filter_union : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ assume a, by simp [and_or_distrib_left] theorem filter_filter {p' : α → Prop} [decidable_pred p'] : (s.filter p).filter p' = s.filter (λa, p a ∧ p' a) := ext $ assume a, by simp @[simp] theorem filter_false {h : decidable_pred $ λa:α, false} : @finset.filter α _ (λa:α, false) h s = ∅ := ext $ assume a, by simp theorem filter_union_filter_neg_eq : s.filter p ∪ s.filter (λa, ¬ p a) = s := ext $ assume a, by by_cases p a; simp [iff_iff_implies_and_implies, *] {contextual := tt} theorem filter_inter_filter_neg_eq : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := ext $ assume a, by by_cases p a; simp * {contextual := tt} end filter section sdiff variables [decidable_eq α] {a : α} {s₁ s₂ t₁ t₂ : finset α} instance : has_sdiff (finset α) := ⟨λs₁ s₂, s₁.filter (λa, a ∉ s₂)⟩ @[simp] theorem mem_sdiff_iff : a ∈ s₁ \ s₂ ↔ (a ∈ s₁ ∧ a ∉ s₂) := mem_filter lemma sdiff_union_of_subset (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext $ assume a, by rw [subset_iff] at h; by_cases a ∈ s₁; simp [iff_iff_implies_and_implies, *] {contextual := tt} lemma sdiff_inter_self : (s₂ \ s₁) ∩ s₁ = ∅ := ext $ by simp {contextual := tt} lemma sdiff_subset_sdiff : t₁ ⊆ t₂ → s₂ ⊆ s₁ → t₁ \ s₁ ⊆ t₂ \ s₂ := begin simp [subset_iff, mem_sdiff_iff] {contextual := tt}, exact assume h₁ h₂ a _ ha₁ ha₂, ha₁ $ h₂ _ ha₂ end end sdiff /- range -/ section range variables {n m l : ℕ} def range (n : ℕ) : finset ℕ := to_finset_of_nodup (list.range n) (nodup_range n) @[simp] theorem mem_range : m ∈ range n ↔ m < n := list.mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_succ : range (succ n) = insert n (range n) := ext $ by simp [mem_insert, le_iff_lt_or_eq, lt_succ_iff] @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem exists_nat_subset_range {s : finset ℕ} : ∃n : ℕ, s ⊆ range n := s.induction_on ⟨0, by simp⟩ $ assume a s ha ⟨n, hn⟩, ⟨max (a + 1) n, subset_iff.mpr $ assume x, begin simp [subset_iff, mem_range] at hn, simp [or_imp_distrib, mem_range, lt_max_iff, hn] {contextual := tt}, exact assume _, or.inr (lt_succ_self a) end⟩ end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := ⟨λ⟨x, hx⟩, not_mem_empty (hx.left), false.elim⟩ 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) := iff.intro (λ H, let ⟨x,H1,H2⟩ := H in or.elim (mem_insert.mp H1) (λ l, or.inl (eq.subst l H2)) (λ r, or.inr ⟨x, ⟨r, H2⟩⟩)) (λ H, or.elim H (λ l, ⟨a, ⟨mem_insert_self, l⟩⟩) (λ r, let ⟨x,H2,H3⟩ := r in ⟨x, ⟨mem_insert_of_mem H2, H3⟩⟩)) theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff.intro (λ H, trivial) (λ H x H', absurd H' not_mem_empty) 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 [or_imp_distrib, forall_and_distrib] section image variables (f : α → β) (s s₁ s₂ : finset α) [decidable_eq β] protected def image : finset β := quot.lift_on s (λl, to_finset $ l.val.map f) $ assume ⟨l₁, hl₁⟩ ⟨l₂, hl₂⟩ (h : perm l₁ l₂), quotient.sound $ perm_erase_dup_of_perm $ perm_map _ $ h @[simp] lemma image_empty {f : α → β} : (∅ : finset α).image f = ∅ := rfl variables {f s s₁ s₂} {b : β} [decidable_eq α] lemma mem_image_iff : b ∈ s.image f ↔ (∃a∈s, f a = b) := finset.induction_on_to_finset s $ assume l h, show b ∈ to_finset (l.map f) ↔ _, by simp [mem_to_finset] lemma erase_dup_map_erase_dup_eq {f : α → β} : ∀{l : list α}, erase_dup (map f (erase_dup l)) = (erase_dup $ map f l) | [] := by simp | (x :: xs) := have f x ∈ map f (erase_dup xs) ↔ f x ∈ map f xs, by simp, by by_cases x ∈ xs; by_cases f x ∈ map f xs; simp * at * lemma image_to_finset {l : list α} : (to_finset l).image f = to_finset (l.map f) := quot.sound $ show perm (erase_dup $ map f $ erase_dup l) (erase_dup $ map f l), by rw [erase_dup_map_erase_dup_eq] lemma image_to_finset_of_nodup {l : list α} (hl : nodup l) (h : ∀x∈l, ∀y∈l, f x = f y → x = y) : (to_finset_of_nodup l hl).image f = to_finset_of_nodup (l.map f) (nodup_map_on h hl) := quot.sound $ show perm (erase_dup (map f l)) (l.map f), by rw [erase_dup_eq_self.2 (nodup_map_on h hl)] lemma image_id : s.image id = s := quot.induction_on s $ assume ⟨l, hl⟩, show to_finset (l.map id) = to_finset_of_nodup l hl, by rw [map_id, to_finset_eq_of_nodup] lemma image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := quot.induction_on s $ assume ⟨l, hl⟩, show ((to_finset_of_nodup l hl).image f).image g = (to_finset_of_nodup l hl).image (g ∘ f), by simp [to_finset_eq_of_nodup, image_to_finset] lemma image_subset_image : s₁ ⊆ s₂ → s₁.image f ⊆ s₂.image f := by simp [subset_iff, mem_image_iff] {contextual:=tt}; from assume h b a h_eq ha, ⟨a, h_eq, h _ ha⟩ lemma image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ assume b, by simp [mem_image_iff]; exact iff.intro (assume ⟨hb, ⟨a, h_eq, ha⟩⟩, ⟨a, h_eq, show p (f a), from h_eq.symm ▸ hb, ha⟩) (assume ⟨a, h_eq, ha, has⟩, ⟨h_eq ▸ ha, a, h_eq, has⟩) lemma image_union {f : α → β} : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ assume b, by simp [mem_image_iff, and_or_distrib_left, exists_or_distrib] lemma image_inter (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ assume b, by simp [mem_image_iff, iff_def]; from and.intro (assume x x_eq hx y y_eq hy, have y = x, from hf _ _ $ by simp *, ⟨x, x_eq, hx, this ▸ hy⟩) (assume x x_eq h₁ h₂, ⟨⟨x, x_eq, h₁⟩, ⟨x, x_eq, h₂⟩⟩) @[simp] lemma image_singleton {f : α → β} {a : α} : ({a}: finset α).image f = {f a} := ext $ by simp [mem_image_iff, and_or_distrib_left, exists_or_distrib, iff_def] {contextual := tt} @[simp] lemma image_insert {f : α → β} {s : finset α} {a : α} : (insert a s).image f = insert (f a) (s.image f) := by simp [insert_eq, image_union] @[simp] lemma image_eq_empty_iff : s.image f = ∅ ↔ s = ∅ := iff.intro (assume h, have ∀a, a ∉ s, from assume a ha, have f a ∈ s.image f, from mem_image_iff.mpr ⟨a, ha, rfl⟩, by simp * at *, ext $ by simp *) (assume h, by simp *) end image section card variables [decidable_eq α] {a : α} {s : finset α} {n : ℕ} /- card -/ def card (s : finset α) : nat := quot.lift_on s (λ l, length l.1) (λ l₁ l₂, perm_length) @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl lemma ne_empty_of_card_eq_succ : card s = succ n → s ≠ ∅ := λ h hn, by rw hn at h; contradiction @[simp] theorem card_insert_of_not_mem : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list α) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le : card (insert a s) ≤ card s + 1 := if h : a ∈ s then by simp [h, le_add_left] else by rw [card_insert_of_not_mem h] theorem eq_empty_of_card_eq_zero : card s = 0 → s = ∅ := s.induction_on (assume _, rfl) (assume a s ha ih, by rw [card_insert_of_not_mem ha]; exact assume h, nat.no_confusion h) theorem card_erase_of_mem : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_range : card (range n) = n := list.length_range n end card end finset
e77f92f0c7e6b1898a4c2631107366e2a4ee7d46
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Parser/Module.lean
d8924f4180b8271e4f4bf5f3fdae6fbfe5883de6
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
4,770
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Message import Init.Lean.Parser.Command namespace Lean namespace Parser namespace Module def «prelude» := parser! "prelude" def «import» := parser! "import " >> optional "runtime" >> ident def header := parser! optional «prelude» >> many «import» def updateTokens (c : ParserContext) : ParserContext := { tokens := match addParserTokens c.tokens header.info with | Except.ok tables => tables | Except.error _ => unreachable!, .. c } end Module structure ModuleParserState := (pos : String.Pos := 0) (recovering : Bool := false) instance ModuleParserState.inhabited : Inhabited ModuleParserState := ⟨{}⟩ private def mkErrorMessage (c : ParserContext) (pos : String.Pos) (errorMsg : String) : Message := let pos := c.fileMap.toPosition pos; { fileName := c.fileName, pos := pos, data := errorMsg } def parseHeader (env : Environment) (inputCtx : InputContext) : Syntax × ModuleParserState × MessageLog := let ctx := mkParserContext env inputCtx; let ctx := Module.updateTokens ctx; let s := mkParserState ctx.input; let s := whitespace ctx s; let s := Module.header.fn ctx s; let stx := s.stxStack.back; match s.errorMsg with | some errorMsg => let msg := mkErrorMessage ctx s.pos (toString errorMsg); (stx, { pos := s.pos, recovering := true }, { MessageLog . }.add msg) | none => (stx, { pos := s.pos }, {}) private def mkEOI (pos : String.Pos) : Syntax := let atom := mkAtom { pos := pos, trailing := "".toSubstring, leading := "".toSubstring } ""; Syntax.node `Lean.Parser.Module.eoi #[atom] def isEOI (s : Syntax) : Bool := s.isOfKind `Lean.Parser.Module.eoi def isExitCommand (s : Syntax) : Bool := s.isOfKind `Lean.Parser.Command.exit private def consumeInput (c : ParserContext) (pos : String.Pos) : String.Pos := let s : ParserState := { cache := initCacheForInput c.input, pos := pos }; let s := tokenFn c s; match s.errorMsg with | some _ => pos + 1 | none => s.pos partial def parseCommand (env : Environment) (inputCtx : InputContext) : ModuleParserState → MessageLog → Syntax × ModuleParserState × MessageLog | s@{ pos := pos, recovering := recovering }, messages => if inputCtx.input.atEnd pos then (mkEOI pos, s, messages) else let c := mkParserContext env inputCtx; let s := { ParserState . cache := initCacheForInput c.input, pos := pos }; let s := whitespace c s; let s := (commandParser : Parser).fn c s; match s.errorMsg with | none => let stx := s.stxStack.back; (stx, { pos := s.pos }, messages) | some errorMsg => if recovering then parseCommand { pos := consumeInput c s.pos, recovering := true } messages else let msg := mkErrorMessage c s.pos (toString errorMsg); let messages := messages.add msg; parseCommand { pos := consumeInput c s.pos, recovering := true } messages private partial def testModuleParserAux (env : Environment) (inputCtx : InputContext) (displayStx : Bool) : ModuleParserState → MessageLog → IO Bool | s, messages => match parseCommand env inputCtx s messages with | (stx, s, messages) => if isEOI stx || isExitCommand stx then do messages.forM $ fun msg => IO.println msg; pure (!messages.hasErrors) else do when displayStx (IO.println stx); testModuleParserAux s messages @[export lean_test_module_parser] def testModuleParser (env : Environment) (input : String) (fileName := "<input>") (displayStx := false) : IO Bool := timeit (fileName ++ " parser") $ do let inputCtx := mkInputContext input fileName; let (stx, s, messages) := parseHeader env inputCtx; when displayStx (IO.println stx); testModuleParserAux env inputCtx displayStx s messages partial def parseFileAux (env : Environment) (inputCtx : InputContext) : ModuleParserState → MessageLog → Array Syntax → IO Syntax | state, msgs, stxs => match parseCommand env inputCtx state msgs with | (stx, state, msgs) => if isEOI stx then if msgs.isEmpty then let stx := mkListNode stxs; pure stx.updateLeading else do msgs.forM $ fun msg => IO.println msg; throw (IO.userError "failed to parse file") else parseFileAux state msgs (stxs.push stx) def parseFile (env : Environment) (fname : String) : IO Syntax := do fname ← IO.realPath fname; contents ← IO.FS.readFile fname; let inputCtx := mkInputContext contents fname; let (stx, state, messages) := parseHeader env inputCtx; parseFileAux env inputCtx state messages #[stx] end Parser end Lean
0f778e86141250a2dabfc9ca0b8fb3509b8928d2
92e157ec9825b5e4597a6d715a8928703bc8e3b2
/src/mywork/lecture_5.lean
ac4ff3e32781912ce3c4d2fad961d23062f1cab2
[]
no_license
exb3dg/cs2120f21
9e566bc508762573c023d3e70f83cb839c199ec8
319b8bf0d63bf96437bf17970ce0198d0b3525cd
refs/heads/main
1,692,970,909,568
1,634,584,540,000
1,634,584,540,000
399,947,025
0
0
null
null
null
null
UTF-8
Lean
false
false
2,420
lean
/- INTRODUCTION and ELIMINATION RULES -/ /- For ∀ x, P x (every x has property P) - introduction rule: assume arbitrary x, then show P x - elimination rule: *apply* a proof of ∀ x, P x, as a kind of function to a specific value of x, say k, to produce a proof of P k. -/ theorem silly : ∀ (n : ℕ), true := begin assume (n : ℕ), exact true.intro, end /- The proposition true is unconditionally true, as proven by an always available proof called (in Lean) true.intro. -/ #check silly 7 /- The check command will tell you the type of any expression (aka term) in Lean. Here we can see that silly is like a function, and that when we apply it to the specific argument, 7, we get back a proof of the resulting proposition (which is just, "true"). We'll soon be equipped to deal with more interesting "return types". -/ /- For P → Q (if P is true then Q must also be true) - introduction rule: assume arbitrary P, then show Q - elimination rule: *apply* a proof of P → Q, as a - kind of function, to any proof of P to derive a proof of Q! -/ def foo : ∀ (x : ℕ), x = 0 → x + 1 = 1 := begin assume x h, rw h, end /- Wow! ∀ and → sure do seem similar. Indeed they're the same! They define function types. We construct a proof of ∀ or → by assuming the premise and showing that in that context we can derive a result of the conclusion type. We can then use a proof of a ∀ or → by treating it as a function that can be applied to a specific value to derive a proof *for that specific value. Indeed, in Lean, → is really just another notation for forall! -/ /- Introduction rule for and ∧ Given a proof of P and a proof of Q get back a proof of (P ∧ Q). -/ axioms (P Q : Prop) #check P #check (P ∧ Q) axioms (p : P) (q : Q) example : P ∧ Q := and.intro p q /- Prive that if arbitrary porpositions P and Q are trie (which is to say that we have a proof of each of them), that the proposition P ∧ Q is also true Proof: The conjecture that P ∧ Q is true is proved by application of the introduction rule for and.) -/ theorem bar : 0 = 0 ∧ 1 = 1 := begin apply and.intro (eq.refl 0) (eq.refl 1) end #check bracket #check and.elim_left bar #check and.elim_right bar theorem and_commutative : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q h, apply and.intro _ _, apply and.elim_right h, apply and.elim_left h, end
8b15866f655e2f325a80d6d7d5219fe01cd55937
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/affine_space/affine_map.lean
878eb6c3a187e0ccd20357257d1bcec7908aa273
[ "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
24,067
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import algebra.add_torsor import data.set.intervals.unordered_interval import linear_algebra.affine_space.basic import linear_algebra.bilinear_map import linear_algebra.pi import linear_algebra.prod import tactic.abel /-! # Affine maps This file defines affine maps. ## Main definitions * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Notations * `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`; * `affine_space V P`: a localized notation for `add_torsor V P` defined in `linear_algebra.affine_space.basic`. ## Implementation notes `out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open_locale affine /-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : V1 →ₗ[k] V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2 instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2]: has_coe_to_fun (P1 →ᵃ[k] P2) (λ _, P1 → P2) := ⟨affine_map.to_fun⟩ namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : V₁ →ᵃ[k] V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, obtain rfl : f = g := funext h, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn := λ f g H, ext $ congr_fun H protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y := congr_arg _ h protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x := h ▸ rfl variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : P1 →ᵃ[k] P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} lemma linear_eq_zero_iff_exists_const (f : P1 →ᵃ[k] P2) : f.linear = 0 ↔ ∃ q, f = const k P1 q := begin refine ⟨λ h, _, λ h, _⟩, { use f (classical.arbitrary P1), ext, rw [coe_const, function.const_apply, ← @vsub_eq_zero_iff_eq V2, ← f.linear_map_vsub, h, linear_map.zero_apply], }, { rcases h with ⟨q, rfl⟩, exact const_linear k P1 q, }, end instance nonempty : nonempty (P1 →ᵃ[k] P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : P1 →ᵃ[k] P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl section has_smul variables {R : Type*} [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2] /-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/ instance : mul_action R (P1 →ᵃ[k] V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _ } @[simp, norm_cast] lemma coe_smul (c : R) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl @[simp] lemma smul_linear (t : R) (f : P1 →ᵃ[k] V2) : (t • f).linear = t • f.linear := rfl instance [distrib_mul_action Rᵐᵒᵖ V2] [is_central_scalar R V2] : is_central_scalar R (P1 →ᵃ[k] V2) := { op_smul_eq_smul := λ r x, ext $ λ _, op_smul_eq_smul _ _ } end has_smul instance : has_zero (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩ } instance : has_add (P1 →ᵃ[k] V2) := { add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩ } instance : has_sub (P1 →ᵃ[k] V2) := { sub := λ f g, ⟨f - g, f.linear - g.linear, λ p v, by simp [sub_add_sub_comm]⟩ } instance : has_neg (P1 →ᵃ[k] V2) := { neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩ } @[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := rfl @[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl @[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl @[simp] lemma sub_linear (f g : P1 →ᵃ[k] V2) : (f - g).linear = f.linear - g.linear := rfl @[simp] lemma neg_linear (f : P1 →ᵃ[k] V2) : (-f).linear = -f.linear := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (P1 →ᵃ[k] V2) := coe_fn_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _) /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps from `P1` to the vector space `V2` corresponding to `P2`. -/ instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_vadd, add_right_comm]⟩, zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p), add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p := rfl /-- `prod.fst` as an `affine_map`. -/ def fst : (P1 × P2) →ᵃ[k] P1 := { to_fun := prod.fst, linear := linear_map.fst k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl @[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl /-- `prod.snd` as an `affine_map`. -/ def snd : (P1 × P2) →ᵃ[k] P2 := { to_fun := prod.snd, linear := linear_map.snd k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl @[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : P1 →ᵃ[k] P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (P1 →ᵃ[k] P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl /-- `affine_map.linear` on endomorphisms is a `monoid_hom`. -/ @[simps] def linear_hom : (P1 →ᵃ[k] P1) →* (V1 →ₗ[k] V1) := { to_fun := linear, map_one' := rfl, map_mul' := λ _ _, rfl } include V2 @[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) : function.injective f.linear ↔ function.injective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_injective, equiv.injective_comp], end @[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) : function.surjective f.linear ↔ function.surjective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_surjective, equiv.surjective_comp], end lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) : (f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) := begin ext v, simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left, ← f.linear_map_vsub], split, { rintros ⟨x, hx, y, hy, hv⟩, exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, }, { rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩, exact ⟨x, hx, y, hy, rfl⟩, }, end omit V2 /-! ### Definition of `affine_map.line_map` and lemmas about it -/ /-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/ def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 := ((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀ lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by simp [line_map_apply_module', smul_sub, sub_smul]; abel omit V1 lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a := rfl lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b := line_map_apply_module a b c include V1 lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) : line_map p (v +ᵥ p) c = c • v +ᵥ p := by rw [line_map_apply, vadd_vsub] @[simp] lemma line_map_linear (p₀ p₁ : P1) : (line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) := add_zero _ lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply] @[simp] lemma line_map_same (p : P1) : line_map p p = const k k p := ext $ line_map_same_apply p @[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ := by simp [line_map_apply] @[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ := by simp [line_map_apply] include V2 @[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) : f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c := by simp [line_map_apply] @[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) : f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) := ext $ f.apply_line_map p₀ p₁ @[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c := fst.apply_line_map p₀ p₁ c @[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c := snd.apply_line_map p₀ p₁ c omit V2 lemma line_map_symm (p₀ p₁ : P1) : line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) := by { rw [comp_line_map], simp } lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c := by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] } @[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) := vadd_vsub _ _ @[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) : p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) := by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev] @[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by rw [← line_map_apply_one_sub, line_map_vsub_left] @[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) : p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by rw [← line_map_apply_one_sub, left_vsub_line_map] lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) : line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c := ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) : line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c := -- Why Lean fails to find this instance without a hint? by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] omit V1 lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k) (a b : k) : f '' set.interval a b = set.interval (f a) (f b) := begin have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0), { ext x, change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0, rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd], simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] }, rw [this, set.image_comp], simp only [set.image_add_const_interval, set.image_mul_const_interval] end section variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)] [Π i, module k (V i)] [Π i, add_torsor (V i) (P i)] include V /-- Evaluation at a point as an affine map. -/ def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i := { to_fun := λ f, f i, linear := @linear_map.proj k ι _ V _ _ i, map_vadd' := λ p v, rfl } @[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl @[simp] lemma proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) : line_map f g c i = line_map (f i) (g i) c := (proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c end end affine_map namespace affine_map variables {R k V1 P1 V2 : Type*} section ring variables [ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2] variables [module k V1] [module k V2] include V1 section distrib_mul_action variables [monoid R] [distrib_mul_action R V2] [smul_comm_class k R V2] /-- The space of affine maps to a module inherits an `R`-action from the action on its codomain. -/ instance : distrib_mul_action R (P1 →ᵃ[k] V2) := { smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _ } end distrib_mul_action section module variables [semiring R] [module R V2] [smul_comm_class k R V2] /-- The space of affine maps taking values in an `R`-module is an `R`-module. -/ instance : module R (P1 →ᵃ[k] V2) := { smul := (•), add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _, .. affine_map.distrib_mul_action } variables (R) /-- The space of affine maps between two modules is linearly equivalent to the product of the domain with the space of linear maps, by taking the value of the affine map at `(0 : V1)` and the linear part. See note [bundled maps over different rings]-/ @[simps] def to_const_prod_linear_map : (V1 →ᵃ[k] V2) ≃ₗ[R] V2 × (V1 →ₗ[k] V2) := { to_fun := λ f, ⟨f 0, f.linear⟩, inv_fun := λ p, p.2.to_affine_map + const k V1 p.1, left_inv := λ f, by { ext, rw f.decomp, simp, }, right_inv := by { rintros ⟨v, f⟩, ext; simp, }, map_add' := by simp, map_smul' := by simp, } end module end ring section comm_ring variables [comm_ring k] [add_comm_group V1] [affine_space V1 P1] [add_comm_group V2] variables [module k V1] [module k V2] include V1 /-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r lemma homothety_mul_apply (c : P1) (r₁ r₂ : k) (p : P1) : homothety c (r₁ * r₂) p = homothety c r₁ (homothety c r₂ p) := by simp [homothety_apply, mul_smul] lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := ext $ homothety_mul_apply c r₁ r₂ @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_vadd] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : k →ᵃ[k] _) = homothety c := rfl end comm_ring end affine_map section variables {𝕜 E F : Type*} [ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {x y : E} {a b : 𝕜} {f : E →ᵃ[𝕜] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := by { simp only [convex.combo_eq_smul_sub_add h, ←vsub_eq_sub], exact f.apply_line_map _ _ _ } end
07991f9c895f38914321fa3a183d0895bec88abe
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/trigonometric/arctan.lean
10ce7f424c9fcaaa5bc4ffd2455bfa5c9aeb4b22
[ "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
7,968
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, Benjamin Davidson -/ import analysis.special_functions.trigonometric.complex /-! # The `arctan` function. Inequalities, derivatives, and `real.tan` as a `local_homeomorph` between `(-(π / 2), π / 2)` and the whole line. -/ noncomputable theory namespace real open set filter open_locale topology real lemma tan_add {x y : ℝ} (h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2) ∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y = (2 * l + 1) * π / 2)) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := by simpa only [← complex.of_real_inj, complex.of_real_sub, complex.of_real_add, complex.of_real_div, complex.of_real_mul, complex.of_real_tan] using @complex.tan_add (x:ℂ) (y:ℂ) (by convert h; norm_cast) lemma tan_add' {x y : ℝ} (h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := tan_add (or.inl h) lemma tan_two_mul {x:ℝ} : tan (2 * x) = 2 * tan x / (1 - tan x ^ 2) := by simpa only [← complex.of_real_inj, complex.of_real_sub, complex.of_real_div, complex.of_real_pow, complex.of_real_mul, complex.of_real_tan, complex.of_real_bit0, complex.of_real_one] using complex.tan_two_mul lemma tan_ne_zero_iff {θ : ℝ} : tan θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π / 2 := by rw [← complex.of_real_ne_zero, complex.of_real_tan, complex.tan_ne_zero_iff]; norm_cast lemma tan_eq_zero_iff {θ : ℝ} : tan θ = 0 ↔ ∃ k : ℤ, θ = k * π / 2 := by rw [← not_iff_not, not_exists, ← ne, tan_ne_zero_iff] lemma tan_int_mul_pi_div_two (n : ℤ) : tan (n * π/2) = 0 := tan_eq_zero_iff.mpr (by use n) lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} := begin suffices : continuous_on (λ x, sin x / cos x) {x | cos x ≠ 0}, { have h_eq : (λ x, sin x / cos x) = tan, by {ext1 x, rw tan_eq_sin_div_cos, }, rwa h_eq at this, }, exact continuous_on_sin.div continuous_on_cos (λ x, id), end @[continuity] lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) := continuous_on_iff_continuous_restrict.1 continuous_on_tan lemma continuous_on_tan_Ioo : continuous_on tan (Ioo (-(π/2)) (π/2)) := begin refine continuous_on.mono continuous_on_tan (λ x, _), simp only [and_imp, mem_Ioo, mem_set_of_eq, ne.def], rw cos_eq_zero_iff, rintros hx_gt hx_lt ⟨r, hxr_eq⟩, cases le_or_lt 0 r, { rw lt_iff_not_ge at hx_lt, refine hx_lt _, rw [hxr_eq, ← one_mul (π / 2), mul_div_assoc, ge_iff_le, mul_le_mul_right (half_pos pi_pos)], simp [h], }, { rw lt_iff_not_ge at hx_gt, refine hx_gt _, rw [hxr_eq, ← one_mul (π / 2), mul_div_assoc, ge_iff_le, neg_mul_eq_neg_mul, mul_le_mul_right (half_pos pi_pos)], have hr_le : r ≤ -1, by rwa [int.lt_iff_add_one_le, ← le_neg_iff_add_nonpos_right] at h, rw [← le_sub_iff_add_le, mul_comm, ← le_div_iff], { norm_num, rw [← int.cast_one, ← int.cast_neg], norm_cast, exact hr_le, }, { exact zero_lt_two, }, }, end lemma surj_on_tan : surj_on tan (Ioo (-(π / 2)) (π / 2)) univ := have _ := neg_lt_self pi_div_two_pos, continuous_on_tan_Ioo.surj_on_of_tendsto (nonempty_Ioo.2 this) (by simp [tendsto_tan_neg_pi_div_two, this]) (by simp [tendsto_tan_pi_div_two, this]) lemma tan_surjective : function.surjective tan := λ x, surj_on_tan.subset_range trivial lemma image_tan_Ioo : tan '' (Ioo (-(π / 2)) (π / 2)) = univ := univ_subset_iff.1 surj_on_tan /-- `real.tan` as an `order_iso` between `(-(π / 2), π / 2)` and `ℝ`. -/ def tan_order_iso : Ioo (-(π / 2)) (π / 2) ≃o ℝ := (strict_mono_on_tan.order_iso _ _).trans $ (order_iso.set_congr _ _ image_tan_Ioo).trans order_iso.set.univ /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ @[pp_nodot] noncomputable def arctan (x : ℝ) : ℝ := tan_order_iso.symm x @[simp] lemma tan_arctan (x : ℝ) : tan (arctan x) = x := tan_order_iso.apply_symm_apply x lemma arctan_mem_Ioo (x : ℝ) : arctan x ∈ Ioo (-(π / 2)) (π / 2) := subtype.coe_prop _ @[simp] lemma range_arctan : range arctan = Ioo (-(π / 2)) (π / 2) := ((equiv_like.surjective _).range_comp _).trans subtype.range_coe lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := subtype.ext_iff.1 $ tan_order_iso.symm_apply_apply ⟨x, hx₁, hx₂⟩ lemma cos_arctan_pos (x : ℝ) : 0 < cos (arctan x) := cos_pos_of_mem_Ioo $ arctan_mem_Ioo x lemma cos_sq_arctan (x : ℝ) : cos (arctan x) ^ 2 = 1 / (1 + x ^ 2) := by rw [one_div, ← inv_one_add_tan_sq (cos_arctan_pos x).ne', tan_arctan] lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := by rw [← tan_div_sqrt_one_add_tan_sq (cos_arctan_pos x), tan_arctan] lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := by rw [one_div, ← inv_sqrt_one_add_tan_sq (cos_arctan_pos x), tan_arctan] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := (arctan_mem_Ioo x).2 lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := (arctan_mem_Ioo x).1 lemma arctan_eq_arcsin (x : ℝ) : arctan x = arcsin (x / sqrt (1 + x ^ 2)) := eq.symm $ arcsin_eq_of_sin_eq (sin_arctan x) (mem_Icc_of_Ioo $ arctan_mem_Ioo x) lemma arcsin_eq_arctan {x : ℝ} (h : x ∈ Ioo (-(1:ℝ)) 1) : arcsin x = arctan (x / sqrt (1 - x ^ 2)) := begin rw [arctan_eq_arcsin, div_pow, sq_sqrt, one_add_div, div_div, ← sqrt_mul, mul_div_cancel', sub_add_cancel, sqrt_one, div_one]; nlinarith [h.1, h.2], end @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan_eq_arcsin] lemma arctan_eq_of_tan_eq {x y : ℝ} (h : tan x = y) (hx : x ∈ Ioo (-(π / 2)) (π / 2)) : arctan y = x := inj_on_tan (arctan_mem_Ioo _) hx (by rw [tan_arctan, h]) @[simp] lemma arctan_one : arctan 1 = π / 4 := arctan_eq_of_tan_eq tan_pi_div_four $ by split; linarith [pi_pos] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan_eq_arcsin, neg_div] lemma arctan_eq_arccos {x : ℝ} (h : 0 ≤ x) : arctan x = arccos ((sqrt (1 + x ^ 2))⁻¹) := begin rw [arctan_eq_arcsin, arccos_eq_arcsin], swap, { exact inv_nonneg.2 (sqrt_nonneg _) }, congr' 1, rw [←sqrt_inv, sq_sqrt, ←one_div, one_sub_div, add_sub_cancel', sqrt_div, sqrt_sq h], all_goals { positivity } end -- The junk values for `arccos` and `sqrt` make this true even for `1 < x`. lemma arccos_eq_arctan {x : ℝ} (h : 0 < x) : arccos x = arctan (sqrt (1 - x ^ 2) / x) := begin rw [arccos, eq_comm], refine arctan_eq_of_tan_eq _ ⟨_, _⟩, { rw [tan_pi_div_two_sub, tan_arcsin, inv_div] }, { linarith only [arcsin_le_pi_div_two x, pi_pos] }, { linarith only [arcsin_pos.2 h] } end @[continuity] lemma continuous_arctan : continuous arctan := continuous_subtype_coe.comp tan_order_iso.to_homeomorph.continuous_inv_fun lemma continuous_at_arctan {x : ℝ} : continuous_at arctan x := continuous_arctan.continuous_at /-- `real.tan` as a `local_homeomorph` between `(-(π / 2), π / 2)` and the whole line. -/ def tan_local_homeomorph : local_homeomorph ℝ ℝ := { to_fun := tan, inv_fun := arctan, source := Ioo (-(π / 2)) (π / 2), target := univ, map_source' := maps_to_univ _ _, map_target' := λ y hy, arctan_mem_Ioo y, left_inv' := λ x hx, arctan_tan hx.1 hx.2, right_inv' := λ y hy, tan_arctan y, open_source := is_open_Ioo, open_target := is_open_univ, continuous_to_fun := continuous_on_tan_Ioo, continuous_inv_fun := continuous_arctan.continuous_on } @[simp] lemma coe_tan_local_homeomorph : ⇑tan_local_homeomorph = tan := rfl @[simp] lemma coe_tan_local_homeomorph_symm : ⇑tan_local_homeomorph.symm = arctan := rfl end real
75bd964a78bf8bc6737d92984e2628f8510e03ed
367134ba5a65885e863bdc4507601606690974c1
/src/group_theory/perm/subgroup.lean
ef0d70cae526760db29b4db65c8ddb704815f9fa
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,617
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.perm.basic import data.fintype.basic import group_theory.subgroup /-! # Lemmas about subgroups within the permutations (self-equivalences) of a type `α` This file provides extra lemmas about some `subgroup`s that exist within `equiv.perm α`. `group_theory.subgroup` depends on `group_theory.perm.basic`, so these need to be in a separate file. It also provides decidable instances on membership in these subgroups, since `monoid_hom.decidable_mem_range` cannot be inferred without the help of a lambda. The presence of these instances induces a `fintype` instance on the `quotient_group.quotient` of these subgroups. -/ namespace equiv namespace perm universes u instance sum_congr_hom.decidable_mem_range {α β : Type*} [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (λ x, x ∈ (sum_congr_hom α β).range) := λ x, infer_instance @[simp] lemma sum_congr_hom.card_range {α β : Type*} [fintype (sum_congr_hom α β).range] [fintype (perm α × perm β)] : fintype.card (sum_congr_hom α β).range = fintype.card (perm α × perm β) := fintype.card_eq.mpr ⟨(set.range (sum_congr_hom α β) sum_congr_hom_injective).symm⟩ instance sigma_congr_right_hom.decidable_mem_range {α : Type*} {β : α → Type*} [decidable_eq α] [∀ a, decidable_eq (β a)] [fintype α] [∀ a, fintype (β a)] : decidable_pred (λ x, x ∈ (sigma_congr_right_hom β).range) := λ x, infer_instance @[simp] lemma sigma_congr_right_hom.card_range {α : Type*} {β : α → Type*} [fintype (sigma_congr_right_hom β).range] [fintype (Π a, perm (β a))] : fintype.card (sigma_congr_right_hom β).range = fintype.card (Π a, perm (β a)) := fintype.card_eq.mpr ⟨(set.range (sigma_congr_right_hom β) sigma_congr_right_hom_injective).symm⟩ instance subtype_congr_hom.decidable_mem_range {α : Type*} (p : α → Prop) [decidable_pred p] [fintype (perm {a // p a} × perm {a // ¬ p a})] [decidable_eq (perm α)] : decidable_pred (λ x, x ∈ (subtype_congr_hom p).range) := λ x, infer_instance @[simp] lemma subtype_congr_hom.card_range {α : Type*} (p : α → Prop) [decidable_pred p] [fintype (subtype_congr_hom p).range] [fintype (perm {a // p a} × perm {a // ¬ p a})] : fintype.card (subtype_congr_hom p).range = fintype.card (perm {a // p a} × perm {a // ¬ p a}) := fintype.card_eq.mpr ⟨(set.range (subtype_congr_hom p) (subtype_congr_hom_injective p)).symm⟩ end perm end equiv
672cbab43759b09537d9f8dea2071d689fcccc70
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/decorrelateExists.lean
8869aaec24fbc9c112f3e523c13efce8f1e08c8d
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,626
lean
import ..sql import ..tactics import ..u_semiring import ..cosette_lemmas import ..extra_constants import ..TDP import ..cosette_tactics open Expr open Proj open Pred open SQL variable i : const datatypes.int theorem rule : forall (Γ scm_emp : Schema) (rel_emp : relation scm_emp) (emp_empno : Column datatypes.int scm_emp) (emp_ename : Column datatypes.int scm_emp) (emp_job : Column datatypes.int scm_emp) (emp_mgr : Column datatypes.int scm_emp) (emp_hiredate : Column datatypes.int scm_emp) (emp_comm : Column datatypes.int scm_emp) (emp_sal : Column datatypes.int scm_emp) (emp_deptno : Column datatypes.int scm_emp) (emp_slacker : Column datatypes.int scm_emp), denoteSQL (SELECT * FROM1 (table rel_emp WHERE EXISTS (SELECT * FROM1 table rel_emp WHERE (equal (uvariable (left⋅right⋅emp_deptno)) (uvariable (right⋅emp_deptno))))) : SQL Γ _) = denoteSQL (SELECT1 (right⋅left⋅star) FROM1 (product (table rel_emp) (DISTINCT (SELECT1 (combine (right⋅emp_deptno) (e2p (constantExpr i))) FROM1 table rel_emp)) WHERE (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left)))) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, print_size, apply ueq_symm, -- remove_dup_sigs_lhs, sorry end
99ae0c5793f222d08a205070be0ef24af52006b1
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love11_logical_foundations_of_mathematics_exercise_solution.lean
474f39fb2c8d19969f14b1bce5fd146e5106d450
[]
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
2,860
lean
import .love11_logical_foundations_of_mathematics_demo /- # LoVe Exercise 11: Logical Foundations of Mathematics -/ set_option pp.beta true set_option pp.generalized_field_notation false 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 | [] [] := by simp [list.add] | (x :: xs) (y :: ys) := begin simp [list.add, length], intro h, rw list.length_add xs ys h end | [] (y :: ys) := begin intro h, cases' h end | (x :: xs) [] := begin intro h, cases' h end /- 1.2. Define componentwise addition on vectors using `list.add` and `list.length_add`. -/ def vector.add {n : ℕ} : vector ℤ n → vector ℤ n → vector ℤ n | u v := subtype.mk (list.add (subtype.val u) (subtype.val v)) begin rw list.length_add, { exact subtype.property u }, { rw subtype.property u, rw subtype.property v } end /- 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 | [] [] := by refl | (x :: xs) (y :: ys) := by simp [list.add, add_comm]; exact list.add.comm xs ys | [] (y :: ys) := by refl | (x :: xs) [] := by refl lemma vector.add.comm {n : ℕ} (x y : vector ℤ n) : vector.add x y = vector.add y x := begin apply subtype.eq, simp [vector.add], apply list.add.comm end /- ## 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 := quotient.lift (λpn : ℕ × ℕ, ⟦(prod.snd pn, prod.fst pn)⟧) begin intros a a' ha, cases' a with p n, cases' a' with p' n', apply quotient.sound, simp at *, rw int.rel_iff at *, cc end /- 2.2. Prove the following lemmas about negation. -/ lemma int.neg_eq (p n : ℕ) : int.neg ⟦(p, n)⟧ = ⟦(n, p)⟧ := by refl lemma int.neg_neg (a : int) : int.neg (int.neg a) = a := begin apply quotient.induction_on a, intro a, cases' a, simp [int.neg_eq] end end LoVe
ddac99be788ef3a6b8fa4e0de98736c46d6e44b4
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/linear_algebra/direct_sum/tensor_product.lean
060e60bace54a08435cfdf293d418c69390da1f1
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
2,262
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import linear_algebra.tensor_product import linear_algebra.direct_sum_module section ring namespace tensor_product open_locale tensor_product open linear_map variables (R : Type*) [comm_ring R] variables (ι₁ : Type*) (ι₂ : Type*) variables [decidable_eq ι₁] [decidable_eq ι₂] variables (M₁ : ι₁ → Type*) (M₂ : ι₂ → Type*) variables [Π i₁, add_comm_group (M₁ i₁)] [Π i₂, add_comm_group (M₂ i₂)] variables [Π i₁, module R (M₁ i₁)] [Π i₂, module R (M₂ i₂)] /-- The linear equivalence `(⊕ i₁, M₁ i₁) ⊗ (⊕ i₂, M₂ i₂) ≃ (⊕ i₁, ⊕ i₂, M₁ i₁ ⊗ M₂ i₂)`, i.e. "tensor product distributes over direct sum". -/ def direct_sum : direct_sum ι₁ M₁ ⊗[R] direct_sum ι₂ M₂ ≃ₗ[R] direct_sum (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) := begin refine linear_equiv.of_linear (lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂, flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂)) (direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _)) (linear_map.ext $ direct_sum.to_module.ext _ $ λ i, mk_compr₂_inj $ linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _) (mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext _ $ λ i₁, linear_map.ext $ λ x₁, linear_map.ext $ direct_sum.to_module.ext _ $ λ i₂, linear_map.ext $ λ x₂, _), repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|> rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|> rw curry_apply }, cases i; refl end @[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) : direct_sum R ι₁ ι₂ M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) = direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) := by simp [direct_sum] end tensor_product end ring
b00461034c4e7b0661b5eb00c8dc540aa7dfdc38
42610cc2e5db9c90269470365e6056df0122eaa0
/library/theories/group_theory/basic.lean
b1bfe3d165f8c7a0dc7a52b06c16fd9600731d3d
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
39,831
lean
/- Copyright (c) 2016 Andrew Zipperer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Zipperer, Jeremy Avigad Basic group theory: subgroups, homomorphisms on a set, homomorphic images, cosets, normal cosets and the normalizer, the kernel of a homomorphism, the centralizer, etc. For notation a * S and S * a for cosets, open the namespace "coset_notation". For notation a^b and S^a, open the namespace "conj_notation". TODO: homomorphisms on sets should be refactored and moved to algebra. -/ import data.set algebra.homomorphism theories.topology.basic theories.move open eq.ops set function namespace group_theory variables {A B C : Type} /- subgroups -/ structure is_one_closed [class] [has_one A] (S : set A) : Prop := (one_mem : one ∈ S) proposition one_mem [has_one A] {S : set A} [is_one_closed S] : 1 ∈ S := is_one_closed.one_mem _ S structure is_mul_closed [class] [has_mul A] (S : set A) : Prop := (mul_mem : ∀₀ a ∈ S, ∀₀ b ∈ S, a * b ∈ S) proposition mul_mem [has_mul A] {S : set A} [is_mul_closed S] {a b : A} (aS : a ∈ S) (bS : b ∈ S) : a * b ∈ S := is_mul_closed.mul_mem _ S aS bS structure is_inv_closed [class] [has_inv A] (S : set A) : Prop := (inv_mem : ∀₀ a ∈ S, a⁻¹ ∈ S) proposition inv_mem [has_inv A] {S : set A} [is_inv_closed S] {a : A} (aS : a ∈ S) : a⁻¹ ∈ S := is_inv_closed.inv_mem _ S aS structure is_subgroup [class] [group A] (S : set A) extends is_one_closed S, is_mul_closed S, is_inv_closed S : Prop section groupA variable [group A] proposition mem_of_inv_mem {a : A} {S : set A} [is_subgroup S] (H : a⁻¹ ∈ S) : a ∈ S := have (a⁻¹)⁻¹ ∈ S, from inv_mem H, by rewrite inv_inv at this; apply this proposition inv_mem_iff (a : A) (S : set A) [is_subgroup S] : a⁻¹ ∈ S ↔ a ∈ S := iff.intro mem_of_inv_mem inv_mem proposition is_subgroup_univ [instance] : is_subgroup (@univ A) := ⦃ is_subgroup, one_mem := trivial, mul_mem := λ a au b bu, trivial, inv_mem := λ a au, trivial ⦄ proposition is_subgroup_inter [instance] (G H : set A) [is_subgroup G] [is_subgroup H] : is_subgroup (G ∩ H) := ⦃ is_subgroup, one_mem := and.intro one_mem one_mem, mul_mem := λ a ai b bi, and.intro (mul_mem (and.left ai) (and.left bi)) (mul_mem (and.right ai) (and.right bi)), inv_mem := λ a ai, and.intro (inv_mem (and.left ai)) (inv_mem (and.right ai)) ⦄ end groupA /- homomorphisms on sets -/ section has_mulABC variables [has_mul A] [has_mul B] [has_mul C] -- in group theory, we can use is_hom for is_mul_hom abbreviation is_hom := @is_mul_hom definition is_hom_on [class] (f : A → B) (S : set A) : Prop := ∀₀ a₁ ∈ S, ∀₀ a₂ ∈ S, f (a₁ * a₂) = f a₁ * f a₂ proposition hom_on_mul (f : A → B) {S : set A} [H : is_hom_on f S] {a₁ a₂ : A} (a₁S : a₁ ∈ S) (a₂S : a₂ ∈ S) : f (a₁ * a₂) = (f a₁) * (f a₂) := H a₁S a₂S proposition is_hom_on_of_is_hom (f : A → B) (S : set A) [H : is_hom f] : is_hom_on f S := forallb_of_forall₂ S S (hom_mul f) proposition is_hom_of_is_hom_on_univ (f : A → B) [H : is_hom_on f univ] : is_hom f := is_mul_hom.mk (forall_of_forallb_univ₂ H) proposition is_hom_on_univ_iff (f : A → B) : is_hom_on f univ ↔ is_hom f := iff.intro (λH, is_hom_of_is_hom_on_univ f) (λ H, is_hom_on_of_is_hom f univ) proposition is_hom_on_of_subset (f : A → B) {S T : set A} (ssubt : S ⊆ T) [H : is_hom_on f T] : is_hom_on f S := forallb_of_subset₂ ssubt ssubt H proposition is_hom_on_id (S : set A) : is_hom_on id S := have H : is_hom (@id A), from is_mul_hom_id, is_hom_on_of_is_hom id S proposition is_hom_on_comp {S : set A} {T : set B} {g : B → C} {f : A → B} (H₁ : is_hom_on f S) (H₂ : is_hom_on g T) (H₃ : maps_to f S T) : is_hom_on (g ∘ f) S := take a₁, assume a₁S, take a₂, assume a₂S, have f a₁ ∈ T, from H₃ a₁S, have f a₂ ∈ T, from H₃ a₂S, show g (f (a₁ * a₂)) = g (f a₁) * g (f a₂), by rewrite [H₁ a₁S a₂S, H₂ `f a₁ ∈ T` `f a₂ ∈ T`] end has_mulABC section groupAB variables [group A] [group B] proposition hom_on_one (f : A → B) (G : set A) [is_subgroup G] [H : is_hom_on f G] : f 1 = 1 := have f 1 * f 1 = f 1 * 1, by rewrite [-H one_mem one_mem, *mul_one], eq_of_mul_eq_mul_left' this proposition hom_on_inv (f : A → B) {G : set A} [is_subgroup G] [H : is_hom_on f G] {a : A} (aG : a ∈ G) : f a⁻¹ = (f a)⁻¹ := have f a⁻¹ * f a = 1, by rewrite [-H (inv_mem aG) aG, mul.left_inv, hom_on_one f G], eq_inv_of_mul_eq_one this proposition is_subgroup_image [instance] (f : A → B) (G : set A) [is_subgroup G] [is_hom_on f G] : is_subgroup (f ' G) := ⦃ is_subgroup, one_mem := mem_image one_mem (hom_on_one f G), mul_mem := λ a afG b bfG, obtain c (cG : c ∈ G)(Hc : f c = a), from afG, obtain d (dG : d ∈ G)(Hd : f d = b), from bfG, show a * b ∈ f ' G, from mem_image (mul_mem cG dG) (by rewrite [hom_on_mul f cG dG, Hc, Hd]), inv_mem := λ a afG, obtain c (cG : c ∈ G)(Hc : f c = a), from afG, show a⁻¹ ∈ f ' G, from mem_image (inv_mem cG) (by rewrite [hom_on_inv f cG, Hc]) ⦄ end groupAB /- cosets -/ definition lcoset [has_mul A] (a : A) (N : set A) : set A := (mul a) 'N definition rcoset [has_mul A] (N : set A) (a : A) : set A := (mul^~ a) 'N -- overload multiplication namespace coset_notation infix * := lcoset infix * := rcoset end coset_notation open coset_notation section has_mulA variable [has_mul A] proposition mul_mem_lcoset {S : set A} {x : A} (a : A) (xS : x ∈ S) : a * x ∈ a * S := mem_image_of_mem (mul a) xS proposition mul_mem_rcoset [has_mul A] {S : set A} {x : A} (xS : x ∈ S) (a : A) : x * a ∈ S * a := mem_image_of_mem (mul^~ a) xS definition lcoset_equiv (S : set A) (a b : A) : Prop := a * S = b * S proposition equivalence_lcoset_equiv (S : set A) : equivalence (lcoset_equiv S) := mk_equivalence (lcoset_equiv S) (λ a, rfl) (λ a b, !eq.symm) (λ a b c, !eq.trans) proposition lcoset_subset_lcoset {S T : set A} (a : A) (H : S ⊆ T) : a * S ⊆ a * T := image_subset _ H proposition rcoset_subset_rcoset {S T : set A} (H : S ⊆ T) (a : A) : S * a ⊆ T * a := image_subset _ H proposition image_lcoset_of_is_hom_on {B : Type} [has_mul B] {f : A → B} {S : set A} {a : A} {G : set A} (SsubG : S ⊆ G) (aG : a ∈ G) [is_hom_on f G] : f ' (a * S) = f a * f ' S := ext (take x, iff.intro (assume fas : x ∈ f ' (a * S), obtain t [s (sS : s ∈ S) (seq : a * s = t)] (teq : f t = x), from fas, have x = f a * f s, by rewrite [-teq, -seq, hom_on_mul f aG (SsubG sS)], show x ∈ f a * f ' S, by rewrite this; apply mul_mem_lcoset _ (mem_image_of_mem _ sS)) (assume fafs : x ∈ f a * f ' S, obtain t [s (sS : s ∈ S) (seq : f s = t)] (teq : f a * t = x), from fafs, have x = f (a * s), by rewrite [-teq, -seq, hom_on_mul f aG (SsubG sS)], show x ∈ f ' (a * S), by rewrite this; exact mem_image_of_mem _ (mul_mem_lcoset _ sS))) proposition image_rcoset_of_is_hom_on {B : Type} [has_mul B] {f : A → B} {S : set A} {a : A} {G : set A} (SsubG : S ⊆ G) (aG : a ∈ G) [is_hom_on f G] : f ' (S * a) = f ' S * f a := ext (take x, iff.intro (assume fas : x ∈ f ' (S * a), obtain t [s (sS : s ∈ S) (seq : s * a = t)] (teq : f t = x), from fas, have x = f s * f a, by rewrite [-teq, -seq, hom_on_mul f (SsubG sS) aG], show x ∈ f ' S * f a, by rewrite this; exact mul_mem_rcoset (mem_image_of_mem _ sS) _) (assume fafs : x ∈ f ' S * f a, obtain t [s (sS : s ∈ S) (seq : f s = t)] (teq : t * f a = x), from fafs, have x = f (s * a), by rewrite [-teq, -seq, hom_on_mul f (SsubG sS) aG], show x ∈ f ' (S * a), by rewrite this; exact mem_image_of_mem _ (mul_mem_rcoset sS _))) proposition image_lcoset_of_is_hom {B : Type} [has_mul B] (f : A → B) (a : A) (S : set A) [is_hom f] : f ' (a * S) = f a * f ' S := have is_hom_on f univ, from is_hom_on_of_is_hom f univ, image_lcoset_of_is_hom_on (subset_univ S) !mem_univ proposition image_rcoset_of_is_hom {B : Type} [has_mul B] (f : A → B) (S : set A) (a : A) [is_hom f] : f ' (S * a) = f ' S * f a := have is_hom_on f univ, from is_hom_on_of_is_hom f univ, image_rcoset_of_is_hom_on (subset_univ S) !mem_univ end has_mulA section semigroupA variable [semigroup A] proposition rcoset_rcoset (S : set A) (a b : A) : S * a * b = S * (a * b) := have H : (mul^~ b) ∘ (mul^~ a) = mul^~ (a * b), from funext (take x, !mul.assoc), calc S * a * b = ((mul^~ b) ∘ (mul^~ a)) 'S : image_comp ... = S * (a * b) : by rewrite [↑rcoset, H] proposition lcoset_lcoset (S : set A) (a b : A) : a * (b * S) = (a * b) * S := have H : (mul a) ∘ (mul b) = mul (a * b), from funext (take x, !mul.assoc⁻¹), calc a * (b * S) = ((mul a) ∘ (mul b)) 'S : image_comp ... = (a * b) * S : by rewrite [↑lcoset, H] proposition lcoset_rcoset [semigroup A] (S : set A) (a b : A) : a * S * b = a * (S * b) := have H : (mul^~ b) ∘ (mul a) = (mul a) ∘ (mul^~ b), from funext (take x, !mul.assoc), calc a * S * b = ((mul^~ b) ∘ (mul a)) 'S : image_comp ... = ((mul a) ∘ (mul^~ b)) 'S : H ... = a * (S * b) : image_comp end semigroupA section monoidA variable [monoid A] proposition one_lcoset (S : set A) : 1 * S = S := ext (take x, iff.intro (suppose x ∈ 1 * S, obtain s (sS : s ∈ S) (eqx : 1 * s = x), from this, show x ∈ S, by rewrite [-eqx, one_mul]; apply sS) (suppose x ∈ S, have 1 * x ∈ 1 * S, from mem_image_of_mem (mul 1) this, show x ∈ 1 * S, by rewrite one_mul at this; apply this)) proposition rcoset_one (S : set A) : S * 1 = S := ext (take x, iff.intro (suppose x ∈ S * 1, obtain s (sS : s ∈ S) (eqx : s * 1 = x), from this, show x ∈ S, by rewrite [-eqx, mul_one]; apply sS) (suppose x ∈ S, have x * 1 ∈ S * 1, from mem_image_of_mem (mul^~ 1) this, show x ∈ S * 1, by rewrite mul_one at this; apply this)) end monoidA section groupA variable [group A] proposition lcoset_inv_lcoset (a : A) (S : set A) : a * (a⁻¹ * S) = S := by rewrite [lcoset_lcoset, mul.right_inv, one_lcoset] proposition inv_lcoset_lcoset (a : A) (S : set A) : a⁻¹ * (a * S) = S := by rewrite [lcoset_lcoset, mul.left_inv, one_lcoset] proposition rcoset_inv_rcoset (S : set A) (a : A) : (S * a⁻¹) * a = S := by rewrite [rcoset_rcoset, mul.left_inv, rcoset_one] proposition rcoset_rcoset_inv (S : set A) (a : A) : (S * a) * a⁻¹ = S := by rewrite [rcoset_rcoset, mul.right_inv, rcoset_one] proposition eq_of_lcoset_eq_lcoset {a : A} {S T : set A} (H : a * S = a * T) : S = T := by rewrite [-inv_lcoset_lcoset a S, -inv_lcoset_lcoset a T, H] proposition eq_of_rcoset_eq_rcoset {a : A} {S T : set A} (H : S * a = T * a) : S = T := by rewrite [-rcoset_rcoset_inv S a, -rcoset_rcoset_inv T a, H] proposition mem_of_mul_mem_lcoset {a b : A} {S : set A} (abaS : a * b ∈ a * S) : b ∈ S := have a⁻¹ * (a * b) ∈ a⁻¹ * (a * S), from mul_mem_lcoset _ abaS, by rewrite [inv_mul_cancel_left at this, inv_lcoset_lcoset at this]; apply this proposition mul_mem_lcoset_iff (a b : A) (S : set A) : a * b ∈ a * S ↔ b ∈ S := iff.intro !mem_of_mul_mem_lcoset !mul_mem_lcoset proposition mem_of_mul_mem_rcoset {a b : A} {S : set A} (abSb : a * b ∈ S * b) : a ∈ S := have (a * b) * b⁻¹ ∈ (S * b) * b⁻¹, from mul_mem_rcoset abSb _, by rewrite [mul_inv_cancel_right at this, rcoset_rcoset_inv at this]; apply this proposition mul_mem_rcoset_iff (a b : A) (S : set A) : a * b ∈ S * b ↔ a ∈ S := iff.intro !mem_of_mul_mem_rcoset (λ H, mul_mem_rcoset H _) proposition inv_mul_mem_of_mem_lcoset {a b : A} {S : set A} (abS : a ∈ b * S) : b⁻¹ * a ∈ S := have b⁻¹ * a ∈ b⁻¹ * (b * S), from mul_mem_lcoset b⁻¹ abS, by rewrite inv_lcoset_lcoset at this; apply this proposition mem_lcoset_of_inv_mul_mem {a b : A} {S : set A} (H : b⁻¹ * a ∈ S) : a ∈ b * S := have b * (b⁻¹ * a) ∈ b * S, from mul_mem_lcoset b H, by rewrite mul_inv_cancel_left at this; apply this proposition mem_lcoset_iff (a b : A) (S : set A) : a ∈ b * S ↔ b⁻¹ * a ∈ S := iff.intro inv_mul_mem_of_mem_lcoset mem_lcoset_of_inv_mul_mem proposition mul_inv_mem_of_mem_rcoset {a b : A} {S : set A} (aSb : a ∈ S * b) : a * b⁻¹ ∈ S := have a * b⁻¹ ∈ (S * b) * b⁻¹, from mul_mem_rcoset aSb b⁻¹, by rewrite rcoset_rcoset_inv at this; apply this proposition mem_rcoset_of_mul_inv_mem {a b : A} {S : set A} (H : a * b⁻¹ ∈ S) : a ∈ S * b := have a * b⁻¹ * b ∈ S * b, from mul_mem_rcoset H b, by rewrite inv_mul_cancel_right at this; apply this proposition mem_rcoset_iff (a b : A) (S : set A) : a ∈ S * b ↔ a * b⁻¹ ∈ S := iff.intro mul_inv_mem_of_mem_rcoset mem_rcoset_of_mul_inv_mem proposition lcoset_eq_iff_eq_inv_lcoset (a : A) (S T : set A) : (a * S = T) ↔ (S = a⁻¹ * T) := iff.intro (assume H, by rewrite [-H, inv_lcoset_lcoset]) (assume H, by rewrite [H, lcoset_inv_lcoset]) proposition rcoset_eq_iff_eq_rcoset_inv (a : A) (S T : set A) : (S * a = T) ↔ (S = T * a⁻¹) := iff.intro (assume H, by rewrite [-H, rcoset_rcoset_inv]) (assume H, by rewrite [H, rcoset_inv_rcoset]) proposition lcoset_inter (a : A) (S T : set A) [is_subgroup S] [is_subgroup T] : a * (S ∩ T) = (a * S) ∩ (a * T) := eq_of_subset_of_subset (image_inter_subset _ S T) (take b, suppose b ∈ (a * S) ∩ (a * T), obtain [s [smem (seq : a * s = b)]] [t [tmem (teq : a * t = b)]], from this, have s = t, from eq_of_mul_eq_mul_left' (eq.trans seq (eq.symm teq)), show b ∈ a * (S ∩ T), begin rewrite -seq, apply mul_mem_lcoset, apply and.intro smem, rewrite this, apply tmem end) proposition inter_rcoset (a : A) (S T : set A) [is_subgroup S] [is_subgroup T] : (S ∩ T) * a = (S * a) ∩ (T * a) := eq_of_subset_of_subset (image_inter_subset _ S T) (take b, suppose b ∈ (S * a) ∩ (T * a), obtain [s [smem (seq : s * a = b)]] [t [tmem (teq : t * a = b)]], from this, have s = t, from eq_of_mul_eq_mul_right' (eq.trans seq (eq.symm teq)), show b ∈ (S ∩ T) * a, begin rewrite -seq, apply mul_mem_rcoset, apply and.intro smem, rewrite this, apply tmem end) end groupA section subgroupG variables [group A] {G : set A} [is_subgroup G] proposition lcoset_eq_self_of_mem {a : A} (aG : a ∈ G) : a * G = G := ext (take x, iff.intro (assume xaG, obtain g [gG xeq], from xaG, show x ∈ G, by rewrite -xeq; exact (mul_mem aG gG)) (assume xG, show x ∈ a * G, from mem_image (show a⁻¹ * x ∈ G, from (mul_mem (inv_mem aG) xG)) !mul_inv_cancel_left)) proposition rcoset_eq_self_of_mem {a : A} (aG : a ∈ G) : G * a = G := ext (take x, iff.intro (assume xGa, obtain g [gG xeq], from xGa, show x ∈ G, by rewrite -xeq; exact (mul_mem gG aG)) (assume xG, show x ∈ G * a, from mem_image (show x * a⁻¹ ∈ G, from (mul_mem xG (inv_mem aG))) !inv_mul_cancel_right)) proposition mem_lcoset_self (a : A) : a ∈ a * G := by rewrite [-mul_one a at {1}]; exact mul_mem_lcoset a one_mem proposition mem_rcoset_self (a : A) : a ∈ G * a := by rewrite [-one_mul a at {1}]; exact mul_mem_rcoset one_mem a proposition mem_of_lcoset_eq_self {a : A} (H : a * G = G) : a ∈ G := by rewrite [-H]; exact mem_lcoset_self a proposition mem_of_rcoset_eq_self {a : A} (H : G * a = G) : a ∈ G := by rewrite [-H]; exact mem_rcoset_self a variable (G) proposition lcoset_eq_self_iff (a : A) : a * G = G ↔ a ∈ G := iff.intro mem_of_lcoset_eq_self lcoset_eq_self_of_mem proposition rcoset_eq_self_iff (a : A) : G * a = G ↔ a ∈ G := iff.intro mem_of_rcoset_eq_self rcoset_eq_self_of_mem variable {G} proposition lcoset_eq_lcoset {a b : A} (H : b⁻¹ * a ∈ G) : a * G = b * G := have b⁻¹ * (a * G) = b⁻¹ * (b * G), by rewrite [inv_lcoset_lcoset, lcoset_lcoset, lcoset_eq_self_of_mem H], eq_of_lcoset_eq_lcoset this proposition inv_mul_mem_of_lcoset_eq_lcoset {a b : A} (H : a * G = b * G) : b⁻¹ * a ∈ G := mem_of_lcoset_eq_self (by rewrite [-lcoset_lcoset, H, inv_lcoset_lcoset]) proposition lcoset_eq_lcoset_iff (a b : A) : a * G = b * G ↔ b⁻¹ * a ∈ G := iff.intro inv_mul_mem_of_lcoset_eq_lcoset lcoset_eq_lcoset proposition rcoset_eq_rcoset {a b : A} (H : a * b⁻¹ ∈ G) : G * a = G * b := have G * a * b⁻¹ = G * b * b⁻¹, by rewrite [rcoset_rcoset_inv, rcoset_rcoset, rcoset_eq_self_of_mem H], eq_of_rcoset_eq_rcoset this proposition mul_inv_mem_of_rcoset_eq_rcoset {a b : A} (H : G * a = G * b) : a * b⁻¹ ∈ G := mem_of_rcoset_eq_self (by rewrite [-rcoset_rcoset, H, rcoset_rcoset_inv]) proposition rcoset_eq_rcoset_iff (a b : A) : G * a = G * b ↔ a * b⁻¹ ∈ G := iff.intro mul_inv_mem_of_rcoset_eq_rcoset rcoset_eq_rcoset end subgroupG /- normal cosets and the normalizer -/ section has_mulA variable [has_mul A] abbreviation normalizes [reducible] (a : A) (S : set A) : Prop := a * S = S * a definition is_normal [class] (S : set A) : Prop := ∀ a, normalizes a S definition normalizer (S : set A) : set A := { a : A | normalizes a S } definition is_normal_in [class] (S T : set A) : Prop := T ⊆ normalizer S abbreviation normalizer_in [reducible] (S T : set A) : set A := T ∩ normalizer S proposition lcoset_eq_rcoset (a : A) (S : set A) [H : is_normal S] : a * S = S * a := H a proposition subset_normalizer (S T : set A) [H : is_normal_in T S] : S ⊆ normalizer T := H proposition lcoset_eq_rcoset_of_mem {a : A} (S : set A) {T : set A} [H : is_normal_in S T] (amemT : a ∈ T) : a * S = S * a := H amemT proposition is_normal_in_of_is_normal (S T : set A) [H : is_normal S] : is_normal_in S T := forallb_of_forall T H proposition is_normal_of_is_normal_in_univ {S : set A} (H : is_normal_in S univ) : is_normal S := forall_of_forallb_univ H proposition is_normal_in_univ_iff_is_normal (S : set A) : is_normal_in S univ ↔ is_normal S := forallb_univ_iff_forall _ proposition is_normal_in_of_subset {S T U : set A} (H : T ⊆ U) (H' : is_normal_in S U) : is_normal_in S T := forallb_of_subset H H' proposition normalizes_of_mem_normalizer {a : A} {S : set A} (H : a ∈ normalizer S) : normalizes a S := H proposition mem_normalizer_iff_normalizes (a : A) (S : set A) : a ∈ normalizer S ↔ normalizes a S := iff.refl _ proposition is_normal_in_normalizer [instance] (S : set A) : is_normal_in S (normalizer S) := subset.refl (normalizer S) end has_mulA section groupA variable [group A] proposition is_normal_in_of_forall_subset {S G : set A} [is_subgroup G] (H : ∀₀ x ∈ G, x * S ⊆ S * x) : is_normal_in S G := take x, assume xG, show x * S = S * x, from eq_of_subset_of_subset (H xG) (have x * (x⁻¹ * S) * x ⊆ x * (S * x⁻¹) * x, from rcoset_subset_rcoset (lcoset_subset_lcoset x (H (inv_mem xG))) x, show S * x ⊆ x * S, begin rewrite [lcoset_inv_lcoset at this, lcoset_rcoset at this, rcoset_inv_rcoset at this], exact this end) proposition is_normal_of_forall_subset {S : set A} (H : ∀ x, x * S ⊆ S * x) : is_normal S := begin rewrite [-is_normal_in_univ_iff_is_normal], apply is_normal_in_of_forall_subset, intro x xuniv, exact H x end proposition subset_normalizer_self (G : set A) [is_subgroup G] : G ⊆ normalizer G := take a, assume aG, show a * G = G * a, by rewrite [lcoset_eq_self_of_mem aG, rcoset_eq_self_of_mem aG] end groupA section normalG variables [group A] (G : set A) [is_normal G] proposition lcoset_equiv_mul {a₁ a₂ b₁ b₂ : A} (H₁ : lcoset_equiv G a₁ a₂) (H₂ : lcoset_equiv G b₁ b₂) : lcoset_equiv G (a₁ * b₁) (a₂ * b₂) := begin unfold lcoset_equiv at *, rewrite [-lcoset_lcoset, H₂, lcoset_eq_rcoset, -lcoset_rcoset, H₁, lcoset_rcoset, -lcoset_eq_rcoset, lcoset_lcoset] end proposition lcoset_equiv_inv {a₁ a₂ : A} (H : lcoset_equiv G a₁ a₂) : lcoset_equiv G a₁⁻¹ a₂⁻¹ := begin unfold lcoset_equiv at *, have a₁⁻¹ * G = a₂⁻¹ * (a₂ * G) * a₁⁻¹, by rewrite [inv_lcoset_lcoset, lcoset_eq_rcoset], rewrite [this, -H, lcoset_rcoset, lcoset_eq_rcoset, rcoset_rcoset_inv] end end normalG /- the normalizer is a subgroup -/ section semigroupA variable [semigroup A] proposition mul_mem_normalizer {S : set A} {a b : A} (Ha : a ∈ normalizer S) (Hb : b ∈ normalizer S) : a * b ∈ normalizer S := show a * b * S = S * (a * b), by rewrite [-lcoset_lcoset, normalizes_of_mem_normalizer Hb, -lcoset_rcoset, normalizes_of_mem_normalizer Ha, rcoset_rcoset] end semigroupA section monoidA variable [monoid A] proposition one_mem_normalizer (S : set A) : 1 ∈ normalizer S := by rewrite [↑normalizer, mem_set_of_iff, one_lcoset, rcoset_one] end monoidA section groupA variable [group A] proposition inv_mem_normalizer {S : set A} {a : A} (H : a ∈ normalizer S) : a⁻¹ ∈ normalizer S := have a⁻¹ * S = S * a⁻¹, begin apply iff.mp (rcoset_eq_iff_eq_rcoset_inv _ _ _), rewrite [lcoset_rcoset, -normalizes_of_mem_normalizer H, inv_lcoset_lcoset] end, by rewrite [↑normalizer, mem_set_of_iff, this] proposition is_subgroup_normalizer [instance] (S : set A) : is_subgroup (normalizer S) := ⦃ is_subgroup, one_mem := one_mem_normalizer S, mul_mem := λ a Ha b Hb, mul_mem_normalizer Ha Hb, inv_mem := λ a H, inv_mem_normalizer H⦄ end groupA section subgroupG variables [group A] {G : set A} [is_subgroup G] proposition normalizes_image_of_is_hom_on [group B] {a : A} (aG : a ∈ G) {S : set A} (SsubG : S ⊆ G) (H : normalizes a S) (f : A → B) [is_hom_on f G] : normalizes (f a) (f ' S) := by rewrite [-image_lcoset_of_is_hom_on SsubG aG, -image_rcoset_of_is_hom_on SsubG aG, ↑normalizes at H, H] proposition is_normal_in_image_image [group B] {S T : set A} (SsubT : S ⊆ T) [H : is_normal_in S T] (f : A → B) [is_subgroup T] [is_hom_on f T] : is_normal_in (f ' S) (f ' T) := take a, assume afT, obtain b [bT (beq : f b = a)], from afT, show normalizes a (f ' S), begin rewrite -beq, apply (normalizes_image_of_is_hom_on bT SsubT (H bT)) end proposition normalizes_image_of_is_hom [group B] {a : A} {S : set A} (H : normalizes a S) (f : A → B) [is_hom f] : normalizes (f a) (f ' S) := by rewrite [-image_lcoset_of_is_hom f a S, -image_rcoset_of_is_hom f S a, ↑normalizes at H, H] proposition is_normal_in_image_image_univ [group B] {S : set A} [H : is_normal S] (f : A → B) [is_hom f] : is_normal_in (f ' S) (f ' univ) := take a, assume afT, obtain b [buniv (beq : f b = a)], from afT, show normalizes a (f ' S), begin rewrite -beq, apply (normalizes_image_of_is_hom (H b) f) end end subgroupG /- conjugation -/ definition conj [reducible] [group A] (a b : A) : A := b⁻¹ * a * b definition set_conj [reducible] [group A] (S : set A)(a : A) : set A := a⁻¹ * S * a -- conj^~ a ' S namespace conj_notation infix `^` := conj infix `^` := set_conj end conj_notation open conj_notation section groupA variables [group A] proposition set_conj_eq_image_conj (S : set A) (a : A) : S^a = conj^~ a 'S := eq.symm !image_comp proposition set_conj_eq_self_of_normalizes {S : set A} {a : A} (H : normalizes a S) : S^a = S := by rewrite [lcoset_rcoset, ↑normalizes at H, -H, inv_lcoset_lcoset] proposition normalizes_of_set_conj_eq_self {S : set A} {a : A} (H : S^a = S) : normalizes a S := by rewrite [-H at {1}, ↑set_conj, lcoset_rcoset, lcoset_inv_lcoset] proposition set_conj_eq_self_iff_normalizes (S : set A) (a : A) : S^a = S ↔ normalizes a S := iff.intro normalizes_of_set_conj_eq_self set_conj_eq_self_of_normalizes proposition set_conj_eq_self_of_mem_normalizer {S : set A} {a : A} (H : a ∈ normalizer S) : S^a = S := set_conj_eq_self_of_normalizes H proposition mem_normalizer_of_set_conj_eq_self {S : set A} {a : A} (H : S^a = S) : a ∈ normalizer S := normalizes_of_set_conj_eq_self H proposition set_conj_eq_self_iff_mem_normalizer (S : set A) (a : A) : S^a = S ↔ a ∈ normalizer S := iff.intro mem_normalizer_of_set_conj_eq_self set_conj_eq_self_of_mem_normalizer proposition conj_one (a : A) : a ^ (1 : A) = a := by rewrite [↑conj, one_inv, one_mul, mul_one] proposition conj_conj (a b c : A) : (a^b)^c = a^(b * c) := by rewrite [↑conj, mul_inv, *mul.assoc] proposition conj_inv (a b : A) : (a^b)⁻¹ = (a⁻¹)^b := by rewrite[mul_inv, mul_inv, inv_inv, mul.assoc] proposition mul_conj (a b c : A) : (a * b)^c = a^c * b^c := by rewrite[↑conj, *mul.assoc, mul_inv_cancel_left] end groupA /- the kernel -/ definition ker [has_one B] (f : A → B) : set A := { x | f x = 1 } section hasoneB variable [has_one B] proposition eq_one_of_mem_ker {f : A → B} {a : A} (H : a ∈ ker f) : f a = 1 := H proposition mem_ker_iff (f : A → B) (a : A) : a ∈ ker f ↔ f a = 1 := iff.rfl proposition ker_eq_preimage_one (f : A → B) : ker f = f '- '{1} := ext (take x, by rewrite [mem_ker_iff, -mem_preimage_iff, mem_singleton_iff]) definition ker_in (f : A → B) (S : set A) : set A := ker f ∩ S proposition ker_in_univ (f : A → B) : ker_in f univ = ker f := !inter_univ end hasoneB section groupAB variables [group A] [group B] variable {f : A → B} proposition eq_of_mul_inv_mem_ker [is_hom f] {a₁ a₂ : A} (H : a₁ * a₂⁻¹ ∈ ker f) : f a₁ = f a₂ := eq_of_mul_inv_eq_one (by rewrite [-hom_inv f, -hom_mul f]; exact H) proposition mul_inv_mem_ker_of_eq [is_hom f] {a₁ a₂ : A} (H : f a₁ = f a₂) : a₁ * a₂⁻¹ ∈ ker f := show f (a₁ * a₂⁻¹) = 1, by rewrite [hom_mul f, hom_inv f, H, mul.right_inv] proposition eq_iff_mul_inv_mem_ker [is_hom f] (a₁ a₂ : A) : f a₁ = f a₂ ↔ a₁ * a₂⁻¹ ∈ ker f := iff.intro mul_inv_mem_ker_of_eq eq_of_mul_inv_mem_ker proposition eq_of_mul_inv_mem_ker_in {G : set A} [is_subgroup G] [is_hom_on f G] {a₁ a₂ : A} (a₁G : a₁ ∈ G) (a₂G : a₂ ∈ G) (H : a₁ * a₂⁻¹ ∈ ker_in f G) : f a₁ = f a₂ := eq_of_mul_inv_eq_one (by rewrite [-hom_on_inv f a₂G, -hom_on_mul f a₁G (inv_mem a₂G)]; exact and.left H) proposition mul_inv_mem_ker_in_of_eq {G : set A} [is_subgroup G] [is_hom_on f G] {a₁ a₂ : A} (a₁G : a₁ ∈ G) (a₂G : a₂ ∈ G) (H : f a₁ = f a₂) : a₁ * a₂⁻¹ ∈ ker_in f G := and.intro (show f (a₁ * a₂⁻¹) = 1, by rewrite [hom_on_mul f a₁G (inv_mem a₂G), hom_on_inv f a₂G, H, mul.right_inv]) (mul_mem a₁G (inv_mem a₂G)) proposition eq_iff_mul_inv_mem_ker_in {G : set A} [is_subgroup G] [is_hom_on f G] {a₁ a₂ : A} (a₁G : a₁ ∈ G) (a₂G : a₂ ∈ G) : f a₁ = f a₂ ↔ a₁ * a₂⁻¹ ∈ ker_in f G := iff.intro (mul_inv_mem_ker_in_of_eq a₁G a₂G) (eq_of_mul_inv_mem_ker_in a₁G a₂G) -- Ouch! These versions are not equivalent to the ones before. proposition eq_of_inv_mul_mem_ker [is_hom f] {a₁ a₂ : A} (H : a₁⁻¹ * a₂ ∈ ker f) : f a₁ = f a₂ := eq.symm (eq_of_inv_mul_eq_one (by rewrite [-hom_inv f, -hom_mul f]; exact H)) proposition inv_mul_mem_ker_of_eq [is_hom f] {a₁ a₂ : A} (H : f a₁ = f a₂) : a₁⁻¹ * a₂ ∈ ker f := show f (a₁⁻¹ * a₂) = 1, by rewrite [hom_mul f, hom_inv f, H, mul.left_inv] proposition eq_iff_inv_mul_mem_ker [is_hom f] (a₁ a₂ : A) : f a₁ = f a₂ ↔ a₁⁻¹ * a₂ ∈ ker f := iff.intro inv_mul_mem_ker_of_eq eq_of_inv_mul_mem_ker proposition eq_of_inv_mul_mem_ker_in {G : set A} [is_subgroup G] [is_hom_on f G] {a₁ a₂ : A} (a₁G : a₁ ∈ G) (a₂G : a₂ ∈ G) (H : a₁⁻¹ * a₂ ∈ ker_in f G) : f a₁ = f a₂ := eq.symm (eq_of_inv_mul_eq_one (by rewrite [-hom_on_inv f a₁G, -hom_on_mul f (inv_mem a₁G) a₂G]; exact and.left H)) proposition inv_mul_mem_ker_in_of_eq {G : set A} [is_subgroup G] [is_hom_on f G] {a₁ a₂ : A} (a₁G : a₁ ∈ G) (a₂G : a₂ ∈ G) (H : f a₁ = f a₂) : a₁⁻¹ * a₂ ∈ ker_in f G := and.intro (show f (a₁⁻¹ * a₂) = 1, by rewrite [hom_on_mul f (inv_mem a₁G) a₂G, hom_on_inv f a₁G, H, mul.left_inv]) (mul_mem (inv_mem a₁G) a₂G) proposition eq_iff_inv_mul_mem_ker_in {G : set A} [is_subgroup G] [is_hom_on f G] {a₁ a₂ : A} (a₁G : a₁ ∈ G) (a₂G : a₂ ∈ G) : f a₁ = f a₂ ↔ a₁⁻¹ * a₂ ∈ ker_in f G := iff.intro (inv_mul_mem_ker_in_of_eq a₁G a₂G) (eq_of_inv_mul_mem_ker_in a₁G a₂G) proposition eq_one_of_eq_one_of_injective [is_hom f] (H : injective f) {x : A} (H' : f x = 1) : x = 1 := H (by rewrite [H', hom_one f]) proposition eq_one_iff_eq_one_of_injective [is_hom f] (H : injective f) (x : A) : f x = 1 ↔ x = 1 := iff.intro (eq_one_of_eq_one_of_injective H) (λ H', by rewrite [H', hom_one f]) proposition injective_of_forall_eq_one [is_hom f] (H : ∀ x, f x = 1 → x = 1) : injective f := take a₁ a₂, assume Heq, have f (a₁ * a₂⁻¹) = 1, by rewrite [hom_mul f, hom_inv f, Heq, mul.right_inv], eq_of_mul_inv_eq_one (H _ this) proposition injective_of_ker_eq_singleton_one [is_hom f] (H : ker f = '{1}) : injective f := injective_of_forall_eq_one (take x, suppose x ∈ ker f, by rewrite [H at this]; exact eq_of_mem_singleton this) proposition ker_eq_singleton_one_of_injective [is_hom f] (H : injective f) : ker f = '{1} := ext (take x, by rewrite [mem_ker_iff, mem_singleton_iff, eq_one_iff_eq_one_of_injective H]) variable (f) proposition injective_iff_ker_eq_singleton_one [is_hom f] : injective f ↔ ker f = '{1} := iff.intro ker_eq_singleton_one_of_injective injective_of_ker_eq_singleton_one variable {f} proposition eq_one_of_eq_one_of_inj_on {G : set A} [is_subgroup G] [is_hom_on f G] (H : inj_on f G) {x : A} (xG : x ∈ G) (H' : f x = 1) : x = 1 := H xG one_mem (by rewrite [H', hom_on_one f G]) proposition eq_one_iff_eq_one_of_inj_on {G : set A} [is_subgroup G] [is_hom_on f G] (H : inj_on f G) {x : A} (xG : x ∈ G) [is_hom_on f G] : f x = 1 ↔ x = 1 := iff.intro (eq_one_of_eq_one_of_inj_on H xG) (λ H', by rewrite [H', hom_on_one f G]) proposition inj_on_of_forall_eq_one {G : set A} [is_subgroup G] [is_hom_on f G] (H : ∀₀ x ∈ G, f x = 1 → x = 1) : inj_on f G := take a₁ a₂, assume a₁G a₂G Heq, have f (a₁ * a₂⁻¹) = 1, by rewrite [hom_on_mul f a₁G (inv_mem a₂G), hom_on_inv f a₂G, Heq, mul.right_inv], eq_of_mul_inv_eq_one (H (mul_mem a₁G (inv_mem a₂G)) this) proposition inj_on_of_ker_in_eq_singleton_one {G : set A} [is_subgroup G] [is_hom_on f G] (H : ker_in f G = '{1}) : inj_on f G := inj_on_of_forall_eq_one (take x, assume xG fxone, have x ∈ ker_in f G, from and.intro fxone xG, by rewrite [H at this]; exact eq_of_mem_singleton this) proposition ker_in_eq_singleton_one_of_inj_on {G : set A} [is_subgroup G] [is_hom_on f G] (H : inj_on f G) : ker_in f G = '{1} := ext (take x, begin rewrite [↑ker_in, mem_inter_iff, mem_ker_iff, mem_singleton_iff], apply iff.intro, {intro H', cases H' with fxone xG, exact eq_one_of_eq_one_of_inj_on H xG fxone}, intro xone, rewrite xone, split, exact hom_on_one f G, exact one_mem end) variable (f) proposition inj_on_iff_ker_in_eq_singleton_one (G : set A) [is_subgroup G] [is_hom_on f G] : inj_on f G ↔ ker_in f G = '{1} := iff.intro ker_in_eq_singleton_one_of_inj_on inj_on_of_ker_in_eq_singleton_one variable {f} proposition conj_mem_ker [is_hom f] {a₁ : A} (a₂ : A) (H : a₁ ∈ ker f) : a₁^a₂ ∈ ker f := show f (a₁^a₂) = 1, by rewrite [↑conj, *(hom_mul f), hom_inv f, eq_one_of_mem_ker H, mul_one, mul.left_inv] variable (f) proposition is_subgroup_ker_in [instance] (S : set A) [is_subgroup S] [is_hom_on f S] : is_subgroup (ker_in f S) := ⦃ is_subgroup, one_mem := and.intro (hom_on_one f S) one_mem, mul_mem := λ a aker b bker, obtain (fa : f a = 1) (aS : a ∈ S), from aker, obtain (fb : f b = 1) (bS : b ∈ S), from bker, and.intro (show f (a * b) = 1, by rewrite [hom_on_mul f aS bS, fa, fb, one_mul]) (mul_mem aS bS), inv_mem := λ a aker, obtain (fa : f a = 1) (aS : a ∈ S), from aker, and.intro (show f (a⁻¹) = 1, by rewrite [hom_on_inv f aS, fa, one_inv]) (inv_mem aS) ⦄ proposition is_subgroup_ker [instance] [is_hom f] : is_subgroup (ker f) := begin rewrite [-ker_in_univ f], have is_hom_on f univ, from is_hom_on_of_is_hom f univ, apply is_subgroup_ker_in f univ end proposition is_normal_in_ker_in [instance] (G : set A) [is_subgroup G] [is_hom_on f G] : is_normal_in (ker_in f G) G := is_normal_in_of_forall_subset (take x, assume xG, take y, assume yker, obtain z [[(fz : f z = 1) zG] (yeq : x * z = y)], from yker, have y = x * z * x⁻¹ * x, by rewrite [yeq, inv_mul_cancel_right], show y ∈ ker_in f G * x, begin rewrite this, apply mul_mem_rcoset, apply and.intro, show f (x * z * x⁻¹) = 1, by rewrite [hom_on_mul f (mul_mem xG zG) (inv_mem xG), hom_on_mul f xG zG, fz, hom_on_inv f xG, mul_one, mul.right_inv], show x * z * x⁻¹ ∈ G, from mul_mem (mul_mem xG zG) (inv_mem xG) end) proposition is_normal_ker [instance] [H : is_hom f] : is_normal (ker f) := begin rewrite [-ker_in_univ, -is_normal_in_univ_iff_is_normal], apply is_normal_in_ker_in, exact is_hom_on_of_is_hom f univ end end groupAB section subgroupH variables [group A] [group B] {H : set A} [is_subgroup H] variables {f : A → B} [is_hom f] proposition subset_ker_of_forall (hyp : ∀ x y, x * H = y * H → f x = f y) : H ⊆ ker f := take h, assume hH, have h * H = 1 * H, by rewrite [lcoset_eq_self_of_mem hH, one_lcoset], have f h = f 1, from hyp h 1 this, show f h = 1, by rewrite [this, hom_one f] proposition eq_of_lcoset_eq_lcoset_of_subset_ker {x y : A} (hyp₀ : x * H = y * H) (hyp₁ : H ⊆ ker f) : f x = f y := have y⁻¹ * x ∈ H, from inv_mul_mem_of_lcoset_eq_lcoset hyp₀, eq.symm (eq_of_inv_mul_mem_ker (hyp₁ this)) variables (H f) proposition subset_ker_iff : H ⊆ ker f ↔ ∀ x y, x * H = y * H → f x = f y := iff.intro (λ h₁ x y h₀, eq_of_lcoset_eq_lcoset_of_subset_ker h₀ h₁) subset_ker_of_forall end subgroupH section subgroupGH variables [group A] [group B] {G H : set A} [is_subgroup G] [is_subgroup H] variables {f : A → B} [is_hom_on f G] proposition subset_ker_in_of_forall (hyp₀ : ∀₀ x ∈ G, ∀₀ y ∈ G, x * H = y * H → f x = f y) (hyp₁ : H ⊆ G) : H ⊆ ker_in f G := take h, assume hH, have hG : h ∈ G, from hyp₁ hH, and.intro (have h * H = 1 * H, by rewrite [lcoset_eq_self_of_mem hH, one_lcoset], have f h = f 1, from hyp₀ hG one_mem this, show f h = 1, by rewrite [this, hom_on_one f G]) hG proposition eq_of_lcoset_eq_lcoset_of_subset_ker_in {x : A} (xG : x ∈ G) {y : A} (yG : y ∈ G) (hyp₀ : x * H = y * H) (hyp₁ : H ⊆ ker_in f G) : f x = f y := have y⁻¹ * x ∈ H, from inv_mul_mem_of_lcoset_eq_lcoset hyp₀, eq.symm (eq_of_inv_mul_mem_ker_in yG xG (hyp₁ this)) variables (H f) proposition subset_ker_in_iff : H ⊆ ker_in f G ↔ (H ⊆ G ∧ ∀₀ x ∈ G, ∀₀ y ∈ G, x * H = y * H → f x = f y) := iff.intro (λ h₁, and.intro (subset.trans h₁ (inter_subset_right _ _)) (λ x xG y yG h₀, eq_of_lcoset_eq_lcoset_of_subset_ker_in xG yG h₀ h₁)) (λ h, subset_ker_in_of_forall (and.right h) (and.left h)) end subgroupGH /- the centralizer -/ section has_mulA variable [has_mul A] abbreviation centralizes [reducible] (a : A) (S : set A) : Prop := ∀₀ b ∈ S, a * b = b * a definition centralizer (S : set A) : set A := { a : A | centralizes a S } abbreviation is_centralized_by (S T : set A) : Prop := T ⊆ centralizer S abbreviation centralizer_in (S T : set A) : set A := T ∩ centralizer S proposition mem_centralizer_iff_centralizes (a : A) (S : set A) : a ∈ centralizer S ↔ centralizes a S := iff.refl _ proposition normalizes_of_centralizes {a : A} {S : set A} (H : centralizes a S) : normalizes a S := ext (take b, iff.intro (suppose b ∈ a * S, obtain s [ains (beq : a * s = b)], from this, show b ∈ S * a, by rewrite[-beq, H ains]; apply mem_image_of_mem _ ains) (suppose b ∈ S * a, obtain s [ains (beq : s * a = b)], from this, show b ∈ a * S, by rewrite[-beq, -H ains]; apply mem_image_of_mem _ ains)) proposition centralizer_subset_normalizer (S : set A) : centralizer S ⊆ normalizer S := λ a acent, normalizes_of_centralizes acent proposition centralizer_subset_centralizer {S T : set A} (ssubt : S ⊆ T) : centralizer T ⊆ centralizer S := λ x xCentT s sS, xCentT _ (ssubt sS) end has_mulA section groupA variable [group A] proposition is_subgroup_centralizer [instance] [group A] (S : set A) : is_subgroup (centralizer S) := ⦃ is_subgroup, one_mem := λ b bS, by rewrite [one_mul, mul_one], mul_mem := λ a acent b bcent c cS, by rewrite [mul.assoc, bcent cS, -*mul.assoc, acent cS], inv_mem := λ a acent c cS, eq_mul_inv_of_mul_eq (by rewrite [mul.assoc, -acent cS, inv_mul_cancel_left])⦄ end groupA /- the subgroup generated by a set -/ section groupA variable [group A] inductive subgroup_generated_by (S : set A) : A → Prop := | generators_mem : ∀ x, x ∈ S → subgroup_generated_by S x | one_mem : subgroup_generated_by S 1 | mul_mem : ∀ x y, subgroup_generated_by S x → subgroup_generated_by S y → subgroup_generated_by S (x * y) | inv_mem : ∀ x, subgroup_generated_by S x → subgroup_generated_by S (x⁻¹) theorem generators_subset_subgroup_generated_by (S : set A) : S ⊆ subgroup_generated_by S := subgroup_generated_by.generators_mem theorem is_subgroup_subgroup_generated_by [instance] (S : set A) : is_subgroup (subgroup_generated_by S) := ⦃ is_subgroup, one_mem := subgroup_generated_by.one_mem S, mul_mem := λ a amem b bmem, subgroup_generated_by.mul_mem a b amem bmem, inv_mem := λ a amem, subgroup_generated_by.inv_mem a amem ⦄ theorem subgroup_generated_by_subset {S G : set A} [is_subgroup G] (H : S ⊆ G) : subgroup_generated_by S ⊆ G := begin intro x xgenS, induction xgenS with a aS a b agen bgen aG bG a agen aG, {exact H aS}, {exact one_mem}, {exact mul_mem aG bG}, exact inv_mem aG end end groupA end group_theory
c9bc885797e4040f894e301745e266764708292d
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/doc/examples/bintree.lean
9b9236638874f0c10132b7c421a64ce2868c5da4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
10,900
lean
/-! # Binary Search Trees If the type of keys can be totally ordered -- that is, it supports a well-behaved `≤` comparison -- then maps can be implemented with binary search trees (BSTs). Insert and lookup operations on BSTs take time proportional to the height of the tree. If the tree is balanced, the operations therefore take logarithmic time. This example is based on a similar example found in the ["Sofware Foundations"](https://softwarefoundations.cis.upenn.edu/vfa-current/SearchTree.html) book (volume 3). -/ /-! We use `Nat` as the key type in our implementation of BSTs, since it has a convenient total order with lots of theorems and automation available. We leave as an exercise to the reader the generalization to arbitrary types. -/ inductive Tree (β : Type v) where | leaf | node (left : Tree β) (key : Nat) (value : β) (right : Tree β) deriving Repr /-! The function `contains` returns `true` iff the given tree contains the key `k`. -/ def Tree.contains (t : Tree β) (k : Nat) : Bool := match t with | leaf => false | node left key value right => if k < key then left.contains k else if key < k then right.contains k else true /-! `t.find? k` returns `some v` if `v` is the value bound to key `k` in the tree `t`. It returns `none` otherwise. -/ 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 /-! `t.insert k v` is the map containing all the bindings of `t` along with a binding of `k` to `v`. -/ 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 /-! Let's add a new operation to our tree: converting it to an association list that contains the key--value bindings from the tree stored as pairs. If that list is sorted by the keys, then any two trees that represent the same map would be converted to the same list. Here's a function that does so with an in-order traversal of the tree. -/ def Tree.toList (t : Tree β) : List (Nat × β) := match t with | leaf => [] | node l k v r => l.toList ++ [(k, v)] ++ r.toList #eval Tree.leaf.insert 2 "two" |>.insert 3 "three" |>.insert 1 "one" #eval Tree.leaf.insert 2 "two" |>.insert 3 "three" |>.insert 1 "one" |>.toList /-! The implemention of `Tree.toList` is inefficient because of how it uses the `++` operator. On a balanced tree its running time is linearithmic, because it does a linear number of concatentations at each level of the tree. On an unbalanced tree it's quadratic time. Here's a tail-recursive implementation than runs in linear time, regardless of whether the tree is balanced: -/ def Tree.toListTR (t : Tree β) : List (Nat × β) := go t [] where go (t : Tree β) (acc : List (Nat × β)) : List (Nat × β) := match t with | leaf => acc | node l k v r => go l ((k, v) :: go r acc) /-! We now prove that `t.toList` and `t.toListTR` return the same list. The proof is on induction, and as we used the auxiliary function `go` to define `Tree.toListTR`, we use the auxiliary theorem `go` to prove the theorem. The proof of the auxiliary theorem is by induction on `t`. The `generalizing acc` modifier instructs Lean to revert `acc`, apply the induction theorem for `Tree`s, and then reintroduce `acc` in each case. By using `generalizing`, we obtain the more general induction hypotheses - `left_ih : ∀ acc, toListTR.go left acc = toList left ++ acc` - `right_ih : ∀ acc, toListTR.go right acc = toList right ++ acc` Recall that the combinator `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. In this theorem, we use it to apply `simp` and close each subgoal produced by the `induction` tactic. The `simp` parameters `toListTR.go` and `toList` instruct the simplifier to try to reduce and/or apply auto generated equation theorems for these two functions. The parameter `*` intructs the simplifier to use any equation in a goal as rewriting rules. In this particular case, `simp` uses the induction hypotheses as rewriting rules. Finally, the parameter `List.append_assoc` intructs the simplifier to use the `List.append_assoc` theorem as a rewriting rule. -/ theorem Tree.toList_eq_toListTR (t : Tree β) : t.toList = t.toListTR := by simp [toListTR, go t []] where go (t : Tree β) (acc : List (Nat × β)) : toListTR.go t acc = t.toList ++ acc := by induction t generalizing acc <;> simp [toListTR.go, toList, *, List.append_assoc] /-! The `[csimp]` annotation instructs the Lean code generator to replace any `Tree.toList` with `Tree.toListTR` when generating code. -/ @[csimp] theorem Tree.toList_eq_toListTR_csimp : @Tree.toList = @Tree.toListTR := by funext β t apply toList_eq_toListTR /-! The implementations of `Tree.find?` and `Tree.insert` assume that values of type tree obey the BST invariant: for any non-empty node with key `k`, all the values of the `left` subtree are less than `k` and all the values of the right subtree are greater than `k`. But that invariant is not part of the definition of tree. So, let's formalize the BST invariant. Here's one way to do so. First, we define a helper `ForallTree` to express that idea that a predicate holds at every node of a tree: -/ 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) /-! Second, we define the BST invariant: An empty tree is a BST. A non-empty tree is a BST if all its left nodes have a lesser key, its right nodes have a greater key, and the left and right subtrees are themselves BSTs. -/ inductive BST : Tree β → Prop | leaf : BST .leaf | node : ForallTree (fun k v => k < key) left → ForallTree (fun k v => key < k) right → BST left → BST right → BST (.node left key value right) /-! We can use the `macro` command to create helper tactics for organizing our proofs. The macro `have_eq x y` tries to prove `x = y` using linear arithmetic, and then immediately uses the new equality to substitute `x` with `y` everywhere in the goal. The modifier `local` specifies the scope of the macro. -/ /-- The `have_eq lhs rhs` tactic (tries to) prove that `lhs = rhs`, and then replaces `lhs` with `rhs`. -/ local macro "have_eq " lhs:term:max rhs:term:max : tactic => `((have h : $lhs = $rhs := -- TODO: replace with linarith by simp_arith at *; apply Nat.le_antisymm <;> assumption try subst $lhs)) /-! The `by_cases' e` is just the regular `by_cases` followed by `simp` using all hypotheses in the current goal as rewriting rules. Recall that the `by_cases` tactic creates two goals. One where we have `h : e` and another one containing `h : ¬ e`. The simplier uses the `h` to rewrite `e` to `True` in the first subgoal, and `e` to `False` in the second. This is particularly useful if `e` is the condition of an `if`-statement. -/ /-- `by_cases' e` is a shorthand form `by_cases e <;> simp[*]` -/ local macro "by_cases' " e:term : tactic => `(by_cases $e <;> simp [*]) /-! We can use the attribute `[simp]` to instruct the simplifier to reduce given definitions or apply rewrite theorems. The `local` modifier limits the scope of this modification to this file. -/ attribute [local simp] Tree.insert /-! We now prove that `Tree.insert` preserves the BST invariant using induction and case analysis. Recall that the tactic `. tac` focuses on the main goal and tries to solve it using `tac`, or else fails. It is used to structure proofs in Lean. The notation `‹e›` is just syntax sugar for `(by assumption : e)`. That is, it tries to find a hypothesis `h : e`. It is useful to access hypothesis that have auto generated names (aka "inaccessible") names. -/ theorem Tree.forall_insert_of_forall (h₁ : ForallTree p t) (h₂ : p key value) : ForallTree p (t.insert key value) := by induction h₁ with | leaf => exact .node .leaf h₂ .leaf | node hl hp hr ihl ihr => rename Nat => k by_cases' key < k . exact .node ihl hp hr . by_cases' k < key . exact .node hl hp ihr . have_eq key k exact .node hl h₂ hr theorem Tree.bst_insert_of_bst {t : Tree β} (h : BST t) (key : Nat) (value : β) : BST (t.insert key value) := by induction h with | leaf => exact .node .leaf .leaf .leaf .leaf | node h₁ h₂ b₁ b₂ ih₁ ih₂ => rename Nat => k simp by_cases' key < k . exact .node (forall_insert_of_forall h₁ ‹key < k›) h₂ ih₁ b₂ . by_cases' k < key . exact .node h₁ (forall_insert_of_forall h₂ ‹k < key›) b₁ ih₂ . have_eq key k exact .node h₁ h₂ b₁ b₂ /-! Now, we define the type `BinTree` using a `Subtype` that states that only trees satisfying the BST invariant are `BinTree`s. -/ def BinTree (β : Type u) := { t : Tree β // BST t } def BinTree.mk : BinTree β := ⟨.leaf, .leaf⟩ def BinTree.contains (b : BinTree β) (k : Nat) : Bool := b.val.contains k 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, b.val.bst_insert_of_bst b.property k v⟩ /-! Finally, we prove that `BinTree.find?` and `BinTree.insert` satisfy the map properties. -/ attribute [local simp] BinTree.mk BinTree.contains BinTree.find? BinTree.insert Tree.find? Tree.contains Tree.insert theorem BinTree.find_mk (k : Nat) : BinTree.mk.find? k = (none : Option β) := by simp 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 . cases h; apply ihl; assumption . by_cases' key < k cases h; apply ihr; assumption theorem BinTree.find_insert_of_ne (b : BinTree β) (h : k ≠ k') (v : β) : (b.insert k v).find? k' = b.find? k' := by let ⟨t, h⟩ := b; simp induction t with simp | leaf => split <;> simp <;> split <;> simp have_eq k k' contradiction | node left key value right ihl ihr => let .node hl hr bl br := h specialize ihl bl specialize ihr br by_cases' k < key; by_cases' key < k have_eq key k by_cases' k' < k; by_cases' k < k' have_eq k k' contradiction
cdee1f0e3566594dac29a44c9cc224dcbe059573
680b0d1592ce164979dab866b232f6fa743f2cc8
/hott/types/pointed.hlean
02caf0818275c4a84849fcf86c856be74ca55105
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
12,082
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ import arity .eq .bool .unit .sigma .nat.basic open is_trunc eq prod sigma nat equiv option is_equiv bool unit algebra structure pointed [class] (A : Type) := (point : A) structure Pointed := {carrier : Type} (Point : carrier) open Pointed notation `Type*` := Pointed namespace pointed attribute Pointed.carrier [coercion] variables {A B : Type} definition pt [unfold 2] [H : pointed A] := point A protected definition Mk [constructor] := @Pointed.mk protected definition MK [constructor] (A : Type) (a : A) := Pointed.mk a protected definition mk' [constructor] (A : Type) [H : pointed A] : Type* := Pointed.mk (point A) definition pointed_carrier [instance] [constructor] (A : Type*) : pointed A := pointed.mk (Point A) -- Any contractible type is pointed definition pointed_of_is_contr [instance] [priority 800] [constructor] (A : Type) [H : is_contr A] : pointed A := pointed.mk !center -- A pi type with a pointed target is pointed definition pointed_pi [instance] [constructor] (P : A → Type) [H : Πx, pointed (P x)] : pointed (Πx, P x) := pointed.mk (λx, pt) -- A sigma type of pointed components is pointed definition pointed_sigma [instance] [constructor] (P : A → Type) [G : pointed A] [H : pointed (P pt)] : pointed (Σx, P x) := pointed.mk ⟨pt,pt⟩ definition pointed_prod [instance] [constructor] (A B : Type) [H1 : pointed A] [H2 : pointed B] : pointed (A × B) := pointed.mk (pt,pt) definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) := pointed.mk idp definition pointed_bool [instance] [constructor] : pointed bool := pointed.mk ff definition Bool [constructor] : Type* := pointed.mk' bool definition Unit [constructor] : Type* := Pointed.mk unit.star definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B := pointed.mk (f pt) definition Loop_space [reducible] [constructor] (A : Type*) : Type* := pointed.mk' (point A = point A) definition Iterated_loop_space [unfold 1] [reducible] : ℕ → Type* → Type* | Iterated_loop_space 0 X := X | Iterated_loop_space (n+1) X := Loop_space (Iterated_loop_space n X) prefix `Ω`:(max+5) := Loop_space notation `Ω[`:95 n:0 `] `:0 A:95 := Iterated_loop_space n A definition rfln [constructor] [reducible] {A : Type*} {n : ℕ} : Ω[n] A := pt definition refln [constructor] [reducible] (A : Type*) (n : ℕ) : Ω[n] A := pt definition refln_eq_refl (A : Type*) (n : ℕ) : rfln = rfl :> Ω[succ n] A := rfl definition iterated_loop_space [unfold 3] (A : Type) [H : pointed A] (n : ℕ) : Type := Ω[n] (pointed.mk' A) open equiv.ops definition Pointed_eq {A B : Type*} (f : A ≃ B) (p : f pt = pt) : A = B := begin cases A with A a, cases B with B b, esimp at *, fapply apd011 @Pointed.mk, { apply ua f}, { rewrite [cast_ua,p]}, end protected definition Pointed.sigma_char.{u} : Pointed.{u} ≃ Σ(X : Type.{u}), X := begin fapply equiv.MK, { intro x, induction x with X x, exact ⟨X, x⟩}, { intro x, induction x with X x, exact pointed.MK X x}, { intro x, induction x with X x, reflexivity}, { intro x, induction x with X x, reflexivity}, end definition add_point [constructor] (A : Type) : Type* := Pointed.mk (none : option A) postfix `₊`:(max+1) := add_point -- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A") end pointed open pointed structure pmap (A B : Type*) := (map : A → B) (resp_pt : map (Point A) = Point B) open pmap namespace pointed abbreviation respect_pt [unfold 3] := @pmap.resp_pt notation `map₊` := pmap infix ` →* `:30 := pmap attribute pmap.map [coercion] variables {A B C D : Type*} {f g h : A →* B} definition pmap_eq (r : Πa, f a = g a) (s : respect_pt f = (r pt) ⬝ respect_pt g) : f = g := begin cases f with f p, cases g with g q, esimp at *, fapply apo011 pmap.mk, { exact eq_of_homotopy r}, { apply concato_eq, apply pathover_eq_Fl, apply inv_con_eq_of_eq_con, rewrite [ap_eq_ap10,↑ap10,apd10_eq_of_homotopy,s]} end definition pid [constructor] (A : Type*) : A →* A := pmap.mk id idp definition pcompose [constructor] (g : B →* C) (f : A →* B) : A →* C := pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g) infixr ` ∘* `:60 := pcompose structure phomotopy (f g : A →* B) := (homotopy : f ~ g) (homotopy_pt : homotopy pt ⬝ respect_pt g = respect_pt f) infix ` ~* `:50 := phomotopy abbreviation to_homotopy_pt [unfold 5] := @phomotopy.homotopy_pt abbreviation to_homotopy [coercion] [unfold 5] (p : f ~* g) : Πa, f a = g a := phomotopy.homotopy p definition passoc (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) := begin fconstructor, intro a, reflexivity, cases A, cases B, cases C, cases D, cases f with f pf, cases g with g pg, cases h with h ph, esimp at *, induction pf, induction pg, induction ph, reflexivity end definition pid_comp (f : A →* B) : pid B ∘* f ~* f := begin fconstructor, { intro a, reflexivity}, { esimp, exact !idp_con ⬝ !ap_id⁻¹} end definition comp_pid (f : A →* B) : f ∘* pid A ~* f := begin fconstructor, { intro a, reflexivity}, { reflexivity} end definition pmap_equiv_left (A : Type) (B : Type*) : A₊ →* B ≃ (A → B) := begin fapply equiv.MK, { intro f a, cases f with f p, exact f (some a)}, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity}, { intro f, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end -- set_option pp.notation false -- definition pmap_equiv_right (A : Type*) (B : Type) -- : (Σ(b : B), map₊ A (pointed.Mk b)) ≃ (A → B) := -- begin -- fapply equiv.MK, -- { intro u a, cases u with b f, cases f with f p, esimp at f, exact f a}, -- { intro f, refine ⟨f pt, _⟩, fapply pmap.mk, -- intro a, esimp, exact f a, -- reflexivity}, -- { intro f, reflexivity}, -- { intro u, cases u with b f, cases f with f p, esimp at *, apply sigma_eq p, -- esimp, apply sorry -- } -- end definition pmap_bool_equiv (B : Type*) : map₊ Bool B ≃ B := begin fapply equiv.MK, { intro f, cases f with f p, exact f tt}, { intro b, fconstructor, intro u, cases u, exact pt, exact b, reflexivity}, { intro b, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B := begin fconstructor, { intro p, exact !respect_pt⁻¹ ⬝ ap f p ⬝ !respect_pt}, { esimp, apply con.left_inv} end definition apn [unfold 3] (n : ℕ) (f : map₊ A B) : Ω[n] A →* Ω[n] B := begin induction n with n IH, { exact f}, { esimp [Iterated_loop_space], exact ap1 IH} end variable (A) definition loop_space_succ_eq_in (n : ℕ) : Ω[succ n] A = Ω[n] (Ω A) := begin induction n with n IH, { reflexivity}, { exact ap Loop_space IH} end definition loop_space_add (n m : ℕ) : Ω[n] (Ω[m] A) = Ω[m+n] (A) := begin induction n with n IH, { reflexivity}, { exact ap Loop_space IH} end definition loop_space_succ_eq_out (n : ℕ) : Ω[succ n] A = Ω(Ω[n] A) := idp variable {A} /- the equality [loop_space_succ_eq_in] preserves concatenation -/ theorem loop_space_succ_eq_in_concat {n : ℕ} (p q : Ω[succ (succ n)] A) : transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) (p ⬝ q) = transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) p ⬝ transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) q := begin rewrite [-+tr_compose, ↑function.compose], rewrite [+@transport_eq_FlFr_D _ _ _ _ Point Point, +con.assoc], apply whisker_left, rewrite [-+con.assoc], apply whisker_right, rewrite [con_inv_cancel_right, ▸*, -ap_con] end definition loop_space_loop_irrel (p : point A = point A) : Ω(Pointed.mk p) = Ω[2] A := begin intros, fapply Pointed_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv} end definition iterated_loop_space_loop_irrel (n : ℕ) (p : point A = point A) : Ω[succ n](Pointed.mk p) = Ω[succ (succ n)] A :> Pointed := calc Ω[succ n](Pointed.mk p) = Ω[n](Ω (Pointed.mk p)) : loop_space_succ_eq_in ... = Ω[n] (Ω[2] A) : loop_space_loop_irrel ... = Ω[2+n] A : loop_space_add ... = Ω[n+2] A : by rewrite [algebra.add.comm] -- TODO: -- definition apn_compose (n : ℕ) (g : B →* C) (f : A →* B) : apn n (g ∘* f) ~* apn n g ∘* apn n f := -- _ definition ap1_compose (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f := begin induction B, induction C, induction g with g pg, induction f with f pf, esimp at *, induction pg, induction pf, fconstructor, { intro p, esimp, apply whisker_left, exact ap_compose g f p ⬝ ap (ap g) !idp_con⁻¹}, { reflexivity} end protected definition phomotopy.refl [refl] (f : A →* B) : f ~* f := begin fconstructor, { intro a, exact idp}, { apply idp_con} end protected definition phomotopy.trans [trans] (p : f ~* g) (q : g ~* h) : f ~* h := begin fconstructor, { intro a, exact p a ⬝ q a}, { induction f, induction g, induction p with p p', induction q with q q', esimp at *, induction p', induction q', esimp, apply con.assoc} end protected definition phomotopy.symm [symm] (p : f ~* g) : g ~* f := begin fconstructor, { intro a, exact (p a)⁻¹}, { induction f, induction p with p p', esimp at *, induction p', esimp, apply inv_con_cancel_left} end infix ` ⬝* `:75 := phomotopy.trans postfix `⁻¹*`:(max+1) := phomotopy.symm definition eq_of_phomotopy (p : f ~* g) : f = g := begin fapply pmap_eq, { intro a, exact p a}, { exact !to_homotopy_pt⁻¹} end definition pwhisker_left (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g := begin fconstructor, { intro a, exact ap h (p a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', reflexivity} end definition pwhisker_right (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h := begin fconstructor, { intro a, exact p (h a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', esimp, exact !idp_con⁻¹} end structure pequiv (A B : Type*) := (to_pmap : A →* B) (is_equiv_to_pmap : is_equiv to_pmap) infix ` ≃* `:25 := pequiv attribute pequiv.to_pmap [coercion] attribute pequiv.is_equiv_to_pmap [instance] definition equiv_of_pequiv [constructor] (f : A ≃* B) : A ≃ B := equiv.mk f _ definition to_pinv [constructor] (f : A ≃* B) : B →* A := pmap.mk f⁻¹ (ap f⁻¹ (respect_pt f)⁻¹ ⬝ !left_inv) definition pua {A B : Type*} (f : A ≃* B) : A = B := Pointed_eq (equiv_of_pequiv f) !respect_pt end pointed
98780f9bfc742b3780493082f4c9ed8e8d475dae
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/fractional_ideal.lean
630cce4cc9454786d275027ba56efbad7771efac
[ "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
51,881
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import algebra.big_operators.finprod import ring_theory.integral_closure import ring_theory.localization.integer import ring_theory.localization.submodule import ring_theory.noetherian import ring_theory.principal_ideal_domain import tactic.field_simp /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal S P` is the type of fractional ideals in `P` * `has_coe_t (ideal R) (fractional_ideal S P)` instance * `comm_semiring (fractional_ideal S P)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal S P)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions). * `fractional_ideal R⁰ K` is the type of fractional ideals in the field of fractions * `has_div (fractional_ideal R⁰ K)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `prod_one_self_div_eq` states that `1 / I` is the inverse of `I` if one exists * `is_noetherian` states that every fractional ideal of a noetherian integral domain is noetherian ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `↑I + ↑J = ↑(I + J)` and `↑⊥ = ↑0`. Many results in fact do not need that `P` is a localization, only that `P` is an `R`-algebra. We omit the `is_localization` parameter whenever this is practical. Similarly, we don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `R⁰`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open is_localization open_locale pointwise open_locale non_zero_divisors section defs variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] variables [algebra R P] variables (S) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R P) := ∃ a ∈ S, ∀ b ∈ I, is_integer R (a • b) variables (S P) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R P // is_fractional S I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] variables [algebra R P] [loc : is_localization S P] /-- Map a fractional ideal `I` to a submodule by forgetting that `∃ a, a I ⊆ R`. This coercion is typically called `coe_to_submodule` in lemma names (or `coe` when the coercion is clear from the context), not to be confused with `is_localization.coe_submodule : ideal R → submodule R P` (which we use to define `coe : ideal R → fractional_ideal S P`, referred to as `coe_ideal` in theorem names). -/ instance : has_coe (fractional_ideal S P) (submodule R P) := ⟨λ I, I.val⟩ protected lemma is_fractional (I : fractional_ideal S P) : is_fractional S (I : submodule R P) := I.prop section set_like instance : set_like (fractional_ideal S P) P := { coe := λ I, ↑(I : submodule R P), coe_injective' := set_like.coe_injective.comp subtype.coe_injective } @[simp] lemma mem_coe {I : fractional_ideal S P} {x : P} : x ∈ (I : submodule R P) ↔ x ∈ I := iff.rfl @[ext] lemma ext {I J : fractional_ideal S P} : (∀ x, x ∈ I ↔ x ∈ J) → I = J := set_like.ext /-- Copy of a `fractional_ideal` with a new underlying set equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : fractional_ideal S P) (s : set P) (hs : s = ↑p) : fractional_ideal S P := ⟨submodule.copy p s hs, by { convert p.is_fractional, ext, simp only [hs], refl }⟩ end set_like @[simp] lemma val_eq_coe (I : fractional_ideal S P) : I.val = I := rfl @[simp, norm_cast] lemma coe_mk (I : submodule R P) (hI : is_fractional S I) : (subtype.mk I hI : submodule R P) = I := rfl lemma coe_to_submodule_injective : function.injective (coe : fractional_ideal S P → submodule R P) := subtype.coe_injective lemma is_fractional_of_le_one (I : submodule R P) (h : I ≤ 1) : is_fractional S I := begin use [1, S.one_mem], intros b hb, rw one_smul, obtain ⟨b', b'_mem, rfl⟩ := h hb, exact set.mem_range_self b', end lemma is_fractional_of_le {I : submodule R P} {J : fractional_ideal S P} (hIJ : I ≤ J) : is_fractional S I := begin obtain ⟨a, a_mem, ha⟩ := J.is_fractional, use [a, a_mem], intros b b_mem, exact ha b (hIJ b_mem) end /-- Map an ideal `I` to a fractional ideal by forgetting `I` is integral. This is a bundled version of `is_localization.coe_submodule : ideal R → submodule R P`, which is not to be confused with the `coe : fractional_ideal S P → submodule R P`, also called `coe_to_submodule` in theorem names. This map is available as a ring hom, called `fractional_ideal.coe_ideal_hom`. -/ -- Is a `coe_t` rather than `coe` to speed up failing inference, see library note [use has_coe_t] instance coe_to_fractional_ideal : has_coe_t (ideal R) (fractional_ideal S P) := ⟨λ I, ⟨coe_submodule P I, is_fractional_of_le_one _ (by simpa using coe_submodule_mono P (le_top : I ≤ ⊤))⟩⟩ @[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal S P) : submodule R P) = coe_submodule P I := rfl variables (S) @[simp] lemma mem_coe_ideal {x : P} {I : ideal R} : x ∈ (I : fractional_ideal S P) ↔ ∃ x', x' ∈ I ∧ algebra_map R P x' = x := mem_coe_submodule _ _ lemma mem_coe_ideal_of_mem {x : R} {I : ideal R} (hx : x ∈ I) : algebra_map R P x ∈ (I : fractional_ideal S P) := (mem_coe_ideal S).mpr ⟨x, hx, rfl⟩ lemma coe_ideal_le_coe_ideal' [is_localization S P] (h : S ≤ non_zero_divisors R) {I J : ideal R} : (I : fractional_ideal S P) ≤ J ↔ I ≤ J := coe_submodule_le_coe_submodule h @[simp] lemma coe_ideal_le_coe_ideal (K : Type*) [comm_ring K] [algebra R K] [is_fraction_ring R K] {I J : ideal R} : (I : fractional_ideal R⁰ K) ≤ J ↔ I ≤ J := is_fraction_ring.coe_submodule_le_coe_submodule instance : has_zero (fractional_ideal S P) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal S P) ↔ x = 0 := ⟨(λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩)⟩ variables {S} @[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal S P) = (⊥ : submodule R P) := submodule.ext $ λ _, mem_zero_iff S @[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal S P) = 0 := rfl variables (P) include loc @[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) : (∃ x', x' ∈ I ∧ algebra_map R P x' = algebra_map R P x) ↔ x ∈ I := ⟨λ ⟨x', hx', eq⟩, is_localization.injective _ h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩ variables {P} lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) : function.injective (coe : ideal R → fractional_ideal S P) := λ I J heq, have ∀ (x : R), algebra_map R P x ∈ (I : fractional_ideal S P) ↔ algebra_map R P x ∈ (J : fractional_ideal S P) := λ x, heq ▸ iff.rfl, ideal.ext (by simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq P h] using this) lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal S P) = 0 ↔ I = (⊥ : ideal R) := ⟨λ h, coe_to_fractional_ideal_injective hS h, λ h, by rw [h, coe_to_fractional_ideal_bot]⟩ lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal S P) ≠ 0 ↔ I ≠ (⊥ : ideal R) := not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS) omit loc lemma coe_to_submodule_eq_bot {I : fractional_ideal S P} : (I : submodule R P) = ⊥ ↔ I = 0 := ⟨λ h, coe_to_submodule_injective (by simp [h]), λ h, by simp [h]⟩ lemma coe_to_submodule_ne_bot {I : fractional_ideal S P} : ↑I ≠ (⊥ : submodule R P) ↔ I ≠ 0 := not_iff_not.mpr coe_to_submodule_eq_bot instance : inhabited (fractional_ideal S P) := ⟨0⟩ instance : has_one (fractional_ideal S P) := ⟨(⊤ : ideal R)⟩ variables (S) @[simp, norm_cast] lemma coe_ideal_top : ((⊤ : ideal R) : fractional_ideal S P) = 1 := rfl lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal S P) ↔ ∃ x' : R, algebra_map R P x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨⟩, h⟩) lemma coe_mem_one (x : R) : algebra_map R P x ∈ (1 : fractional_ideal S P) := (mem_one_iff S).mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal S P) := (mem_one_iff S).mpr ⟨1, ring_hom.map_one _⟩ variables {S} /-- `(1 : fractional_ideal S P)` is defined as the R-submodule `f(R) ≤ P`. However, this is not definitionally equal to `1 : submodule R P`, which is proved in the actual `simp` lemma `coe_one`. -/ lemma coe_one_eq_coe_submodule_top : ↑(1 : fractional_ideal S P) = coe_submodule P (⊤ : ideal R) := rfl @[simp, norm_cast] lemma coe_one : (↑(1 : fractional_ideal S P) : submodule R P) = 1 := by rw [coe_one_eq_coe_submodule_top, coe_submodule_top] section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ @[simp] lemma coe_le_coe {I J : fractional_ideal S P} : (I : submodule R P) ≤ (J : submodule R P) ↔ I ≤ J := iff.rfl lemma zero_le (I : fractional_ideal S P) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal S P) := { bot := 0, bot_le := zero_le } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal S P) = 0 := rfl @[simp] lemma le_zero_iff {I : fractional_ideal S P} : I ≤ 0 ↔ I = 0 := le_bot_iff lemma eq_zero_iff {I : fractional_ideal S P} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, (mem_zero_iff S).mpr (h x hx))) ⟩ lemma _root_.is_fractional.sup {I J : submodule R P} : is_fractional S I → is_fractional S J → is_fractional S (I ⊔ J) | ⟨aI, haI, hI⟩ ⟨aJ, haJ, hJ⟩ := ⟨aI * aJ, S.mul_mem haI haJ, λ b hb, begin rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, rfl⟩, rw smul_add, apply is_integer_add, { rw [mul_smul, smul_comm], exact is_integer_smul (hI bI hbI), }, { rw mul_smul, exact is_integer_smul (hJ bJ hbJ) } end⟩ lemma _root_.is_fractional.inf_right {I : submodule R P} : is_fractional S I → ∀ J, is_fractional S (I ⊓ J) | ⟨aI, haI, hI⟩ J := ⟨aI, haI, λ b hb, begin rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact hI b hbI end⟩ instance : has_inf (fractional_ideal S P) := ⟨λ I J, ⟨I ⊓ J, I.is_fractional.inf_right J⟩⟩ @[simp, norm_cast] lemma coe_inf (I J : fractional_ideal S P) : ↑(I ⊓ J) = (I ⊓ J : submodule R P) := rfl instance : has_sup (fractional_ideal S P) := ⟨λ I J, ⟨I ⊔ J, I.is_fractional.sup J.is_fractional⟩⟩ @[norm_cast] lemma coe_sup (I J : fractional_ideal S P) : ↑(I ⊔ J) = (I ⊔ J : submodule R P) := rfl instance lattice : lattice (fractional_ideal S P) := function.injective.lattice _ subtype.coe_injective coe_sup coe_inf instance : semilattice_sup (fractional_ideal S P) := { ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal S P) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal S P) : I ⊔ J = I + J := rfl @[simp, norm_cast] lemma coe_add (I J : fractional_ideal S P) : (↑(I + J) : submodule R P) = I + J := rfl @[simp, norm_cast] lemma coe_ideal_sup (I J : ideal R) : ↑(I ⊔ J) = (I + J : fractional_ideal S P) := coe_to_submodule_injective $ coe_submodule_sup _ _ _ lemma _root_.is_fractional.nsmul {I : submodule R P} : Π n : ℕ, is_fractional S I → is_fractional S (n • I : submodule R P) | 0 _ := begin rw [zero_smul], convert ((0 : ideal R) : fractional_ideal S P).is_fractional, simp, end | (n + 1) h := begin rw succ_nsmul, exact h.sup (_root_.is_fractional.nsmul n h) end instance : has_scalar ℕ (fractional_ideal S P) := { smul := λ n I, ⟨n • I, I.is_fractional.nsmul n⟩} @[norm_cast] lemma coe_nsmul (n : ℕ) (I : fractional_ideal S P) : (↑(n • I) : submodule R P) = n • I := rfl lemma _root_.is_fractional.mul {I J : submodule R P} : is_fractional S I → is_fractional S J → is_fractional S (I * J : submodule R P) | ⟨aI, haI, hI⟩ ⟨aJ, haJ, hJ⟩ := ⟨aI * aJ, S.mul_mem haI haJ, λ b hb, begin apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [mul_smul, mul_comm m, ← smul_mul_assoc, ← hn', ← algebra.smul_def], apply hI, exact submodule.smul_mem _ _ hm }, { intros x y hx hy, rw smul_add, apply is_integer_add hx hy }, end⟩ lemma _root_.is_fractional.pow {I : submodule R P} (h : is_fractional S I) : ∀ n : ℕ, is_fractional S (I ^ n : submodule R P) | 0 := is_fractional_of_le_one _ (pow_zero _).le | (n + 1) := (pow_succ I n).symm ▸ h.mul (_root_.is_fractional.pow n) /-- `fractional_ideal.mul` is the product of two fractional ideals, used to define the `has_mul` instance. This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`. Elaborated terms involving `fractional_ideal` tend to grow quite large, so by making definitions irreducible, we hope to avoid deep unfolds. -/ @[irreducible] def mul (I J : fractional_ideal S P) : fractional_ideal S P := ⟨I * J, I.is_fractional.mul J.is_fractional⟩ local attribute [semireducible] mul instance : has_mul (fractional_ideal S P) := ⟨λ I J, mul I J⟩ @[simp] lemma mul_eq_mul (I J : fractional_ideal S P) : mul I J = I * J := rfl @[simp, norm_cast] lemma coe_mul (I J : fractional_ideal S P) : (↑(I * J) : submodule R P) = I * J := rfl @[simp, norm_cast] lemma coe_ideal_mul (I J : ideal R) : (↑(I * J) : fractional_ideal S P) = I * J := coe_to_submodule_injective $ coe_submodule_mul _ _ _ lemma mul_left_mono (I : fractional_ideal S P) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal S P) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) lemma mul_mem_mul {I J : fractional_ideal S P} {i j : P} (hi : i ∈ I) (hj : j ∈ J) : i * j ∈ I * J := submodule.mul_mem_mul hi hj lemma mul_le {I J K : fractional_ideal S P} : I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) := submodule.mul_le instance : has_pow (fractional_ideal S P) ℕ := ⟨λ I n, ⟨I^n, I.is_fractional.pow n⟩⟩ @[simp, norm_cast] lemma coe_pow (I : fractional_ideal S P) (n : ℕ) : ↑(I ^ n) = (I ^ n : submodule R P) := rfl @[elab_as_eliminator] protected theorem mul_induction_on {I J : fractional_ideal S P} {C : P → Prop} {r : P} (hr : r ∈ I * J) (hm : ∀ (i ∈ I) (j ∈ J), C (i * j)) (ha : ∀ x y, C x → C y → C (x + y)) : C r := submodule.mul_induction_on hr hm ha instance : comm_semiring (fractional_ideal S P) := function.injective.comm_semiring _ subtype.coe_injective coe_zero coe_one coe_add coe_mul (λ _ _, coe_nsmul _ _) coe_pow section order lemma add_le_add_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) : J' + I ≤ J' + J := sup_le_sup_left hIJ J' lemma mul_le_mul_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) : J' * I ≤ J' * J := mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj)) lemma le_self_mul_self {I : fractional_ideal S P} (hI: 1 ≤ I) : I ≤ I * I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma mul_self_le_self {I : fractional_ideal S P} (hI: I ≤ 1) : I * I ≤ I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal S P) ≤ 1 := λ x hx, let ⟨y, _, hy⟩ := (fractional_ideal.mem_coe_ideal S).mp hx in (fractional_ideal.mem_one_iff S).mpr ⟨y, hy⟩ lemma le_one_iff_exists_coe_ideal {J : fractional_ideal S P} : J ≤ (1 : fractional_ideal S P) ↔ ∃ (I : ideal R), ↑I = J := begin split, { intro hJ, refine ⟨⟨{x : R | algebra_map R P x ∈ J}, _, _, _⟩, _⟩, { intros a b ha hb, rw [mem_set_of_eq, ring_hom.map_add], exact J.val.add_mem ha hb }, { rw [mem_set_of_eq, ring_hom.map_zero], exact J.val.zero_mem }, { intros c x hx, rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul, ← algebra.smul_def], exact J.val.smul_mem c hx }, { ext x, split, { rintros ⟨y, hy, eq_y⟩, rwa ← eq_y }, { intro hx, obtain ⟨y, eq_x⟩ := (fractional_ideal.mem_one_iff S).mp (hJ hx), rw ← eq_x at *, exact ⟨y, hx, rfl⟩ } } }, { rintro ⟨I, hI⟩, rw ← hI, apply coe_ideal_le_one }, end variables (S P) /-- `coe_ideal_hom (S : submonoid R) P` is `coe : ideal R → fractional_ideal S P` as a ring hom -/ @[simps] def coe_ideal_hom : ideal R →+* fractional_ideal S P := { to_fun := coe, map_add' := coe_ideal_sup, map_mul' := coe_ideal_mul, map_one' := by rw [ideal.one_eq_top, coe_ideal_top], map_zero' := coe_to_fractional_ideal_bot } lemma coe_ideal_pow (I : ideal R) (n : ℕ) : (↑(I^n) : fractional_ideal S P) = I^n := (fractional_ideal.coe_ideal_hom S P).map_pow _ n open_locale big_operators lemma coe_ideal_finprod [is_localization S P] {α : Sort*} {f : α → ideal R} (hS : S ≤ non_zero_divisors R) : ((∏ᶠ a : α, f a : ideal R) : fractional_ideal S P) = ∏ᶠ a : α, (f a : fractional_ideal S P) := monoid_hom.map_finprod_of_injective (fractional_ideal.coe_ideal_hom S P).to_monoid_hom (fractional_ideal.coe_to_fractional_ideal_injective hS) f end order variables {P' : Type*} [comm_ring P'] [algebra R P'] [loc' : is_localization S P'] variables {P'' : Type*} [comm_ring P''] [algebra R P''] [loc'' : is_localization S P''] lemma _root_.is_fractional.map (g : P →ₐ[R] P') {I : submodule R P} : is_fractional S I → is_fractional S (submodule.map g.to_linear_map I) | ⟨a, a_nonzero, hI⟩ := ⟨a, a_nonzero, λ b hb, begin obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'] end⟩ /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : P →ₐ[R] P') : fractional_ideal S P → fractional_ideal S P' := λ I, ⟨submodule.map g.to_linear_map I, I.is_fractional.map g⟩ @[simp, norm_cast] lemma coe_map (g : P →ₐ[R] P') (I : fractional_ideal S P) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma mem_map {I : fractional_ideal S P} {g : P →ₐ[R] P'} {y : P'} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := submodule.mem_map variables (I J : fractional_ideal S P) (g : P →ₐ[R] P') @[simp] lemma map_id : I.map (alg_hom.id _ _) = I := coe_to_submodule_injective (submodule.map_id I) @[simp] lemma map_comp (g' : P' →ₐ[R] P'') : I.map (g'.comp g) = (I.map g).map g' := coe_to_submodule_injective (submodule.map_comp g.to_linear_map g'.to_linear_map I) @[simp, norm_cast] lemma map_coe_ideal (I : ideal R) : (I : fractional_ideal S P).map g = I := begin ext x, simp only [mem_coe_ideal], split, { rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩, exact ⟨y, hy, (g.commutes y).symm⟩ }, { rintro ⟨y, hy, rfl⟩, exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ }, end @[simp] lemma map_one : (1 : fractional_ideal S P).map g = 1 := map_coe_ideal g ⊤ @[simp] lemma map_zero : (0 : fractional_ideal S P).map g = 0 := map_coe_ideal g 0 @[simp] lemma map_add : (I + J).map g = I.map g + J.map g := coe_to_submodule_injective (submodule.map_sup _ _ _) @[simp] lemma map_mul : (I * J).map g = I.map g * J.map g := coe_to_submodule_injective (submodule.map_mul _ _ _) @[simp] lemma map_map_symm (g : P ≃ₐ[R] P') : (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I := by rw [←map_comp, g.symm_comp, map_id] @[simp] lemma map_symm_map (I : fractional_ideal S P') (g : P ≃ₐ[R] P') : (I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I := by rw [←map_comp, g.comp_symm, map_id] lemma map_mem_map {f : P →ₐ[R] P'} (h : function.injective f) {x : P} {I : fractional_ideal S P} : f x ∈ map f I ↔ x ∈ I := mem_map.trans ⟨λ ⟨x', hx', x'_eq⟩, h x'_eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩ lemma map_injective (f : P →ₐ[R] P') (h : function.injective f) : function.injective (map f : fractional_ideal S P → fractional_ideal S P') := λ I J hIJ, fractional_ideal.ext (λ x, (fractional_ideal.map_mem_map h).symm.trans (hIJ.symm ▸ fractional_ideal.map_mem_map h)) /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : P ≃ₐ[R] P') : fractional_ideal S P ≃+* fractional_ideal S P' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma coe_fun_map_equiv (g : P ≃ₐ[R] P') : (map_equiv g : fractional_ideal S P → fractional_ideal S P') = map g := rfl @[simp] lemma map_equiv_apply (g : P ≃ₐ[R] P') (I : fractional_ideal S P) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_symm (g : P ≃ₐ[R] P') : ((map_equiv g).symm : fractional_ideal S P' ≃+* _) = map_equiv g.symm := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal S P) := ring_equiv.ext (λ x, by simp) lemma is_fractional_span_iff {s : set P} : is_fractional S (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → is_integer R (a • b) := ⟨λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (by { rw smul_zero, exact is_integer_zero }) (λ x y hx hy, by { rw smul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw smul_comm, exact is_integer_smul hx })⟩⟩ include loc lemma is_fractional_of_fg {I : submodule R P} (hI : I.fg) : is_fractional S I := begin rcases hI with ⟨I, rfl⟩, rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩, rw is_fractional_span_iff, exact ⟨s, hs1, hs⟩, end omit loc lemma mem_span_mul_finite_of_mem_mul {I J : fractional_ideal S P} {x : P} (hx : x ∈ I * J) : ∃ (T T' : finset P), (T : set P) ⊆ I ∧ (T' : set P) ⊆ J ∧ x ∈ span R (T * T' : set P) := submodule.mem_span_mul_finite_of_mem_mul (by simpa using mem_coe.mpr hx) variables (S) lemma coe_ideal_fg (inj : function.injective (algebra_map R P)) (I : ideal R) : fg ((I : fractional_ideal S P) : submodule R P) ↔ I.fg := coe_submodule_fg _ inj _ variables {S} lemma fg_unit (I : (fractional_ideal S P)ˣ) : fg (I : submodule R P) := begin have : (1 : P) ∈ (I * ↑I⁻¹ : fractional_ideal S P), { rw units.mul_inv, exact one_mem_one _ }, obtain ⟨T, T', hT, hT', one_mem⟩ := mem_span_mul_finite_of_mem_mul this, refine ⟨T, submodule.span_eq_of_le _ hT _⟩, rw [← one_mul ↑I, ← mul_one (span R ↑T)], conv_rhs { rw [← fractional_ideal.coe_one, ← units.mul_inv I, fractional_ideal.coe_mul, mul_comm ↑↑I, ← mul_assoc] }, refine submodule.mul_le_mul_left (le_trans _ (submodule.mul_le_mul_right (submodule.span_le.mpr hT'))), rwa [submodule.one_le, submodule.span_mul_span] end lemma fg_of_is_unit (I : fractional_ideal S P) (h : is_unit I) : fg (I : submodule R P) := by { rcases h with ⟨I, rfl⟩, exact fg_unit I } lemma _root_.ideal.fg_of_is_unit (inj : function.injective (algebra_map R P)) (I : ideal R) (h : is_unit (I : fractional_ideal S P)) : I.fg := by { rw ← coe_ideal_fg S inj I, exact fg_of_is_unit I h } variables (S P P') include loc loc' /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `P` and in `P'` -/ @[irreducible] noncomputable def canonical_equiv : fractional_ideal S P ≃+* fractional_ideal S P' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _, ..ring_equiv_of_ring_equiv P P' (ring_equiv.refl R) (show S.map _ = S, by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } @[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal S P} {x : P'} : x ∈ canonical_equiv S P P' I ↔ ∃ y ∈ I, is_localization.map P' (ring_hom.id R) (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) (y : P) = x := begin rw [canonical_equiv, map_equiv_apply, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ end @[simp] lemma canonical_equiv_symm : (canonical_equiv S P P').symm = canonical_equiv S P' P := ring_equiv.ext $ λ I, set_like.ext_iff.mpr $ λ x, by { rw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv, ring_equiv.coe_mk, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ } @[simp] lemma canonical_equiv_flip (I) : canonical_equiv S P P' (canonical_equiv S P' P I) = I := by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply] end semiring section is_fraction_ring /-! ### `is_fraction_ring` section This section concerns fractional ideals in the field of fractions, i.e. the type `fractional_ideal R⁰ K` where `is_fraction_ring R K`. -/ variables {K K' : Type*} [field K] [field K'] variables [algebra R K] [is_fraction_ring R K] [algebra R K'] [is_fraction_ring R K'] variables {I J : fractional_ideal R⁰ K} (h : K →ₐ[R] K') /-- Nonzero fractional ideals contain a nonzero integer. -/ lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) : ∃ x ≠ (0 : R), algebra_map R K x ∈ I := begin obtain ⟨y, y_mem, y_not_mem⟩ := set_like.exists_of_lt (by simpa only using bot_lt_iff_ne_bot.mpr hI), have y_ne_zero : y ≠ 0 := by simpa using y_not_mem, obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y, refine ⟨x, _, _⟩, { rw [ne.def, ← @is_fraction_ring.to_map_eq_zero_iff R _ K, hx, algebra.smul_def], exact mul_ne_zero (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors z.2) y_ne_zero }, { rw hx, exact smul_mem _ _ y_mem } end lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := begin obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI, contrapose! x_ne_zero with map_eq_zero, refine is_fraction_ring.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)), exact ⟨algebra_map R K x, hx, h.commutes x⟩, end @[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨imp_of_not_imp_not _ _ (map_ne_zero _), λ hI, hI.symm ▸ map_zero h⟩ lemma coe_ideal_injective : function.injective (coe : ideal R → fractional_ideal R⁰ K) := injective_of_le_imp_le _ (λ _ _, (coe_ideal_le_coe_ideal _).mp) @[simp] lemma coe_ideal_eq_zero_iff {I : ideal R} : (I : fractional_ideal R⁰ K) = 0 ↔ I = ⊥ := coe_ideal_injective.eq_iff lemma coe_ideal_ne_zero_iff {I : ideal R} : (I : fractional_ideal R⁰ K) ≠ 0 ↔ I ≠ ⊥ := not_iff_not.mpr coe_ideal_eq_zero_iff lemma coe_ideal_ne_zero {I : ideal R} (hI : I ≠ ⊥) : (I : fractional_ideal R⁰ K) ≠ 0 := coe_ideal_ne_zero_iff.mpr hI @[simp] lemma coe_ideal_eq_one_iff {I : ideal R} : (I : fractional_ideal R⁰ K) = 1 ↔ I = 1 := by simpa only [ideal.one_eq_top] using coe_ideal_injective.eq_iff end is_fraction_ring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {R₁ : Type*} [comm_ring R₁] {K : Type*} [field K] variables [algebra R₁ K] [frac : is_fraction_ring R₁ K] instance : nontrivial (fractional_ideal R₁⁰ K) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal R₁⁰ K) := by { rw ← (algebra_map R₁ K).map_one, simpa only [h] using coe_mem_one R₁⁰ 1 }, one_ne_zero ((mem_zero_iff _).mp this)⟩⟩ lemma ne_zero_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal R₁⁰ K) _ _ (by { convert h, simp [hI], }) variables [is_domain R₁] include frac lemma _root_.is_fractional.div_of_nonzero {I J : submodule R₁ K} : is_fractional R₁⁰ I → is_fractional R₁⁰ J → J ≠ 0 → is_fractional R₁⁰ (I / J) | ⟨aI, haI, hI⟩ ⟨aJ, haJ, hJ⟩ h := begin obtain ⟨y, mem_J, not_mem_zero⟩ := set_like.exists_of_lt (by simpa only using bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : algebra_map R₁ K aJ * y = 0, { rw [← algebra.smul_def, ←hy', y'_eq_zero, ring_hom.map_zero] }, have y_zero := (mul_eq_zero.mp this).resolve_left (mt ((injective_iff_map_eq_zero (algebra_map R₁ K)).1 (is_fraction_ring.injective _ _) _) (mem_non_zero_divisors_iff_ne_zero.mp haJ)), apply not_mem_zero, simpa only using (mem_zero_iff R₁⁰).mpr y_zero, }, intros b hb, convert hI _ (hb _ (submodule.smul_mem _ aJ mem_J)) using 1, rw [← hy', mul_comm b, ← algebra.smul_def, mul_smul] end lemma fractional_div_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : is_fractional R₁⁰ (I / J : submodule R₁ K) := I.is_fractional.div_of_nonzero J.is_fractional $ λ H, h $ coe_to_submodule_injective $ H.trans coe_zero.symm noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal R₁⁰ K) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I / J, fractional_div_of_nonzero h⟩ ⟩ variables {I J : fractional_ideal R₁⁰ K} [ J ≠ 0 ] @[simp] lemma div_zero {I : fractional_ideal R₁⁰ K} : I / 0 = 0 := dif_pos rfl lemma div_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (I / J) = ⟨I / J, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] lemma coe_div {I J : fractional_ideal R₁⁰ K} (hJ : J ≠ 0) : (↑(I / J) : submodule R₁ K) = ↑I / (↑J : submodule R₁ K) := congr_arg _ (dif_neg hJ) lemma mem_div_iff_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by { rw div_nonzero h, exact submodule.mem_div_iff_forall_mul_mem } lemma mul_one_div_le_one {I : fractional_ideal R₁⁰ K} : I * (1 / I) ≤ 1 := begin by_cases hI : I = 0, { rw [hI, div_zero, mul_zero], exact zero_le 1 }, { rw [← coe_le_coe, coe_mul, coe_div hI, coe_one], apply submodule.mul_one_div_le_one }, end lemma le_self_mul_one_div {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * (1 / I) := begin by_cases hI_nz : I = 0, { rw [hI_nz, div_zero, mul_zero], exact zero_le 0 }, { rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one], rw [← coe_le_coe, coe_one] at hI, exact submodule.le_self_mul_one_div hI }, end lemma le_div_iff_of_nonzero {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J := ⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx), λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩ lemma le_div_iff_mul_le {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := begin rw div_nonzero hJ', convert submodule.le_div_iff_mul_le using 1, rw [← coe_mul, coe_le_coe] end @[simp] lemma div_one {I : fractional_ideal R₁⁰ K} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal R₁⁰ K) _ _)], ext, split; intro h, { simpa using mem_div_iff_forall_mul_mem.mp h 1 ((algebra_map R₁ K).map_one ▸ coe_mem_one R₁⁰ 1) }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, rfl⟩, rw mul_comm, convert submodule.smul_mem _ y' h, exact (algebra.smul_def _ _).symm } end theorem eq_one_div_of_mul_eq_one_right (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = 1 / I := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply mul_left_mono I, apply (le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact mul_mem_mul hx hy, end theorem mul_div_self_cancel_iff {I : fractional_ideal R₁⁰ K} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨(1 / I), h⟩, λ ⟨J, hJ⟩, by rwa [← eq_one_div_of_mul_eq_one_right I J hJ]⟩ variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_div (I J : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h := begin by_cases H : J = 0, { rw [H, div_zero, map_zero, div_zero] }, { apply coe_to_submodule_injective, simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] } end @[simp] lemma map_one_div (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h := by rw [map_div, map_one] end quotient section field variables {R₁ K L : Type*} [comm_ring R₁] [is_domain R₁] [field K] [field L] variables [algebra R₁ K] [is_fraction_ring R₁ K] [algebra K L] [is_fraction_ring K L] lemma eq_zero_or_one (I : fractional_ideal K⁰ L) : I = 0 ∨ I = 1 := begin rw or_iff_not_imp_left, intro hI, simp_rw [@set_like.ext_iff _ _ _ I 1, fractional_ideal.mem_one_iff], intro x, split, { intro x_mem, obtain ⟨n, d, rfl⟩ := is_localization.mk'_surjective K⁰ x, refine ⟨n / d, _⟩, rw [ring_hom.map_div, is_fraction_ring.mk'_eq_div] }, { rintro ⟨x, rfl⟩, obtain ⟨y, y_ne, y_mem⟩ := fractional_ideal.exists_ne_zero_mem_is_integer hI, rw [← div_mul_cancel x y_ne, ring_hom.map_mul, ← algebra.smul_def], exact submodule.smul_mem I _ y_mem } end lemma eq_zero_or_one_of_is_field (hF : is_field R₁) (I : fractional_ideal R₁⁰ K) : I = 0 ∨ I = 1 := begin letI : field R₁ := hF.to_field, -- TODO can this be less ugly? exact @eq_zero_or_one R₁ K _ _ _ (by { unfreezingI {cases _inst_4}, convert _inst_9 }) I end end field section principal_ideal_ring variables {R₁ : Type*} [comm_ring R₁] {K : Type*} [field K] variables [algebra R₁ K] [is_fraction_ring R₁ K] open_locale classical variables (R₁) /-- `fractional_ideal.span_finset R₁ s f` is the fractional ideal of `R₁` generated by `f '' s`. -/ @[simps] def span_finset {ι : Type*} (s : finset ι) (f : ι → K) : fractional_ideal R₁⁰ K := ⟨submodule.span R₁ (f '' s), begin obtain ⟨a', ha'⟩ := is_localization.exist_integer_multiples R₁⁰ s f, refine ⟨a', a'.2, λ x hx, submodule.span_induction hx _ _ _ _⟩, { rintro _ ⟨i, hi, rfl⟩, exact ha' i hi }, { rw smul_zero, exact is_localization.is_integer_zero }, { intros x y hx hy, rw smul_add, exact is_localization.is_integer_add hx hy }, { intros c x hx, rw smul_comm, exact is_localization.is_integer_smul hx } end⟩ variables {R₁} @[simp] lemma span_finset_eq_zero {ι : Type*} {s : finset ι} {f : ι → K} : span_finset R₁ s f = 0 ↔ ∀ j ∈ s, f j = 0 := by simp only [← coe_to_submodule_injective.eq_iff, span_finset_coe, coe_zero, submodule.span_eq_bot, set.mem_image, finset.mem_coe, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] lemma span_finset_ne_zero {ι : Type*} {s : finset ι} {f : ι → K} : span_finset R₁ s f ≠ 0 ↔ ∃ j ∈ s, f j ≠ 0 := by simp open submodule.is_principal include loc lemma is_fractional_span_singleton (x : P) : is_fractional S (span R {x} : submodule R P) := let ⟨a, ha⟩ := exists_integer_multiple S x in is_fractional_span_iff.mpr ⟨a, a.2, λ x' hx', (set.mem_singleton_iff.mp hx').symm ▸ ha⟩ variables (S) /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ @[irreducible] def span_singleton (x : P) : fractional_ideal S P := ⟨span R {x}, is_fractional_span_singleton x⟩ local attribute [semireducible] span_singleton @[simp] lemma coe_span_singleton (x : P) : (span_singleton S x : submodule R P) = span R {x} := rfl @[simp] lemma mem_span_singleton {x y : P} : x ∈ span_singleton S y ↔ ∃ (z : R), z • y = x := submodule.mem_span_singleton lemma mem_span_singleton_self (x : P) : x ∈ span_singleton S x := (mem_span_singleton S).mpr ⟨1, one_smul _ _⟩ variables {S} lemma span_singleton_eq_span_singleton [no_zero_smul_divisors R P] {x y : P} : span_singleton S x = span_singleton S y ↔ ∃ z : Rˣ, z • x = y := by { rw [← submodule.span_singleton_eq_span_singleton], exact subtype.mk_eq_mk } lemma eq_span_singleton_of_principal (I : fractional_ideal S P) [is_principal (I : submodule R P)] : I = span_singleton S (generator (I : submodule R P)) := coe_to_submodule_injective (span_singleton_generator ↑I).symm lemma is_principal_iff (I : fractional_ideal S P) : is_principal (I : submodule R P) ↔ ∃ x, I = span_singleton S x := ⟨λ h, ⟨@generator _ _ _ _ _ ↑I h, @eq_span_singleton_of_principal _ _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton _ x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton S (0 : P) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm] } lemma span_singleton_eq_zero_iff {y : P} : span_singleton S y = 0 ↔ y = 0 := ⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ lemma span_singleton_ne_zero_iff {y : P} : span_singleton S y ≠ 0 ↔ y ≠ 0 := not_congr span_singleton_eq_zero_iff @[simp] lemma span_singleton_one : span_singleton S (1 : P) = 1 := begin ext, refine (mem_span_singleton S).trans ((exists_congr _).trans (mem_one_iff S).symm), intro x', rw [algebra.smul_def, mul_one] end @[simp] lemma span_singleton_mul_span_singleton (x y : P) : span_singleton S x * span_singleton S y = span_singleton S (x * y) := begin apply coe_to_submodule_injective, simp only [coe_mul, coe_span_singleton, span_mul_span, singleton_mul_singleton], end @[simp] lemma span_singleton_pow (x : P) (n : ℕ) : span_singleton S x ^ n = span_singleton S (x ^ n) := begin induction n with n hn, { rw [pow_zero, pow_zero, span_singleton_one] }, { rw [pow_succ, hn, span_singleton_mul_span_singleton, pow_succ] } end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(ideal.span {x} : ideal R) : fractional_ideal S P) = span_singleton S (algebra_map R P x) := begin ext y, refine (mem_coe_ideal S).trans (iff.trans _ (mem_span_singleton S).symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy', use x', rw [smul_eq_mul, ring_hom.map_mul, algebra.smul_def] }, { rintros ⟨y', rfl⟩, refine ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, _⟩, rw [ring_hom.map_mul, algebra.smul_def] } end @[simp] lemma canonical_equiv_span_singleton {P'} [comm_ring P'] [algebra R P'] [is_localization S P'] (x : P) : canonical_equiv S P P' (span_singleton S x) = span_singleton S (is_localization.map P' (ring_hom.id R) (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) x) := begin apply set_like.ext_iff.mpr, intro y, split; intro h, { rw mem_span_singleton, obtain ⟨x', hx', rfl⟩ := (mem_canonical_equiv_apply _ _ _).mp h, obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp hx', use z, rw is_localization.map_smul, refl }, { rw mem_canonical_equiv_apply, obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp h, use z • x, use (mem_span_singleton _).mpr ⟨z, rfl⟩, simp [is_localization.map_smul] } end lemma mem_singleton_mul {x y : P} {I : fractional_ideal S P} : y ∈ span_singleton S x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply fractional_ideal.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := (mem_span_singleton S).mp hx', use [a • y', submodule.smul_mem I a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', submodule.add_mem I hy hy', (mul_add _ _ _).symm⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul ((mem_span_singleton S).mpr ⟨1, one_smul _ _⟩) hy' } end omit loc variables (K) lemma mk'_mul_coe_ideal_eq_coe_ideal {I J : ideal R₁} {x y : R₁} (hy : y ∈ R₁⁰) : span_singleton R₁⁰ (is_localization.mk' K x ⟨y, hy⟩) * I = (J : fractional_ideal R₁⁰ K) ↔ ideal.span {x} * I = ideal.span {y} * J := begin have inj : function.injective (coe : ideal R₁ → fractional_ideal R₁⁰ K) := fractional_ideal.coe_ideal_injective, have : span_singleton R₁⁰ (is_localization.mk' _ (1 : R₁) ⟨y, hy⟩) * span_singleton R₁⁰ (algebra_map R₁ K y) = 1, { rw [span_singleton_mul_span_singleton, mul_comm, ← is_localization.mk'_eq_mul_mk'_one, is_localization.mk'_self, span_singleton_one] }, let y' : (fractional_ideal R₁⁰ K)ˣ := units.mk_of_mul_eq_one _ _ this, have coe_y' : ↑y' = span_singleton R₁⁰ (is_localization.mk' K (1 : R₁) ⟨y, hy⟩) := rfl, refine iff.trans _ (y'.mul_right_inj.trans inj.eq_iff), rw [coe_y', coe_ideal_mul, coe_ideal_span_singleton, coe_ideal_mul, coe_ideal_span_singleton, ←mul_assoc, span_singleton_mul_span_singleton, ←mul_assoc, span_singleton_mul_span_singleton, mul_comm (mk' _ _ _), ← is_localization.mk'_eq_mul_mk'_one, mul_comm (mk' _ _ _), ← is_localization.mk'_eq_mul_mk'_one, is_localization.mk'_self, span_singleton_one, one_mul], end variables {K} lemma span_singleton_mul_coe_ideal_eq_coe_ideal {I J : ideal R₁} {z : K} : span_singleton R₁⁰ z * (I : fractional_ideal R₁⁰ K) = J ↔ ideal.span {((is_localization.sec R₁⁰ z).1 : R₁)} * I = ideal.span {(is_localization.sec R₁⁰ z).2} * J := -- `erw` to deal with the distinction between `y` and `⟨y.1, y.2⟩` by erw [← mk'_mul_coe_ideal_eq_coe_ideal K (is_localization.sec R₁⁰ z).2.prop, is_localization.mk'_sec K z] variables [is_domain R₁] lemma one_div_span_singleton (x : K) : 1 / span_singleton R₁⁰ x = span_singleton R₁⁰ (x⁻¹) := if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one_right _ _ (by simp [h])).symm @[simp] lemma div_span_singleton (J : fractional_ideal R₁⁰ K) (d : K) : J / span_singleton R₁⁰ d = span_singleton R₁⁰ (d⁻¹) * J := begin rw ← one_div_span_singleton, by_cases hd : d = 0, { simp only [hd, span_singleton_zero, div_zero, zero_mul] }, have h_spand : span_singleton R₁⁰ d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd, apply le_antisymm, { intros x hx, rw [← mem_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx, specialize hx d (mem_span_singleton_self R₁⁰ d), have h_xd : x = d⁻¹ * (x * d), { field_simp }, rw [← mem_coe, coe_mul, one_div_span_singleton, h_xd], exact submodule.mul_mem_mul (mem_span_singleton_self R₁⁰ _) hx }, { rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton, span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one], exact le_refl J }, end lemma exists_eq_span_singleton_mul (I : fractional_ideal R₁⁰ K) : ∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton R₁⁰ (algebra_map R₁ K a)⁻¹ * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.is_fractional, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero : algebra_map R₁ K a_inv ≠ 0 := mt is_fraction_ring.to_map_eq_zero_iff.mp nonzero, refine ⟨a_inv, submodule.comap (algebra.linear_map R₁ K) ↑(span_singleton R₁⁰ (algebra_map R₁ K a_inv) * I), nonzero, ext (λ x, iff.trans ⟨_, _⟩ mem_singleton_mul.symm)⟩, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, rw algebra.smul_def at hx', refine ⟨algebra_map R₁ K x', (mem_coe_ideal _).mpr ⟨x', mem_singleton_mul.mpr _, rfl⟩, _⟩, { exact ⟨x, hx, hx'⟩ }, { rw [hx', ← mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := (mem_coe_ideal _).mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw algebra.linear_map_apply at hx', rwa [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } end instance is_principal {R} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [algebra R K] [is_fraction_ring R K] (I : fractional_ideal R⁰ K) : (I : submodule R K).is_principal := begin obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I, use (algebra_map R K a)⁻¹ * algebra_map R K (generator aI), suffices : I = span_singleton R⁰ ((algebra_map R K a)⁻¹ * algebra_map R K (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [ideal.submodule_span_eq, coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end include loc lemma le_span_singleton_mul_iff {x : P} {I J : fractional_ideal S P} : I ≤ span_singleton S x * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (hzI : zI ∈ I), zI ∈ span_singleton _ x * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI, by simp only [fractional_ideal.mem_singleton_mul, eq_comm] lemma span_singleton_mul_le_iff {x : P} {I J : fractional_ideal S P} : span_singleton _ x * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := begin simp only [fractional_ideal.mul_le, fractional_ideal.mem_singleton_mul, fractional_ideal.mem_span_singleton], split, { intros h zI hzI, exact h x ⟨1, one_smul _ _⟩ zI hzI }, { rintros h _ ⟨z, rfl⟩ zI hzI, rw [algebra.smul_mul_assoc], exact submodule.smul_mem J.1 _ (h zI hzI) }, end lemma eq_span_singleton_mul {x : P} {I J : fractional_ideal S P} : I = span_singleton _ x * J ↔ (∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ ∀ z ∈ J, x * z ∈ I := by simp only [le_antisymm_iff, fractional_ideal.le_span_singleton_mul_iff, fractional_ideal.span_singleton_mul_le_iff] end principal_ideal_ring variables {R₁ : Type*} [comm_ring R₁] variables {K : Type*} [field K] [algebra R₁ K] [frac : is_fraction_ring R₁ K] local attribute [instance] classical.prop_decidable lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal R₁⁰ K) := is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal R₁⁰ K)), by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot }) lemma is_noetherian_iff {I : fractional_ideal R₁⁰ K} : is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ K).fg := is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩ lemma is_noetherian_coe_to_fractional_ideal [_root_.is_noetherian_ring R₁] (I : ideal R₁) : is_noetherian R₁ (I : fractional_ideal R₁⁰ K) := begin rw is_noetherian_iff, intros J hJ, obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one), exact (is_noetherian.noetherian J).map _, end include frac variables [is_domain R₁] lemma is_noetherian_span_singleton_inv_to_map_mul (x : R₁) {I : fractional_ideal R₁⁰ K} (hI : is_noetherian R₁ I) : is_noetherian R₁ (span_singleton R₁⁰ (algebra_map R₁ K x)⁻¹ * I : fractional_ideal R₁⁰ K) := begin by_cases hx : x = 0, { rw [hx, ring_hom.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul], exact is_noetherian_zero }, have h_gx : algebra_map R₁ K x ≠ 0, from mt ((injective_iff_map_eq_zero (algebra_map R₁ K)).mp (is_fraction_ring.injective _ _) x) hx, have h_spanx : span_singleton R₁⁰ (algebra_map R₁ K x) ≠ 0, from span_singleton_ne_zero_iff.mpr h_gx, rw is_noetherian_iff at ⊢ hI, intros J hJ, rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ, obtain ⟨s, hs⟩ := hI _ hJ, use s * {(algebra_map R₁ K x)⁻¹}, rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton R₁⁰, ← coe_mul, mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx, span_singleton_one, mul_one], end /-- Every fractional ideal of a noetherian integral domain is noetherian. -/ theorem is_noetherian [_root_.is_noetherian_ring R₁] (I : fractional_ideal R₁⁰ K) : is_noetherian R₁ I := begin obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I, apply is_noetherian_span_singleton_inv_to_map_mul, apply is_noetherian_coe_to_fractional_ideal, end section adjoin include loc omit frac variables {R P} (S) (x : P) (hx : is_integral R x) /-- `A[x]` is a fractional ideal for every integral `x`. -/ lemma is_fractional_adjoin_integral : is_fractional S (algebra.adjoin R ({x} : set P)).to_submodule := is_fractional_of_fg (fg_adjoin_singleton_of_integral x hx) /-- `fractional_ideal.adjoin_integral (S : submonoid R) x hx` is `R[x]` as a fractional ideal, where `hx` is a proof that `x : P` is integral over `R`. -/ @[simps] def adjoin_integral : fractional_ideal S P := ⟨_, is_fractional_adjoin_integral S x hx⟩ lemma mem_adjoin_integral_self : x ∈ adjoin_integral S x hx := algebra.subset_adjoin (set.mem_singleton x) end adjoin end fractional_ideal
a42e09701a7ffa92b7acc52bc1572d9af1625576
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/functor_categories/whiskering.lean
40cbd4fd5baea3eeb25e324d4f267b14cd403744
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
2,069
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.functor_category import category_theory.tactics.obviously namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ section variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C] (D : Type u₂) [𝒟 : category.{u₂ v₂} D] (E : Type u₃) [ℰ : category.{u₃ v₃} E] include 𝒞 𝒟 ℰ -- set_option trace.tidy true def whiskering_on_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) := { obj := λ F, { obj := λ G, F ⋙ G, map' := λ _ _ α, (nat_trans.id _) ◫ α }, map' := λ F G τ, { app := λ H, { app := λ c, H.map (τ c) } } } def whiskering_on_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) := { obj := λ H, { obj := λ F, F ⋙ H, map' := λ _ _ α, α ◫ (nat_trans.id _) }, map' := λ G H τ, { app := λ F, { app := λ c, τ (F c) } } } end def whisker_on_left_functor {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] (F : C ⥤ D) (E : Type u₃) [ℰ : category.{u₃ v₃} E] : (D ⥤ E) ⥤ (C ⥤ E) := (whiskering_on_left C D E) F def whisker_on_right_functor (C : Type u₁) [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] {E : Type u₃} [ℰ : category.{u₃ v₃} E] (H : D ⥤ E) : (C ⥤ D) ⥤ (C ⥤ E) := (whiskering_on_right C D E) H def whisker_on_left {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] {E : Type u₃} [ℰ : category.{u₃ v₃} E] (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟹ H) : (F ⋙ G) ⟹ (F ⋙ H) := (whisker_on_left_functor F E).map α def whisker_on_right {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] {E : Type u₃} [ℰ : category.{u₃ v₃} E] {G H : C ⥤ D} (α : G ⟹ H) (F : D ⥤ E) : (G ⋙ F) ⟹ (H ⋙ F) := (whisker_on_right_functor C F).map α end category_theory
616837991e583cd1a43b66da80f4049a48af1874
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/matrix/trace.lean
fa68bafdb405f71d4b86b9557c57812579516a68
[ "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
2,350
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import data.matrix.basic /-! # Trace of a matrix This file defines the trace of a matrix, the linear map sending a matrix to the sum of its diagonal entries. See also `linear_algebra.trace` for the trace of an endomorphism. ## Tags matrix, trace, diagonal -/ open_locale big_operators open_locale matrix namespace matrix section trace universes u v w variables {m : Type*} (n : Type*) variables (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M] /-- The diagonal of a square matrix. -/ def diag : (matrix n n M) →ₗ[R] n → M := { to_fun := λ A i, A i i, map_add' := by { intros, ext, refl, }, map_smul' := by { intros, ext, refl, } } variables {n} {R} {M} @[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl @[simp] lemma diag_one [decidable_eq n] : diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_apply_eq] } @[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl variables (n) (R) (M) /-- The trace of a square matrix. -/ def trace [fintype n] : (matrix n n M) →ₗ[R] M := { to_fun := λ A, ∑ i, diag n R M A i, map_add' := by { intros, apply finset.sum_add_distrib, }, map_smul' := by { intros, simp [finset.smul_sum], } } variables {n} {R} {M} [fintype n] [fintype m] @[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = ∑ i, diag n R M A i := rfl lemma trace_apply (A : matrix n n M) : trace n R M A = ∑ i, A i i := rfl @[simp] lemma trace_one [decidable_eq n] : trace n R R 1 = fintype.card n := have h : trace n R R 1 = ∑ i, diag n R R 1 i := rfl, by simp_rw [h, diag_one, finset.sum_const, nsmul_one]; refl @[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl @[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) : trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm lemma trace_mul_comm {S : Type v} [comm_semiring S] (A : matrix m n S) (B : matrix n m S) : trace n S S (B ⬝ A) = trace m S S (A ⬝ B) := by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul] end trace end matrix
2738462435f96905d853485ebdc200f6c2b3e9af
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/friday/manifolds.lean
216ffc21d0b4f46307b1f7c54537e618ca8d2672
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
41,871
lean
import for_mathlib.manifolds noncomputable theory open_locale manifold classical big_operators open set universe u /-! ## Reminder on updating the exercises These instructions are now available at: https://leanprover-community.github.io/lftcm2020/exercises.html To get a new copy of the exercises, run the following commands in your terminal: ``` leanproject get lftcm2020 cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises code lftcm2020 ``` To update your exercise files, run the following commands: ``` cd /path/to/lftcm2020 git pull leanproject get-mathlib-cache ``` Don’t forget to copy the updated files to `src/my_exercises`. -/ /-! ## An overview of manifolds in Lean, discussing design decisions Warning: there are sorries in this section, they are not supposed to be filled! The exercises section start later, and there you will have plenty of sorries to fill. What is a manifold? 1) allow field other than `ℝ` or `ℂ`? 2) allow infinite dimension? 3) allow boundary? 4) allow model space depending on the point of the manifold? Bourbaki: 2, 4 (and just definitions and statements, no proofs!) Lean: 1, 2, 3 Perelman geometrization theorem : any compact connected irreducible 3-manifold can be cut along tori into finitely many pieces, each of which has a _geometric structure_ of finite volume, i.e., it is locally like a model space, with changes of coordinates given locally by the action of a Lie group Typical dynamics theorem : let `M` be a compact manifold, and `f : M → M` a map with property such and such. Then ... Or : Consider a hyperbolic surface of genus `g`, and a random geodesic of length `T`. How many times does it typically self-intersect? Manifold in Lean: * charted space structure, i.e., set of local homeos to a model space. This is data, fixed once and for all (and a typeclass) * compatibility condition, i.e., the change of coordinates should belong to some subgroup of the group of local homeos of the model space. This is Prop (and a typeclass). The same manifold can be at the same time an analytic manifold, a smooth manifold and a topological manifold (with the same fixed atlas). * A charted space is a smooth manifold (with corners) if it is compatible with the smooth groupoid on the model space. To cover uniformly both situations with and without boundary, the smooth groupoid is with respect to a map `I : H → E` (think of `H` as the half-space and `E` the full space), which is the identity in the boundaryless situation, the inclusion in the half-space situation. This map `I` is called a _model with corners_. The most standard ones (identity in `ℝ^n` and inclusion of half-space in `ℝ^n`) have dedicated notations: `𝓡 n` and `𝓡∂ n`. -/ #check charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1) #check has_groupoid (Icc (0 : ℝ) 1) (times_cont_diff_groupoid ∞ (𝓡∂ 1)) #check smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1) -- atlases are not maximal in general #check (times_cont_diff_groupoid ∞ (𝓡∂ 1)).maximal_atlas (Icc (0 : ℝ) 1) -- let's try to put a smooth manifold structure on the sphere -- (we don't have submanifolds yet, but it's coming in the near future) @[derive topological_space] definition sphere (n : ℕ) : Type := metric.sphere (0 : euclidean_space (fin (n+1))) 1 instance (n : ℕ) : has_coe (sphere n) (euclidean_space (fin (n+1))) := ⟨subtype.val⟩ instance (n : ℕ) : charted_space (euclidean_space (fin n)) (sphere n) := { atlas := begin sorry end, chart_at := begin sorry end, mem_chart_source := begin sorry end, chart_mem_atlas := begin sorry end } instance (n : ℕ) : smooth_manifold_with_corners (𝓡 n) (sphere n) := { compatible := begin assume e e' he he', sorry end } -- smooth functions def inc (n : ℕ) : sphere n → euclidean_space (fin (n+1)) := λ p : sphere n, (p : euclidean_space (fin (n+1))) lemma inc_smooth (n : ℕ) : times_cont_mdiff (𝓡 n) (𝓡 (n+1)) ∞ (inc n) := begin rw times_cont_mdiff_iff, split, { exact continuous_subtype_coe, }, { assume x y, sorry } end lemma inc_continuous (n : ℕ) : continuous (inc n) := (inc_smooth n).continuous lemma inc_mdifferentiable (n : ℕ) : mdifferentiable (𝓡 n) (𝓡 (n+1)) (inc n) := (inc_smooth n).mdifferentiable le_top -- tangent space and tangent bundles example (n : ℕ) (p : sphere n) (v : tangent_space (𝓡 n) p) : tangent_bundle (𝓡 n) (sphere n) := ⟨p, v⟩ -- tangent map, derivatives example (n : ℕ) : times_cont_mdiff ((𝓡 n).prod (𝓡 n)) ((𝓡 (n+1)).prod (𝓡 (n+1))) ∞ (tangent_map (𝓡 n) (𝓡 (n+1)) (inc n)) := (inc_smooth n).times_cont_mdiff_tangent_map le_top example (n : ℕ) (f : sphere n → sphere (n^2)) (p : sphere n) (v : tangent_space (𝓡 n) p) : mfderiv (𝓡 n) (𝓡 (n^2)) f p v = (tangent_map (𝓡 n) (𝓡 (n^2)) f ⟨p, v⟩).2 := rfl /- Can you express the sphere eversion theorem, i.e., the fact that there is a smooth isotopy of immersions between the canonical embedding of the sphere `S^2` and `ℝ^3`, and the antipodal embedding? Note that we haven't defined immersions in mathlib, but you can jut require that the fiber derivative is injective everywhere, which is easy to express if you know that the derivative of a function `f` from a manifold of dimension `2` to a manifold of dimension `3` at a point `x` is `mfderiv (𝓡 2) (𝓡 3) f x`. Don't forget to require the global smoothness of the map! You may need to know that the interval `[0,1]`, called `Icc (0 : ℝ) 1` in Lean, already has a manifold (with boundary!) structure, where the corresponding model with corners is called `𝓡∂ 1`. -/ theorem sphere_eversion : ∃ f : (Icc (0 : ℝ) 1) × sphere 2 → euclidean_space (fin 3), times_cont_mdiff ((𝓡∂ 1).prod (𝓡 2)) (𝓡 3) ∞ f ∧ ∀ (t : (Icc (0 : ℝ) 1)), ∀ (p : sphere 2), function.injective (mfderiv (𝓡 2) (𝓡 3) (f ∘ λ y, (t, y)) p) ∧ ∀ (p : sphere 2), f (0, p) = p ∧ ∀ (p : sphere 2), f (1, p) = - p := sorry /- Dicussing three (controversial?) design decisions #### Local homeos What is a local homeo `f` between an open subset of `E` and an open subset of `F`? 1) a map defined on a subtype: `f x` only makes sense for `x : f.source` 2) a map defined on the whole space `E`, but taking values in `option F = F ∪ {junk}`, with `f x = junk` when `x ∉ f.source` 3) a map defined on the whole space `E`, taking values in `F`, and we don't care about its values outside of `f.source`. Just like division by zero! But worse: * issue with 1): you keep intersecting chart domains. But the subtype `u ∩ v` is not the same as the subtype `v ∩ u`, so you keep adding casts everywhere * issue with 2): if you want to say that a chart is smooth, then you define to define smooth functions between `option E` and `option F` when `E` and `F` are vector spaces. All notions need to be redefined with `option`. * issue with 3): it works perfectly well, but it makes mathematicians unhappy/uneasy (and it is *not* equivalent to 1) or 2) when one of the spaces is empty) I picked 3) #### Tangent vectors What is a tangent vector (for a manifold `M` modelled on a vector space `E`)? 1) An equivalence class of germs of curves 2) A derivation 3) Physicist point of view: I don't know what a tangent vector is, but I know in charts. Mathematician's interpretation: equivalence class of `(e, v)` where `e` is a chart at `x`, `v` a vector in the vector space, and `(e, v) ∼ (e', v')` if `D(e' ∘ e ⁻¹) v = v'` 4) ... Issues: 1) Pictures are pretty, but this doesn't bring anything compared to 3) when you go down to details. And what about boundaries, where you can only have a half-curve 2) Need partitions of unity to show that this is local and coincides with the usual point of view. Doesn't work well in finite smoothness, nor in complex manifolds 3) Fine, works in all situations, but requires a lot of work to define the equivalence classes, the topology, check that the topology is compatible with the vector space structure, and so on. In a vector space, the tangent space is not defeq to the vector space itself 4) Pick one favorite chart at `x`, say `e_x`, and *define* the tangent space at `x` to be `E`, but "seen" in the chart `e_x` (this will show up in the definition of the derivative : the derivative of `f : M → M'` at `x` is defined to be the derivative of the map `e_{f x} ∘ f ∘ e_x⁻¹`). Works perfectly fine, but makes mathematicians unhappy/uneasy. (Axiom of choice? In fact we put the choice of `e_x` in the *definition* of charted spaces, so not further choice) I picked 4) #### Smooth functions in manifolds with boundary Usual definition of smooth functions in a half space: extend to a smooth function a little bit beyond the boundary, so one only really needs to speak of smooth functions in open subsets of vector spaces. When you define the derivative, you will need to check that it does not depend on the choice of the extension. Even worse when you want to define the tangent bundle: choose an open extension of your manifold with boundary, and then check that the restriction of the tangent bundle does not depend on the choice of the extension. Very easy when handwaving, nightmare to formalize. (What is the extension of the manifold with boundary? Another type?) Instead, if you define derivatives in (non-open) domains, you can talk of smooth functions in domains, and do everything without extending. Need to know this early enough: when starting to define derivatives, you should already think of manifolds with boundaries! That's what we did in mathlib. Difficulty: if a domain `s` is too small (think `s = ℝ ⊆ ℝ^2`), the values of `f` on `s` do not prescribe uniquely a derivative, so `fderiv_within_at ℝ f s x` may behave badly: derivative of a sum might be different from sum of derivatives, as there is an arbitrary choice to be made. This does not happen with the half-space, as it is large enough: derivatives within domains only work well if the tangent directions span the whole space. Predicate `unique_diff_on` for sets in vector spaces. You won't find this in books! -/ /-! ## Exercises -/ /-! ### Local homeomorphisms Local homeomorphisms are globally defined maps with a globally defined "inverse", but the only relevant set is the *source*, which should be mapped homeomorphically to the *target*. -/ /- Define a local homeomorphism from `ℝ` to `ℝ` which is just `x ↦ -x`, but on `(-1, 1)`. In Lean, the interval `(-1, 1)` is denoted by `Ioo (-1 : ℝ) 1` (where `o` stands for _open_). -/ -- set up a simple helper simp lemma to simplify our life later. @[simp] lemma neg_mem_Ioo_minus_one_one (x : ℝ) : -x ∈ Ioo (-1 : ℝ) 1 ↔ x ∈ Ioo (-1 : ℝ) 1 := begin -- sorry simp [neg_lt, and_comm], -- sorry end def my_first_local_homeo : local_homeomorph ℝ ℝ := { to_fun := λ x, -x, inv_fun := λ x, -x, source := Ioo (-1) 1, target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/, map_source' := begin -- sorry assume x hx, simp [hx], -- sorry end, map_target' := begin -- sorry assume x hx, simp [hx], -- sorry end, left_inv' := begin -- sorry simp, -- sorry end, right_inv' := begin -- sorry simp, -- sorry end, open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/, open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/, continuous_to_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/, continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ } /- Two simple lemmas that will prove useful below. You can leave them sorried if you like. -/ lemma ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : x ≠ 3 := begin -- sorry exact ne_of_lt (lt_trans h.2 (by norm_num)) -- sorry end lemma neg_ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : -x ≠ 3 := begin -- sorry assume h', simp at h, linarith, -- sorry end /- Now, define a second local homeomorphism which is almost like the previous one. You may find the following lemma useful for `continuous_to_fun`: -/ #check continuous_on.congr def my_second_local_homeo : local_homeomorph ℝ ℝ := { to_fun := λ x, if x = 3 then 0 else - x, inv_fun := λ x, -x, source := Ioo (-1) 1, target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/, map_source' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/, map_target' := /- inline sorry -/λ x hx, by simp [hx]/- inline sorry -/, left_inv' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/, right_inv' := /- inline sorry -/λ x hx, by simp [hx, neg_ne_3_of_mem_Ioo hx]/- inline sorry -/, open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/, open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/, continuous_to_fun := begin -- sorry refine continuous_neg.continuous_on.congr (λ x hx, _), simp [hx, ne_3_of_mem_Ioo hx], -- sorry end, continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ } /- Although the two above local homeos are the same for all practical purposes as they coincide where relevant, they are not *equal*: -/ lemma my_first_local_homeo_ne_my_second_local_homeo : my_first_local_homeo ≠ my_second_local_homeo := begin -- sorry assume h, have : my_first_local_homeo 3 = my_second_local_homeo 3, by rw h, simp [my_first_local_homeo, my_second_local_homeo] at this, linarith, -- sorry end /- The right equivalence relation for local homeos is not equality, but `eq_on_source`. Indeed, the two local homeos we have defined above coincide from this point of view. -/ #check local_homeomorph.eq_on_source lemma eq_on_source_my_first_local_homeo_my_second_local_homeo : local_homeomorph.eq_on_source my_first_local_homeo my_second_local_homeo := begin -- sorry refine ⟨rfl, λ x hx, _⟩, simp [my_first_local_homeo, my_second_local_homeo, ne_3_of_mem_Ioo hx], -- sorry end /-! ### An example of a charted space structure on `ℝ` A charted space is a topological space together with a set of local homeomorphisms to a model space, whose sources cover the whole space. For instance, `ℝ` is already endowed with a charted space structure with model space `ℝ`, where the unique chart is the identity: -/ #check charted_space_self ℝ /- For educational purposes only, we will put another charted space structure on `ℝ` using the local homeomorphisms we have constructed above. To avoid using too much structure of `ℝ` (and to avoid confusing Lean), we will work with a copy of `ℝ`, on which we will only register the topology. -/ @[derive topological_space] def myℝ : Type := ℝ instance : charted_space ℝ myℝ := { atlas := { local_homeomorph.refl ℝ, my_first_local_homeo }, chart_at := λ x, if x ∈ Ioo (-1 : ℝ) 1 then my_first_local_homeo else local_homeomorph.refl ℝ, mem_chart_source := begin -- sorry assume x, split_ifs, { exact h }, { exact mem_univ _ } -- sorry end, chart_mem_atlas := begin -- sorry assume x, split_ifs; simp, -- sorry end } /- Now come more interesting bits. We have endowed `myℝ` with a charted space structure, with charts taking values in `ℝ`. We want to say that this is a smooth structure, i.e., the changes of coordinates are smooth. In Lean, this is written with `has_groupoid`. A groupoid is a set of local homeomorphisms of the model space (for example, local homeos that are smooth on their domain). A charted space admits the groupoid as a structure groupoid if all the changes of coordinates belong to the groupoid. There is a difficulty that the definitions are set up to be able to also speak of smooth manifolds with boundary or with corners, so the name of the smooth groupoid on `ℝ` has the slightly strange name `times_cont_diff_groupoid ∞ (model_with_corners_self ℝ ℝ)`. To avoid typing again and again `model_with_corners_self ℝ ℝ`, let us introduce a shortcut -/ abbreviation 𝓡1 := model_with_corners_self ℝ ℝ /- In the library, there are such shortcuts for manifolds modelled on `ℝ^n`, denoted with `𝓡 n`, but for `n = 1` this does not coincide with the above one, as `ℝ^1` (a.k.a. `fin 1 → ℝ`) is not the same as `ℝ`! Still, since they are of the same nature, the notation we have just introduced is very close, compare `𝓡1` with `𝓡 1` (and try not to get confused): -/ instance : has_groupoid myℝ (times_cont_diff_groupoid ∞ 𝓡1) := begin -- in theory, we should prove that all compositions of charts are diffeos, i.e., they are smooth -- and their inverse are smooth. For symmetry reasons, it suffices to check one direction apply has_groupoid_of_pregroupoid, -- take two charts `e` and `e'` assume e e' he he', -- if next line is a little bit slow for your taste, you can replace `simp` with `squeeze_simp` -- and then follow the advice simp [atlas] at he he', dsimp, -- to continue, some hints: -- (1) don't hesitate to use the fact that the restriction of a smooth function to a -- subset is still smooth there (`times_cont_diff.times_cont_diff_on`) -- (2) hopefully, there is a theorem saying that the negation function is smooth. -- you can either try to guess its name, or hope that `suggest` will help you there. -- sorry rcases he with rfl|rfl; rcases he' with rfl|rfl, { exact times_cont_diff_id.times_cont_diff_on }, { exact times_cont_diff_id.neg.times_cont_diff_on }, { exact times_cont_diff_id.neg.times_cont_diff_on }, { convert times_cont_diff_id.times_cont_diff_on, ext x, simp [my_first_local_homeo], }, -- sorry end /- The statement of the previous instance is not very readable. There is a shortcut notation: -/ instance : smooth_manifold_with_corners 𝓡1 myℝ := {} /- We will now study a very simple map from `myℝ` to `ℝ`, the identity. -/ def my_map : myℝ → ℝ := λ x, x /- The map `my_map` is a map going from the type `myℝ` to the type `ℝ`. From the point of view of the kernel of Lean, it is just the identity, but from the point of view of structures on `myℝ` and `ℝ` it might not be trivial, as we have registered different instances on these two types. -/ /- The continuity should be trivial, as the topologies on `myℝ` and `ℝ` are definitionally the same. So `continuous_id` might help. -/ lemma continuous_my_map : continuous my_map := -- sorry continuous_id -- sorry /- Smoothness should not be obvious, though, as the manifold structures are not the same: the atlas on `myℝ` has two elements, while the atlas on `ℝ` has one single element. Note that `myℝ` is not a vector space, nor a normed space, so one can not ask whether `my_map` is smooth in the usual sense (as a map between vector spaces): -/ -- lemma times_cont_diff_my_map : times_cont_diff ℝ ∞ my_map := sorry /- does not make sense (try uncommenting it!) However, we can ask whether `my_map` is a smooth map between manifolds, i.e., whether it is smooth when read in the charts. When we mention the smoothness of a map, we should always specify explicitly the model with corners we are using, because there might be several around (think of a complex manifold that you may want to consider as a real manifold, to talk about functions which are real-smooth but not holomorphic) -/ lemma times_cont_mdiff_my_map : times_cont_mdiff 𝓡1 𝓡1 ∞ my_map := begin -- put things in a nicer form. The simpset `mfld_simps` registers many simplification rules for -- manifolds. `simp` is used heavily in manifold files to bring everything into manageable form. rw times_cont_mdiff_iff, simp only [continuous_my_map] with mfld_simps, -- simp has erased the chart in the target, as it knows that the only chart in the manifold `ℝ` -- is the identity. assume x y, -- sorry simp [my_map, (∘), chart_at], split_ifs, { exact times_cont_diff_id.neg.times_cont_diff_on }, { exact times_cont_diff_id.times_cont_diff_on }, -- sorry end /- Now, let's go to tangent bundles. We have a smooth manifold, so its tangent bundle should also be a smooth manifold. -/ -- the type `tangent_bundle I myℝ` makes sense #check tangent_bundle 𝓡1 myℝ /- The tangent space above a point of `myℝ` is just a one-dimensional vector space (identified with `ℝ`). So, one can prescribe an element of the tangent bundle as a pair (more on this below) -/ example : tangent_bundle 𝓡1 myℝ := ((4 : ℝ), 0) /- Construct the smooth manifold structure on the tangent bundle. Hint: the answer is a one-liner, and this instance is not really needed. -/ instance tangent_bundle_myℝ : smooth_manifold_with_corners (𝓡1.prod 𝓡1) (tangent_bundle 𝓡1 myℝ) := -- sorry by apply_instance -- sorry /- NB: the model space for the tangent bundle to a product manifold or a tangent space is not `ℝ × ℝ`, but a copy called `model_prod ℝ ℝ`. Otherwise, `ℝ × ℝ` would have two charted space structures with model `ℝ × ℝ`, the identity one and the product one, which are not definitionally equal. And this would be bad. -/ #check tangent_bundle.charted_space 𝓡1 myℝ /- A smooth map between manifolds induces a map between their tangent bundles. In `mathlib` this is called the `tangent_map` (you might instead know it as the "differential" or "pushforward" of the map). Let us check that the `tangent_map` of `my_map` is smooth. -/ lemma times_cont_mdiff_tangent_map_my_map : times_cont_mdiff (𝓡1.prod 𝓡1) (𝓡1.prod 𝓡1) ∞ (tangent_map 𝓡1 𝓡1 my_map) := begin -- hopefully, there is a theorem providing the general result, i.e. the tangent map to a smooth -- map is smooth. -- you can either try to guess its name, or hope that `suggest` will help you there. -- sorry exact times_cont_mdiff_my_map.times_cont_mdiff_tangent_map le_top, -- sorry end /- (Harder question) Can you show that this tangent bundle is homeomorphic to `ℝ × ℝ`? You could try to build the homeomorphism by hand, using `tangent_map I I my_map` in one direction and a similar map in the other direction, but it is probably more efficient to use one of the charts of the tangent bundle. Remember, the model space for `tangent_bundle I myℝ` is `model_prod ℝ ℝ`, not `ℝ × ℝ`. But the topologies on `model_prod ℝ ℝ` and `ℝ × ℝ` are the same, so it is by definition good enough to construct a homeomorphism with `model_prod ℝ ℝ`. -/ def my_homeo : tangent_bundle 𝓡1 myℝ ≃ₜ (ℝ × ℝ) := begin -- sorry let p : tangent_bundle 𝓡1 myℝ := ((4 : ℝ), 0), let F := chart_at (model_prod ℝ ℝ) p, have A : ¬ ((4 : ℝ) < 1), by norm_num, have S : F.source = univ, by simp [F, chart_at, A, @local_homeomorph.refl_source ℝ _], have T : F.target = univ, by simp [F, chart_at, A, @local_homeomorph.refl_target ℝ _], exact F.to_homeomorph_of_source_eq_univ_target_eq_univ S T, -- sorry end /- Up to now, we have never used the definition of the tangent bundle, and this corresponds to the usual mathematical practice: one doesn't care if the tangent space is defined using germs of curves, or spaces of derivations, or whatever equivalent definition. Instead, one relies all the time on functoriality (i.e., a smooth map has a well defined derivative, and they compose well, together with the fact that the tangent bundle to a vector space is the product). If you want to know more about the internals of the tangent bundle in mathlib, you can browse through the next section, but it is maybe wiser to skip it on first reading, as it is not needed to use the library -/ section you_should_probably_skip_this /- If `M` is a manifold modelled on a vector space `E`, then the underlying type for the tangent bundle is just `M × E` -/ lemma tangent_bundle_myℝ_is_prod : tangent_bundle 𝓡1 myℝ = (myℝ × ℝ) := /- inline sorry -/rfl/- inline sorry -/ /- This means that you can specify a point in the tangent bundle as a pair `(x, y)`. However, in general, a tangent bundle is not trivial: the topology on `tangent_bundle I myℝ` is *not* the product topology. Instead, the tangent space at a point `x` is identified with `ℝ` through some preferred chart at `x`, called `chart_at ℝ x`, but the way they are glued together depends on the manifold and the charts. In vector spaces, the tangent space is canonically the product space, with the same topology, as there is only one chart so there is no strange gluing at play. The equality of the topologies is given in `tangent_bundle_model_space_topology_eq_prod`, but they are not definitionally equal so one can get strange behavior if abusing identifications. Let us register the identification explicitly, as a homeomorphism: -/ def tangent_bundle_vector_space_triv (E : Type u) [normed_group E] [normed_space ℝ E] : tangent_bundle (model_with_corners_self ℝ E) E ≃ₜ E × E := { to_fun := id, inv_fun := id, left_inv := /- inline sorry -/λ x, rfl/- inline sorry -/, right_inv := /- inline sorry -/λ x, rfl/- inline sorry -/, continuous_to_fun := begin -- if you think that `continuous_id` should work but `exact continuous_id` fails, you -- can try `convert continuous_id`: it might show you what doesn't match and let you -- fix it afterwards. -- sorry convert continuous_id, exact (tangent_bundle_model_space_topology_eq_prod _ _).symm -- sorry end, continuous_inv_fun := begin -- sorry convert continuous_id, exact (tangent_bundle_model_space_topology_eq_prod _ _) -- sorry end } /- Even though the tangent bundle to `myℝ` is trivial abstractly, with this construction the tangent bundle is *not* the product space with the product topology, as we have used various charts so the gluing is not trivial. The following exercise unfolds the definition to see what is going on. It is not a reasonable exercise, in the sense that one should never ever do this when working with a manifold! -/ lemma crazy_formula_after_identifications (x : ℝ) (v : ℝ) : let p : tangent_bundle 𝓡1 myℝ := ((3 : ℝ), 0) in chart_at (model_prod ℝ ℝ) p (x, v) = if x ∈ Ioo (-1 : ℝ) 1 then (x, -v) else (x, v) := begin -- this exercise is not easy (and shouldn't be: you are not supposed to use the library like this!) -- if you really want to do this, you should unfold as much as you can using simp and dsimp, until you -- are left with a statement speaking of derivatives of real functions, without any manifold code left. -- sorry have : ¬ ((3 : ℝ) < 1), by norm_num, simp only [chart_at, this, mem_Ioo, if_false, and_false], dsimp [tangent_bundle_core, basic_smooth_bundle_core.chart, topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv', topological_fiber_bundle_core.index_at, basic_smooth_bundle_core.to_topological_fiber_bundle_core], split_ifs, { simp only [chart_at, h, my_first_local_homeo, if_true, fderiv_within_univ, prod.mk.inj_iff, mem_Ioo, fderiv_neg differentiable_at_id', fderiv_id', id.def, continuous_linear_map.coe_id', continuous_linear_map.neg_apply] with mfld_simps }, { simp only [chart_at, h, fderiv_within_univ, mem_Ioo, if_false, @local_homeomorph.refl_symm ℝ, fderiv_id, continuous_linear_map.coe_id'] with mfld_simps } -- sorry end end you_should_probably_skip_this /-! ### The language of manifolds In this paragraph, we will try to write down interesting statements of theorems, without proving them. The goal here is that Lean should not complain on the statement, but the proof should be sorried. -/ /- Here is a first example, already filled up, to show you how diffeomorphisms are currently named (we will probably introduce an abbreviation, but this hasn't been done yet). Don't try to fill the sorried proof! -/ /-- Two zero-dimensional connected manifolds are diffeomorphic. -/ theorem diffeomorph_of_zero_dim_connected (M M' : Type*) [topological_space M] [topological_space M'] [charted_space (euclidean_space (fin 0)) M] [charted_space (euclidean_space (fin 0)) M'] [connected_space M] [connected_space M'] : nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 0)) M M') := sorry /- Do you think that this statement is correct? (note that we have not assumed that our manifolds are smooth, nor that they are separated, but this is maybe automatic in zero dimension). Now, write down a version of this theorem in dimension 1, replacing the first sorry with meaningful content (and adding what is needed before the colon). Don't try to fill the sorried proof! -/ /-- Two one-dimensional smooth compact connected manifolds are diffeomorphic. -/ theorem diffeomorph_of_one_dim_compact_connected -- omit (M M' : Type*) [topological_space M] [topological_space M'] [charted_space (euclidean_space (fin 1)) M] [charted_space (euclidean_space (fin 1)) M'] [connected_space M] [connected_space M'] [compact_space M] [compact_space M'] [t2_space M] [t2_space M'] [smooth_manifold_with_corners (𝓡 1) M] [smooth_manifold_with_corners (𝓡 1) M'] -- omit : -- sorry nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M M') -- sorry := sorry /- You will definitely need to require smoothness and separation in this case, as it is wrong otherwise. Note that Lean won't complain if you don't put these assumptions, as the theorem would still make sense, but it would just turn out to be wrong. The previous statement is not really satisfactory: we would instead like to express that any such manifold is diffeomorphic to the circle. The trouble is that we don't have the circle as a smooth manifold yet. Since we have cheated and introduced it (with sorries) at the beginning of the tutorial, let's cheat again and use it to reformulate the previous statement. -/ -- the next result is not trivial, leave it sorried (but you can work on it if you don't like -- manifolds and prefer topology -- then please PR it to mathlib!). instance connected_sphere (n : ℕ) : connected_space (sphere (n+1)) := sorry /- The next two instances are easier to prove, you can prove them or leave them sorried as you like. For the second one, you may need to use facts of the library such as -/ #check compact_iff_compact_space #check metric.compact_iff_closed_bounded instance (n : ℕ) : t2_space (sphere n) := begin -- sorry dunfold sphere, apply_instance -- sorry end instance (n : ℕ) : compact_space (sphere n) := begin -- sorry dunfold sphere, apply compact_iff_compact_space.1, rw metric.compact_iff_closed_bounded, split, { exact metric.is_closed_sphere }, { rw metric.bounded_iff_subset_ball (0 : euclidean_space (fin (n+1))), exact ⟨1, metric.sphere_subset_closed_ball⟩ } -- sorry end /- Now, you can prove that any one-dimensional compact connected manifold is diffeomorphic to the circle. Here, you should fill the `sorry` (but luckily you may use `diffeomorph_of_one_dim_compact_connected`). -/ theorem diffeomorph_circle_of_one_dim_compact_connected (M : Type*) [topological_space M] [charted_space (euclidean_space (fin 1)) M] [connected_space M] [compact_space M] [t2_space M] [smooth_manifold_with_corners (𝓡 1) M] : nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M (sphere 1)) := -- sorry diffeomorph_of_one_dim_compact_connected M (sphere 1) -- sorry /- What about trying to say that there are uncountably many different smooth structures on `ℝ⁴`? (see https://en.wikipedia.org/wiki/Exotic_R4). The library is not really designed with this in mind, as in general we only work with one differentiable structure on a space, but it is perfectly capable of expressing this fact if one uses the `@` version of some definitions. Don't try to fill the sorried proof! -/ theorem exotic_ℝ4 : -- sorry let E := (euclidean_space (fin 4)) in ∃ f : ℝ → charted_space E E, ∀ i, @has_groupoid E _ E _ (f i) (times_cont_diff_groupoid ∞ (𝓡 4)) ∧ ∀ i j, nonempty (@structomorph _ _ (times_cont_diff_groupoid ∞ (𝓡 4)) E E _ _ (f i) (f j)) → i = j -- sorry := sorry /-! ### Smooth functions on `[0, 1]` In this paragraph, you will prove several (math-trivial but Lean-nontrivial) statements on the smooth structure of `[0,1]`. These facts should be Lean-trivial, but they are not (yet) since there is essentially nothing in this direction for now in the library. The goal is as much to be able to write the statements as to prove them. Most of the necessary vocabulary has been introduced above, so don't hesitate to browse the file if you are stuck. Additionally, you will need the notion of a smooth function on a subset: it is `times_cont_diff_on` for functions between vector spaces and `times_cont_mdiff_on` for functions between manifolds. Lemma times_cont_mdiff_g : the inclusion `g` of `[0, 1]` in `ℝ` is smooth. Lemma msmooth_of_smooth : Consider a function `f : ℝ → [0, 1]`, which is smooth in the usual sense as a function from `ℝ` to `ℝ` on a set `s`. Then it is manifold-smooth on `s`. Definition : construct a function `f` from `ℝ` to `[0,1]` which is the identity on `[0, 1]`. Theorem : the tangent bundle to `[0, 1]` is homeomorphic to `[0, 1] × ℝ` Hint for Theorem 4: don't try to unfold the definition of the tangent bundle, it will only get you into trouble. Instead, use the derivatives of the maps `f` and `g`, and rely on functoriality to check that they are inverse to each other. (This advice is slightly misleading as these derivatives do not go between the right spaces, so you will need to massage them a little bit). A global advice: don't hesitate to use and abuse `simp`, it is the main workhorse in this area of mathlib. -/ /- After doing the exercise myself, I realized it was (way!) too hard. So I will give at least the statements of the lemmas, to guide you a little bit more. To let you try the original version if you want, I have left a big blank space to avoid spoilers. -/ def g : Icc (0 : ℝ) 1 → ℝ := subtype.val -- smoothness results for `euclidean_space` are expressed for general `L^p` spaces -- (as `euclidean_space` has the `L^2` norm), in: #check pi_Lp.times_cont_diff_coord #check pi_Lp.times_cont_diff_on_iff_coord lemma times_cont_mdiff_g : times_cont_mdiff (𝓡∂ 1) 𝓡1 ∞ g := begin -- sorry rw times_cont_mdiff_iff, refine ⟨continuous_subtype_val, λ x y, _⟩, by_cases h : (x : ℝ) < 1, { simp only [g, chart_at, h, Icc_left_chart, function.comp, model_with_corners_euclidean_half_space, add_zero, dif_pos, if_true, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, subtype.coe_mk, subtype.val_eq_coe] with mfld_simps, refine (pi_Lp.times_cont_diff_coord 0).times_cont_diff_on.congr (λ x hx, _), simp only [mem_inter_eq, mem_set_of_eq] at hx, simp only [hx, le_of_lt hx.right.left, min_eq_left, max_eq_left] }, { simp only [chart_at, h, Icc_right_chart, function.comp, model_with_corners_euclidean_half_space, dif_pos, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, if_false, subtype.coe_mk, subtype.val_eq_coe, g] with mfld_simps, have : times_cont_diff ℝ ⊤ (λ (x : euclidean_space (fin 1)), 1 - x 0) := times_cont_diff_const.sub (pi_Lp.times_cont_diff_coord 0), apply this.times_cont_diff_on.congr (λ x hx, _), simp only [mem_inter_eq, mem_set_of_eq] at hx, have : 0 ≤ 1 - x 0, by linarith, simp only [hx, this, max_eq_left] } -- sorry end lemma msmooth_of_smooth {f : ℝ → Icc (0 : ℝ) 1} {s : set ℝ} (h : times_cont_diff_on ℝ ∞ (λ x, (f x : ℝ)) s) : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f s := begin -- sorry rw times_cont_mdiff_on_iff, split, { have : embedding (subtype.val : Icc (0 : ℝ) 1 → ℝ) := embedding_subtype_coe, exact (embedding.continuous_on_iff this).2 h.continuous_on }, simp only with mfld_simps, assume y, by_cases hy : (y : ℝ) < 1, { simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_left_chart, pi_Lp.times_cont_diff_on_iff_coord], apply h.mono (inter_subset_left _ _) }, { simp [chart_at, model_with_corners_euclidean_half_space, (∘), hy, Icc_right_chart, pi_Lp.times_cont_diff_on_iff_coord], assume i, apply (times_cont_diff_on_const.sub h).mono (inter_subset_left _ _) } -- sorry end /- A function from `ℝ` to `[0,1]` which is the identity on `[0,1]`. -/ def f : ℝ → Icc (0 : ℝ) 1 := λ x, ⟨max (min x 1) 0, by simp [le_refl, zero_le_one]⟩ lemma times_cont_mdiff_on_f : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f (Icc 0 1) := begin -- sorry apply msmooth_of_smooth, apply times_cont_diff_id.times_cont_diff_on.congr, assume x hx, simp at hx, simp [f, hx], -- sorry end lemma fog : f ∘ g = id := begin -- sorry ext x, rcases x with ⟨x', h'⟩, simp at h', simp [f, g, h'], -- sorry end lemma gof : ∀ x ∈ Icc (0 : ℝ) 1, g (f x) = x := begin -- sorry assume x hx, simp at hx, simp [g, f], simp [hx], -- sorry end def G : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) → (Icc (0 : ℝ) 1) × ℝ := λ p, (p.1, (tangent_map (𝓡∂ 1) 𝓡1 g p).2) lemma continuous_G : continuous G := begin -- sorry apply continuous.prod_mk (tangent_bundle_proj_continuous _ _), refine continuous_snd.comp _, have Z := times_cont_mdiff_g.continuous_tangent_map le_top, convert Z, exact (tangent_bundle_model_space_topology_eq_prod ℝ 𝓡1).symm -- sorry end /- in the definition of `F`, we use the map `tangent_bundle_vector_space_triv` (which is just the identity pointwise) to make sure that Lean is not lost between the different topologies. -/ def F : (Icc (0 : ℝ) 1) × ℝ → tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) := λ p, tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) ((tangent_bundle_vector_space_triv ℝ).symm (p.1, p.2)) lemma continuous_F : continuous F := begin -- sorry rw continuous_iff_continuous_on_univ, apply (times_cont_mdiff_on_f.continuous_on_tangent_map_within le_top _).comp, { apply ((tangent_bundle_vector_space_triv ℝ).symm.continuous.comp _).continuous_on, apply (continuous_subtype_coe.comp continuous_fst).prod_mk continuous_snd }, { rintros ⟨⟨x, hx⟩, v⟩ _, simp [tangent_bundle_vector_space_triv], exact hx }, { rw unique_mdiff_on_iff_unique_diff_on, exact unique_diff_on_Icc_zero_one } -- sorry end lemma FoG : F ∘ G = id := begin -- sorry ext1 p, rcases p with ⟨x, v⟩, simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f], dsimp, split, { rcases x with ⟨x', h'⟩, simp at h', simp [h'] }, { change (tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) (tangent_map (𝓡∂ 1) 𝓡1 g (x, v))).snd = v, rw [← tangent_map_within_univ, ← tangent_map_within_comp_at, fog, tangent_map_within_univ, tangent_map_id], { refl }, { apply times_cont_mdiff_on_f.mdifferentiable_on le_top, simpa [g] using x.2 }, { apply (times_cont_mdiff_g.times_cont_mdiff_at.mdifferentiable_at le_top).mdifferentiable_within_at }, { assume z hz, simpa [g] using z.2 }, { apply unique_mdiff_on_univ _ (mem_univ _) } } -- sorry end lemma GoF : G ∘ F = id := begin -- sorry ext1 p, rcases p with ⟨x, v⟩, simp [F, G, tangent_map_within, tangent_bundle_vector_space_triv, f], dsimp, split, { rcases x with ⟨x', h'⟩, simp at h', simp [h'] }, { have A : unique_mdiff_within_at 𝓡1 (Icc 0 1) ((x : ℝ), v).fst, { rw unique_mdiff_within_at_iff_unique_diff_within_at, apply unique_diff_on_Icc_zero_one _ x.2 }, change (tangent_map (𝓡∂ 1) 𝓡1 g (tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) (x, v))).snd = v, rw [← tangent_map_within_univ, ← tangent_map_within_comp_at _ _ _ _ A], { have : tangent_map_within 𝓡1 𝓡1 (g ∘ f) (Icc 0 1) (x, v) = tangent_map_within 𝓡1 𝓡1 id (Icc 0 1) (x, v) := tangent_map_within_congr gof _ x.2 A, rw [this, tangent_map_within_id A] }, { apply times_cont_mdiff_g.times_cont_mdiff_on.mdifferentiable_on le_top _ (mem_univ _) }, { apply times_cont_mdiff_on_f.mdifferentiable_on le_top _ x.2 }, { simp only [preimage_univ, subset_univ], } } -- sorry end def my_tangent_homeo : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) ≃ₜ (Icc (0 : ℝ) 1) × ℝ := -- sorry { to_fun := G, inv_fun := F, continuous_to_fun := continuous_G, continuous_inv_fun := continuous_F, left_inv := λ p, show (F ∘ G) p = id p, by rw FoG, right_inv := λ p, show (G ∘ F) p = id p, by rw GoF } -- sorry /-! ### Further things to do 1) can you prove `diffeomorph_of_zero_dim_connected` or `connected_sphere`? 2) Try to express and then prove the local inverse theorem in real manifolds: if a map between real manifolds (without boundary, modelled on a complete vector space) is smooth, then it is a local homeomorphism around each point. We already have versions of this statement in mathlib for functions between vector spaces, but this is very much a work in progress. 3) What about trying to prove `diffeomorph_of_one_dim_compact_connected`? (I am not sure mathlib is ready for this, as the proofs I am thinking of are currently a little bit too high-powered. If you manage to do it, you should absolutely PR it!) 4) Why not contribute to the proof of `sphere_eversion`? You can have a look at https://leanprover-community.github.io/sphere-eversion/ to learn more about this project by Patrick Massot. -/
d534899f9a62fc998c3efb871d49019daafc85ff
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/punit.lean
95732e70d9e95a0ba30cdce54a8b8cd1d4a240c5
[ "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,365
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.punit import category_theory.limits.has_limits /-! # `discrete punit` has limits and colimits Mostly for the sake of constructing trivial examples, we show all (co)cones into `discrete punit` are (co)limit (co)cones. We also show that such (co)cones exist, and that `discrete punit` has all (co)limits. -/ universe v open category_theory namespace category_theory.limits variables {J : Type v} [small_category J] {F : J ⥤ discrete punit.{v+1}} /-- A trivial cone for a functor into `punit`. `punit_cone_is_limit` shows it is a limit. -/ def punit_cone : cone F := ⟨punit.star, (functor.punit_ext _ _).hom⟩ /-- A trivial cocone for a functor into `punit`. `punit_cocone_is_limit` shows it is a colimit. -/ def punit_cocone : cocone F := ⟨punit.star, (functor.punit_ext _ _).hom⟩ /-- Any cone over a functor into `punit` is a limit cone. -/ def punit_cone_is_limit {c : cone F} : is_limit c := by tidy /-- Any cocone over a functor into `punit` is a colimit cocone. -/ def punit_cocone_is_colimit {c : cocone F} : is_colimit c := by tidy instance : has_limits (discrete punit) := by tidy instance : has_colimits (discrete punit) := by tidy end category_theory.limits
a4e80a7d0873203812091d84d87bf6438f95d791
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/adjunction/limits.lean
3a9b1825092a83f65660c79559d7256d0f1af35c
[ "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
8,528
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.creates open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality _ G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality _ F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality _ F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (cocones.functoriality K F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. -/ def left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, @equiv.unique _ _ (is_colimit.iso_unique_cocone_morphism.hom hc _) (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _)) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := left_adjoint_preserves_colimits E.adjunction -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves (colimit.is_colimit K) } def has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality _ F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality _ G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality _ G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (cones.functoriality K G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. -/ def right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, @equiv.unique _ _ (is_limit.iso_unique_cone_morphism.hom hc _) (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := right_adjoint_preserves_limits E.inv.adjunction @[priority 100] -- see Note [lower instance priority] instance is_equivalence_reflects_limits (E : D ⥤ C) [is_equivalence E] : reflects_limits E := { reflects_limits_of_shape := λ J 𝒥, by exactI { reflects_limit := λ K, { reflects := λ c t, begin have l: is_limit (E.inv.map_cone (E.map_cone c)) := preserves_limit.preserves t, convert is_limit.map_cone_equiv E.fun_inv_id l, { rw functor.comp_id }, { cases c, cases c_π, congr; rw functor.comp_id } end } } } @[priority 100] -- see Note [lower instance priority] instance is_equivalence_creates_limits (H : D ⥤ C) [is_equivalence H] : creates_limits H := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ F, { lifts := λ c t, { lifted_cone := H.map_cone_inv c, valid_lift := H.map_cone_map_cone_inv c } } } } -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves (limit.is_limit K) } def has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp } /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
9856670910c0312fb37447c2f07e6abaefc1b417
1446f520c1db37e157b631385707cc28a17a595e
/tests/compiler/closure_bug6.lean
a3f8ac43f2e85b31fde056c3207cf2d2c215299c
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
509
lean
def f (x : Nat) : Nat × (Nat → String) := let x1 := x + 1; let x2 := x + 2; let x3 := x + 3; let x4 := x + 4; let x5 := x + 5; let x6 := x + 6; let x7 := x + 7; let x8 := x + 8; let x9 := x + 9; let x10 := x + 10; let x11 := x + 11; let x12 := x + 12; let x13 := x + 13; let x14 := x + 14; let x15 := x + 15; let x16 := x + 16; let x17 := x + 17; (x, fun y => toString [x1, x2, x3, x4, x5, x6, x7, x8]) def main (xs : List String) : IO Unit := IO.println ((f (xs.headD "0").toNat).2 (xs.headD "0").toNat)
77790b6a1c3e047c999ee1b6e482295bca3ed8f8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/909.lean
f2955ed52c67504d5e3401ddf6775f3735b445ec
[ "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
942
lean
structure Date where val : Nat deriving Repr instance : LE Date := ⟨InvImage (Nat.le) Date.val⟩ instance bad (a b : Date) : Decidable (a <= b) := if h0 : (a.val <= b.val) then isTrue h0 else isFalse (fun hf => False.elim (h0 hf)) instance : Min Date := minOfLe /- This implementation also fails: instance (a b : Date) : Decidable (a <= b) := inferInstanceAs (Decidable (a.val <= b.val)) -/ /- This implemenation evaluates successfully: instance (a b : Date) : Decidable (a <= b) := dite (a.val <= b.val) isTrue (fun nle => isFalse (fun hf => False.elim (nle hf))) -/ instance : ToString Date where toString d := s!"D{d.val}" structure DateRange where start_ : Date finish_ : Date h : start_ <= finish_ def r1 := (DateRange.mk (Date.mk 0) (Date.mk 10) (by decide)) -- If you change the start_ value here to `0`, it works. def r2 := (DateRange.mk (Date.mk 1) (Date.mk 10) (by decide)) #eval min r1.start_ r2.start_
2dfe4d73409deed5cda1ff207ffba4c3be7afbf0
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/fin.lean
dcd83e481c1a5264d62f09d592dff43f7c63c930
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
14,243
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek More about finite numbers. -/ import data.nat.basic open fin nat function /-- `fin 0` is empty -/ def fin_zero_elim {C : Sort*} : fin 0 → C := λ x, false.elim $ nat.not_lt_zero x.1 x.2 def {u} fin_zero_elim' {α : fin 0 → Sort u} : ∀(x : fin 0), α x | ⟨n, hn⟩ := false.elim (nat.not_lt_zero n hn) namespace fin variables {n m : ℕ} {a b : fin n} @[simp] protected lemma eta (a : fin n) (h : a.1 < n) : (⟨a.1, h⟩ : fin n) = a := by cases a; refl protected lemma ext_iff (a b : fin n) : a = b ↔ a.val = b.val := iff.intro (congr_arg _) fin.eq_of_veq lemma injective_val {n : ℕ} : injective (val : fin n → ℕ) := λ _ _, fin.eq_of_veq lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ @[simp] protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : fin.mk a ha = fin.mk b hb ↔ a = b := ⟨fin.mk.inj, λ h, by subst h⟩ instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ @[simp] lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl @[simp] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl instance {n : ℕ} : decidable_linear_order (fin n) := decidable_linear_order.lift fin.val (@fin.eq_of_veq _) (by apply_instance) lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma lt_iff_val_lt_val : a < b ↔ a.val < b.val := iff.rfl lemma le_iff_val_le_val : a ≤ b ↔ a.val ≤ b.val := iff.rfl @[simp] lemma succ_val (j : fin n) : j.succ.val = j.val.succ := by cases j; simp [fin.succ] protected theorem succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (fin.ext_iff _ _).1 heq @[simp] lemma pred_val (j : fin (n+1)) (h : j ≠ 0) : (j.pred h).val = j.val.pred := by cases j; simp [fin.pred] @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by cases i; refl @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) (a : fin n) : fin m := cast_lt a (lt_of_lt_of_le a.2 h) /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m) : fin n → fin m := cast_le $ le_of_eq eq /-- `cast_add m i` embedds `i` in `fin (n+m)`. -/ def cast_add (m) : fin n → fin (n + m) := cast_le $ le_add_right n m /-- `cast_succ i` embedds `i` in `fin (n+1)`. -/ def cast_succ : fin n → fin (n + 1) := cast_add 1 /-- `succ_above p i` embeds into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n+1)) (i : fin n) : fin (n+1) := if i.1 < p.1 then i.cast_succ else i.succ /-- `pred_above p i h` embeds `i` into `fin n` by ignoring `p`. -/ def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n := if h : i < p then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2) else i.pred $ have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm, ne_of_gt (lt_of_le_of_lt (zero_le p) this) /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ i.val) : fin n := ⟨i.val - m, by simp [nat.sub_lt_right_iff_lt_add h, i.is_lt]⟩ /-- `add_nat i h` adds `m` on `i`, generalizes `fin.succ`. -/ def add_nat (m) (i : fin n) : fin (n + m) := ⟨i.1 + m, add_lt_add_right i.2 _⟩ /-- `nat_add i h` adds `n` on `i` -/ def nat_add (n) {m} (i : fin m) : fin (n + m) := ⟨n + i.1, add_lt_add_left i.2 _⟩ theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt @[simp] lemma cast_val (k : fin n) (h : n = m) : (fin.cast h k).val = k.val := rfl @[simp] lemma cast_succ_val (k : fin n) : k.cast_succ.val = k.val := rfl @[simp] lemma cast_lt_val (k : fin m) (h : k.1 < n) : (k.cast_lt h).val = k.val := rfl @[simp] lemma cast_le_val (k : fin m) (h : m ≤ n) : (k.cast_le h).val = k.val := rfl @[simp] lemma cast_add_val (k : fin m) : (k.cast_add n).val = k.val := rfl @[simp] lemma last_val (n : ℕ) : (last n).val = n := rfl @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : i.val < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : a.1 < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma sub_nat_val (i : fin (n + m)) (h : m ≤ i.val) : (i.sub_nat m h).val = i.val - m := rfl @[simp] lemma add_nat_val (i : fin (n + m)) (h : m ≤ i.val) : (i.add_nat m).val = i.val + m := rfl @[simp] lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := by simp [eq_iff_veq] def clamp (n m : ℕ) : fin (m + 1) := fin.of_nat $ min n m @[simp] lemma clamp_val (n m : ℕ) : (clamp n m).val = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ lemma injective_cast_le {n₁ n₂ : ℕ} (h : n₁ ≤ n₂) : injective (fin.cast_le h) | ⟨i₁, h₁⟩ ⟨i₂, h₂⟩ eq := fin.eq_of_veq $ show i₁ = i₂, from fin.veq_of_eq eq theorem succ_above_ne (p : fin (n+1)) (i : fin n) : p.succ_above i ≠ p := begin assume eq, unfold fin.succ_above at eq, split_ifs at eq with h; simpa [lt_irrefl, nat.lt_succ_self, eq.symm] using h end @[simp] lemma succ_above_descend : ∀(p i : fin (n+1)) (h : i ≠ p), p.succ_above (p.pred_above i h) = i | ⟨p, hp⟩ ⟨0, hi⟩ h := fin.eq_of_veq $ by simp [succ_above, pred_above]; split_ifs; simp * at * | ⟨p, hp⟩ ⟨i+1, hi⟩ h := fin.eq_of_veq begin have : i + 1 ≠ p, by rwa [(≠), fin.ext_iff] at h, unfold succ_above pred_above, split_ifs with h1 h2; simp only [fin.cast_succ_cast_lt, add_right_inj, pred_val, ne.def, cast_succ_val, nat.pred_succ, fin.succ_pred, add_right_inj] at *, exact (this (le_antisymm h2 (le_of_not_gt h1))).elim end @[simp] lemma pred_above_succ_above (p : fin (n+1)) (i : fin n) (h : p.succ_above i ≠ p) : p.pred_above (p.succ_above i) h = i := begin unfold fin.succ_above, apply eq_of_veq, split_ifs with h₀, { simp [pred_above, h₀, lt_iff_val_lt_val], }, { unfold pred_above, split_ifs with h₁, { exfalso, rw [lt_iff_val_lt_val, succ_val] at h₁, exact h₀ (lt_trans (nat.lt_succ_self _) h₁) }, { rw [pred_succ] } } end section rec @[elab_as_eliminator] def succ_rec {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : ∀ {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : ∀ n, fin n → Sort*} (H0 : ∀ n, C (succ n) 0) (Hs : ∀ n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : ∀ i : fin n, C (i.succ)) : ∀ (i : fin (succ n)), C i | ⟨0, h⟩ := H0 | ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩ @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ end rec section tuple /- We can think of the type `fin n → α` as `n`-tuples in `α`. Here are some relevant operations. -/ def tail {α} (p : fin (n+1) → α) : fin n → α := λ i, p i.succ def cons {α} (x : α) (v : fin n → α) : fin (n+1) → α := λ j, fin.cases x v j @[simp] lemma tail_cons {α} (x : α) (p : fin n → α) : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ {α} (x : α) (p : fin n → α) (i : fin n) : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero {α} (x : α) (p : fin n → α) : cons x p 0 = x := by simp [cons] end tuple section find def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin.elim0 i) | (n+1) p _ := ⟨λ h, begin resetI, rw [option.is_some_iff_exists] at h, cases h with i hi, exact ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; subst h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find end fin
38b8630c7a0078b12d535a8a1e51f43ca0314b6b
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_1989.lean
bfde4eaf49fc9102e8dad5986e460ceefbda72a9
[]
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
162
lean
import algebra.ordered_ring variables {R : Type*} [ordered_ring R] variables a b c : R -- BEGIN #check (mul_nonneg : 0 ≤ a → 0 ≤ b → 0 ≤ a * b) -- END
a769fd1752ed4c42bbedced0999ded24928de69a
b5d813b41740060da28e55b77c69760b7c52760d
/lean_stuff_4.lean
37d6c77a4bd5090cb7e4e165cf62826225731712
[]
no_license
ImperialCollegeLondon/SF-solns-zak
4e85518c5cd4093b995a7593eee8295887e8727e
7edc4424938e01a6ef4bb518fa8ec1757a2226b1
refs/heads/master
1,584,849,829,155
1,533,216,269,000
1,533,216,269,000
139,470,368
3
0
null
null
null
null
UTF-8
Lean
false
false
5,278
lean
namespace z3 inductive List (α : Type) | emp {} : List | ap : α → List → List open List notation {} := emp notation x :: y := ap x y definition append : Π {α:Type}, List α → List α → List α | α emp L := L | α (x::L₁) L₂ := x::(append L₁ L₂) definition repeat : Π {α:Type}, α → ℕ → List α | α _ 0 := emp | α x (nat.succ n) := append (x::{}) (repeat x (n)) definition len : Π {α:Type}, List α → ℕ | α emp := 0 | α (_::L) := len L + 1 --todo : {} for append theorem list_app_eq : ∀ α : Type, ∀ L₁ L₂ : List α, len (append L₁ L₂) = len L₁ + len L₂ := begin intro α, intros L₁ L₂, induction L₁ with new L_shorter H,{unfold append, unfold len, simp}, { unfold append, unfold len, rw H, simp }end -------------- products ----------------- inductive prodd (α β : Type) | pair : α → β → prodd open prodd def fst : Π {α β : Type}, prodd α β → α | _ _ (pair x y) := x def snd : Π {α β : Type}, prodd α β → β | _ _ (pair x y) := y def zip : Π {α β : Type}, List α → List β → List (prodd α β) | α β {} {} := {} | α β (A::L₁) (B::L₂) := ap (pair A B) (zip L₁ L₂) -- if different lengths, give up | _ _ _ _ := {} def unzip : Π {α β : Type}, List (prodd α β) → prodd (List α) (List β) | α β {} := pair {} {} | α β (x::L) := pair (ap (fst x) (fst (unzip L)) ) (ap (snd x) (snd (unzip L)) ) theorem A : ∀ α β:Type, ∀ L₁ L₂:List α, len L₁ = len L₁ → pair L₁ L₂ = unzip (zip L₁ L₂) := begin intros α β, intros L₁ L₂, intro H, admit end inductive option (α : Type) | None : option | Some : α → option def get_nth {α : Type}: List α → ℕ → option α | {} _ := option.None α | (x::_) 0 := option.Some x | (_::y) (nat.succ n) := get_nth y n def filter : Π {α : Type}, List α → (α → bool) → List α | α {} _ := {} | α (x::L) F := if F x = tt then ap x (filter L F) else filter L F def nat_even : ℕ → bool | 0 := tt | 1 := ff | (nat.succ (nat.succ n)) := nat_even n def bool_and : bool → bool → bool | tt tt := tt | _ _ := ff def bool_inv : bool → bool | tt := ff | _ := tt def gt (a b : ℕ) : bool := if a > b then tt else ff def task (L₁ : List ℕ) : List ℕ := filter L₁ (λ n, bool_and (nat_even n) (gt n 7) ) def inverse_func : Π {α : Type}, (α → bool) → (α → bool) := --λ α F, λ b, bool_inv (F b) λ α F, bool_inv ∘ F -- f ∘ g = λ b, f (g b) def partition : Π {α : Type}, (α → bool) → List α → prodd (List α) (List α) := λ α F L, pair (filter L F) (filter L (inverse_func F)) def fold {α β : Type} : (α → β → β) → List α → β → β | _ {} st := st | F (a::L) st := F a (fold F L st) def map : Π {α β : Type}, (α → β) → List α → List β | α β _ {} := {} | α β F (a::L) := ap (F a) (map F L) definition fold_map : Π{α β:Type}, (α → β) → List α → List β := λ α β F L, fold (λ a b, ap (F a) b) L {} -- ∀ n : (α → β), ∀ L : List α, fold_map n L = map n L def reverse : Π {α : Type}, List α → List α | α {} := {} | α (ap n L) := append (reverse L) (n::{}) def flatten_list : Π {α : Type}, List (List α) → List α | α {} := {} | α (a::L) := append a (flatten_list L) def flat_map : Π {α β : Type}, (α → List β) → List α → List β := λ α β F L, flatten_list (map F L) definition fold_length : Π {α : Type}, List α → ℕ := λ α L, fold (λ _ n, nat.succ n) L 0 definition prod_curry {X Y Z : Type} (f : prodd X Y → Z) (x : X) (y : Y) : Z := f (pair x y) definition prod_uncurry {X Y Z : Type} : (X → Y → Z) → (prodd X Y) → Z | f p := f (fst p) (snd p) #check (λ a b, a+b) 5 6 #check prod_curry (prod_uncurry (λ a b, a+b) (pair 1 2)) #reduce prod_curry (λ pair (a:ℕ) (b:ℕ), a+1) 50 6 @[simp]theorem map_app : Π {α β : Type}, ∀ F : α → β, ∀ L : List α, ∀ a : α, map F (append L (a::{})) = append (map F L) ((F a)::{}) := begin intros α β F L a, induction L with new L_sh H,{refl}, { unfold map, unfold append, rw ←H, unfold map } end theorem map_rev : Π {α β : Type}, ∀ F : α → β, ∀ L : List α, map F (reverse L) = reverse (map F L) := begin intros α β, intro F, intro L, induction L with new L_sh H₁, { unfold reverse, unfold map, refl }, { unfold map reverse, simp, rw H₁ --apply map_app F (reverse L_sh) new, } end theorem fold_length_eq : Π {α : Type}, ∀ L : List α, fold_length L = len L := begin intros α L, induction L with new L_sh prev, {refl}, { unfold len, rw ←prev, unfold fold_length, refl } end theorem curry {α β γ : Type} : ∀ F : (α → β → γ), F = prod_curry (prod_uncurry F) := begin intro F, apply funext, intro a, apply funext, intro b, unfold prod_curry, unfold prod_uncurry, refl end theorem a : ∀ X n L, len L = n → @get_nth X L n = option.None X :=begin intros X n L, revert n, induction L with new Lh H₂, { unfold get_nth, intros a b, refl }, { unfold len get_nth, have H₃ := H₂ (len Lh) rfl, intro n, intro H₄, rw ←H₄, clear H₂, unfold get_nth, rw H₃ } end end z3
2b7542f9d6b81a1d3cbc60118c45df7f9fde59b5
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/pp_shadowed_const.lean
2acd96fe6ae72f528f9c70274d6649bbf8280912
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
102
lean
def f : Π (x : nat) (b : bool), bool = bool := λ bool, _ def g (heq : 1 == 1) := heq.symm #print g
1c6047ef4334e960da94be5b240ce68e7110c0cf
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/fin.lean
4d0420556ce9ba7aefba3020b1748b9975d087bb
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
39,333
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.cast import tactic.localized import logic.embedding /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; ### Casts * `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `cast eq` : embed `fin n` into `fin m`, `eq : n = m`; * `cast_add m` : embed `fin n` into `fin (n+m)`; * `cast_succ` : embed `fin n` into `fin (n+1)`; * `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`; * `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`; * `nat_add i h` adds `n` on `i` on the left; * `clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universe u open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 lemma fact.succ.pos {n} : fact (0 < succ n) := zero_lt_succ _ lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) := nat.zero_lt_bit0 $ ne_of_gt h lemma fact.bit1.pos {n} : fact (0 < bit1 n) := nat.zero_lt_bit1 _ lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) := pow_pos h _ localized "attribute [instance] fact.succ.pos" in fin_fact localized "attribute [instance] fact.bit0.pos" in fin_fact localized "attribute [instance] fact.bit1.pos" in fin_fact localized "attribute [instance] fact.pow.pos" in fin_fact namespace fin variables {n m : ℕ} {a b : fin n} instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩ lemma is_lt (i : fin n) : (i : ℕ) < n := i.2 /-- convert a `ℕ` to `fin n`, provided `n` is positive -/ def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h⟩ @[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a := by cases a; refl @[ext] lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b := iff.intro (congr_arg _) fin.eq_of_veq lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 := ⟨vne_of_ne, ne_of_vne⟩ @[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : (⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b := ⟨subtype.mk.inj, λ h, by subst h⟩ lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k := fin.eq_iff_veq a ⟨k, hk⟩ @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma mk_coe (i : fin n) : (⟨i, i.is_lt⟩ : fin n) = i := fin.eta _ _ lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl attribute [simp] val_zero @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl @[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl @[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl @[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl section bit @[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) : (⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) := eq_of_veq (nat.mod_eq_of_lt h).symm @[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) : (⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt ((m + m).lt_succ_self.trans h)⟩ : fin _) := begin ext, simp only [bit1, bit0] at h, simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h], end end bit @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := begin induction a with a ih, { refl }, ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)), { rw [val_add, ← ih, of_nat], exact add_mod _ _ _ } end /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)).val) = a := begin rw ←of_nat_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.property end /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a := coe_val_eq_self a /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Type*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ (i : ℕ) = (j : ℕ) := by { induction h, simp [ext_iff] } instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩ instance {n : ℕ} : linear_order (fin n) := { le := (≤), lt := (<), ..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) } instance {n : ℕ} : decidable_linear_order (fin n) := { decidable_le := fin.decidable_le, decidable_lt := fin.decidable_lt, decidable_eq := fin.decidable_eq _, ..fin.linear_order } lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 @[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 := by cases j; simp [fin.succ] lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe] protected theorem succ.inj (p : fin.succ a = fin.succ b) : a = b := by cases a; cases b; exact eq_of_veq (nat.succ.inj (veq_of_eq p)) @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := ⟨λh, succ.inj h, λh, by rw h⟩ @[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b := by { simp only [le_iff_coe_le_coe, coe_succ], exact ⟨le_of_succ_le_succ, succ_le_succ⟩ } @[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b := by { simp only [lt_iff_coe_lt_coe, coe_succ], exact ⟨lt_of_succ_lt_succ, succ_lt_succ⟩ } lemma succ_injective (n : ℕ) : injective (@fin.succ n) := λa b, succ.inj lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq @[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ := by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i } lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ := by { cases n, { exact fin_zero_elim a }, { rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a } } lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a) @[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 := by { cases j, refl } @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by { cases i, refl } @[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) : fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ := by simp only [ext_iff, coe_pred, coe_mk, nat.add_sub_cancel] @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) (a : fin n) : fin m := cast_lt a (lt_of_lt_of_le a.2 h) /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast (eq : n = m) : fin n → fin m := cast_le $ le_of_eq eq /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/ def cast_add (m) : fin n → fin (n + m) := cast_le $ le_add_right n m /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n → fin (n + 1) := cast_add 1 /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n + 1)) (i : fin n) : fin (n + 1) := if i.cast_succ < p then i.cast_succ else i.succ /-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/ def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n := if h : i < p then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2) else i.pred $ have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm, ne_of_gt (lt_of_le_of_lt (zero_le p) this) /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n := ⟨(i : ℕ) - m, by { rw [nat.sub_lt_right_iff_lt_add h], exact i.is_lt }⟩ /-- `add_nat i h` adds `m` on `i`, generalizes `fin.succ`. -/ def add_nat (m) (i : fin n) : fin (n + m) := ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩ /-- `nat_add i h` adds `n` on `i` -/ def nat_add (n) {m} (i : fin m) : fin (n + m) := ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩ theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt @[simp] lemma coe_cast (k : fin n) (h : n = m) : (fin.cast h k : ℕ) = k := rfl @[simp] lemma coe_cast_succ (k : fin n) : (k.cast_succ : ℕ) = k := rfl @[simp] lemma coe_cast_lt (k : fin m) (h : (k : ℕ) < n) : (k.cast_lt h : ℕ) = k := rfl @[simp] lemma coe_cast_le (k : fin m) (h : m ≤ n) : (k.cast_le h : ℕ) = k := rfl @[simp] lemma coe_cast_add (k : fin m) : (k.cast_add n : ℕ) = k := rfl lemma last_val (n : ℕ) : (last n).val = n := rfl @[simp, norm_cast] lemma coe_last {n : ℕ} : (last n : ℕ) = n := rfl @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m := rfl @[simp] lemma coe_add_nat (i : fin (n + m)) : (i.add_nat m : ℕ) = i + m := rfl @[simp] lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := by simp [eq_iff_veq] lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt @[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl /-- `cast_succ i` is positive when `i` is positive -/ lemma cast_succ_pos (i : fin (n + 1)) (h : 0 < i) : 0 < cast_succ i := by simpa [lt_iff_coe_lt_coe] using h lemma last_pos : (0 : fin (n + 2)) < last (n + 1) := by simp [lt_iff_coe_lt_coe] lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n := by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] } lemma le_coe_last (i : fin (n + 1)) : i ≤ n := by { rw fin.coe_nat_eq_last, exact fin.le_last i } lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 := begin cases n, { exact absurd h (nat.not_lt_zero _) }, { rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h, rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h], exact nat.zero_lt_succ _ } end lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0 lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by { simp [fin.ext_iff], } lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ := by { rw [lt_iff_coe_lt_coe, cast_succ, coe_cast_add, coe_succ], exact lt_add_one _ } @[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ := begin rw [cast_succ, cast_add, cast_le, cast_lt, eq_iff_veq], exact coe_val_of_lt (nat.lt.step a.is_lt), end @[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ := begin cases n, { exact fin_zero_elim a }, { simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] } end lemma lt_succ : a.cast_succ < a.succ := by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val } @[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h := begin rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, nat.add_sub_cancel], exact add_lt_add_right h 1, end /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m @[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ lemma cast_le_injective {n₁ n₂ : ℕ} (h : n₁ ≤ n₂) : injective (fin.cast_le h) | ⟨i₁, h₁⟩ ⟨i₂, h₂⟩ eq := fin.eq_of_veq $ show i₁ = i₂, from fin.veq_of_eq eq lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) := cast_le_injective (le_add_right n 1) /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p` -/ lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) : p.succ_above i = i.cast_succ := by { rw [succ_above], exact if_pos h } /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ` -/ @[simp] lemma succ_above_zero : succ_above (0 : fin (n + 1)) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a whole around `last n` embeds by `cast_succ` -/ @[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ := by { ext, simp only [succ_above, cast_succ_lt_last, if_true] } /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ` -/ lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) : p.succ_above i = i.succ := by { rw [succ_above], exact if_neg (not_lt_of_le h) } /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p` -/ lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ := lt_or_ge (cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p` -/ lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ := or.cases_on (succ_above_lt_ge p i) (λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))) /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p := begin intro eq, by_cases H : i.cast_succ < p, { simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H }, { simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i } end /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i := begin by_cases H : i.cast_succ < p, { simpa [succ_above_below _ _ H] using cast_succ_pos _ h }, { simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ }, end /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_inj {x : fin (n + 1)} : x.succ_above a = x.succ_above b ↔ a = b := begin refine iff.intro _ (λ h, by rw h), intro h, cases succ_above_lt_ge x a with ha ha; cases succ_above_lt_ge x b with hb hb, { simpa only [succ_above_below, ha, hb, cast_succ_inj] using h }, { simp only [succ_above_below, succ_above_above, ha, hb] at h, rw h at ha, exact absurd (lt_of_le_of_lt hb (cast_succ_lt_succ _)) (asymm ha) }, { simp only [succ_above_below, succ_above_above, ha, hb] at h, rw ←h at hb, exact absurd (lt_of_le_of_lt ha (cast_succ_lt_succ _)) (asymm hb) }, { simpa only [succ_above_above, ha, hb, succ_inj] using h }, end /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) := λ _ _, succ_above_right_inj.mp /-- Embedding a `fin (n + 1)` into `fin n` and embedding it back around the same hole gives the starting `fin (n + 1)` -/ @[simp] lemma succ_above_descend (p i : fin (n + 1)) (h : i ≠ p) : p.succ_above (p.pred_above i h) = i := begin rw pred_above, cases lt_or_le i p with H H, { simp only [succ_above_below, cast_succ_cast_lt, H, dif_pos]}, { rw le_iff_coe_le_coe at H, rw succ_above_above, { simp only [le_iff_coe_le_coe, H, not_lt, dif_neg, succ_pred] }, { simp only [le_iff_coe_le_coe, H, coe_pred, not_lt, dif_neg, coe_cast_succ], exact le_pred_of_lt (lt_of_le_of_ne H (vne_of_ne h.symm)) } } end /-- Embedding a `fin n` into `fin (n + 1)` and embedding it back around the same hole gives the starting `fin n` -/ @[simp] lemma pred_above_succ_above (p : fin (n + 1)) (i : fin n) : p.pred_above (p.succ_above i) (succ_above_ne _ _) = i := begin rw pred_above, by_cases H : i.cast_succ < p, { simp [succ_above_below _ _ H, H] }, { cases succ_above_lt_gt p i with h h, { exact absurd h H }, { simp [succ_above_above _ _ (le_of_not_lt H), pred_succ, dif_neg (asymm h)] } } end /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_inj {x y : fin (n + 1)} : x.succ_above = y.succ_above ↔ x = y := begin refine iff.intro _ (λ h, by rw h), contrapose!, intros H h, have key := congr_fun h (y.pred_above x H), rw [succ_above_descend] at key, exact absurd key (succ_above_ne x _) end /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_injective : injective (@succ_above n) := λ _ _, succ_above_left_inj.mp /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] } end section rec /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i | ⟨0, h⟩ := H0 | ⟨succ i, h⟩ := Hs ⟨i, lt_of_succ_lt_succ h⟩ @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ end rec section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ instance tuple0_unique (α : fin 0 → Type u) : unique (Π i : fin 0, α i) := { default := fin_zero_elim, uniq := λ x, funext fin_zero_elim } variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.succ_injective n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc] } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_eq_mp (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_eq_mp C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt] }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i) | (n+1) p _ := ⟨λ h, begin rw [option.is_some_iff_exists] at h, cases h with i hi, exactI ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find @[simp] lemma coe_of_nat_eq_mod (m n : ℕ) : ((n : fin (succ m)) : ℕ) = n % succ m := by rw [← of_nat_eq_coe]; refl @[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] : (@fin.of_nat' _ I n : ℕ) = n % m := rfl end fin
5387a69ed59c40e92f5915073dc564e35501d9d8
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/set_theory/ordinal.lean
1f3503a7c2fbfa66928d1cff39c286506cc4eb5a
[ "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
56,660
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.cardinal /-! # Ordinals Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed with a total order, where an ordinal is smaller than another one if it embeds into it as an initial segment (or, equivalently, in any way). This total order is well founded. ## Main definitions * `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). It is denoted by `r ≼i s`. * `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by `r ≺i s`. * `ordinal`: the type of ordinals (in a given universe) * `ordinal.type r`: given a well-founded order `r`, this is the corresponding ordinal * `ordinal.typein r a`: given a well-founded order `r` on a type `α`, and `a : α`, the ordinal corresponding to all elements smaller than `a`. * `enum r o h`: given a well-order `r` on a type `α`, and an ordinal `o` strictly smaller than the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `α`. In other words, the elements of `α` can be enumerated using ordinals up to `type r`. * `ordinal.card o`: the cardinality of an ordinal `o`. * `ordinal.lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`. For a version registering additionally that this is an initial segment embedding, see `ordinal.lift.initial_seg`. For a version regiserting that it is a principal segment embedding if `u < v`, see `ordinal.lift.principal_seg`. * `ordinal.omega` is the first infinite ordinal. It is the order type of `ℕ`. * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. The main properties of addition (and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here, we only introduce it and prove its basic properties to deduce the fact that the order on ordinals is total (and well founded). * `succ o` is the successor of the ordinal `o`. * `ordinal.min`: the minimal element of a nonempty indexed family of ordinals * `ordinal.omin` : the minimal element of a nonempty set of ordinals * `cardinal.ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality. It is the canonical way to represent a cardinal with an ordinal. ## Notations * `r ≼i s`: the type of initial segment embeddings of `r` into `s`. * `r ≺i s`: the type of principal segment embeddings of `r` into `s`. * `ω` is a notation for the first infinite ordinal in the locale `ordinal`. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-! ### Initial segments Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called `initial_seg r s`, and denoted by `r ≼i s`. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the range of `f`. -/ @[nolint has_inhabited_instance] structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (init : ∀ a b, s b (to_rel_embedding a) → ∃ a', to_rel_embedding a' = b) local infix ` ≼i `:25 := initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ↪r s) := ⟨initial_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≼i s) := ⟨λ _, α → β, λ f x, (f : r ↪r s) x⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≼i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ↪r s).map_rel_iff.1 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ↪r s).map_rel_iff.2 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃r s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `≼i` is reflexive -/ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨rel_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ /-- Composition of functions shows that `≼i` is transitive -/ @[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t := ⟨f.1.trans g.1, λ a c h, begin simp at h ⊢, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.map_rel_iff.1 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl theorem unique_of_extensional [is_extensional β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact rel_embedding.coe_fn_inj this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ↪r s).map_rel_iff.2 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ↪r s).map_rel_iff.2 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@rel_embedding.well_founded _ _ r s a is_well_order.wf)) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `α` and `β` whose images are initial segments, and `β` is a well-order then `α` and `β` are order-isomorphic. -/ def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s := by haveI := f.to_rel_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.map_rel_iff'⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := rel_iso.coe_fn_injective rfl theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on (is_well_order.wf.apply b : acc s b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨rel_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl⟩, λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg /-! ### Principal segments Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form `(-∞, top)` for some element `top` of `β`). The type of these embeddings from `r` to `s` is called `principal_seg r s`, and denoted by `r ≺i s`. Principal segments are in particular initial segments. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an order embedding whose range is an open interval `(-∞, top)` for some element `top` of `β`. Such order embeddings are called principal segments -/ @[nolint has_inhabited_instance] structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (top : β) (down : ∀ b, s b top ↔ ∃ a, to_rel_embedding a = b) local infix ` ≺i `:25 := principal_seg namespace principal_seg instance : has_coe (r ≺i s) (r ↪r s) := ⟨principal_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≺i s) := ⟨λ _, α → β, λ f, f⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≺i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ↪r s) : α → β) = f := rfl theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b := f.down _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ /-- A principal segment is in particular an initial segment. -/ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_rel_embedding, λ a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := @initial_seg.init_iff α β r s f a b theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end /-- Composition of a principal segment with an initial segment, as a principal segment -/ def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl /-- Composition of two principal segments as a principal segment -/ @[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment, as a principal segment -/ def equiv_lt (f : r ≃r s) (g : s ≺i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g.top, λ c, suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down], ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ /-- Composition of a principal segment with an order isomorphism, as a principal segment -/ def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : principal_seg r s) (g : s ≃r t) : principal_seg r t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [← g.apply_symm_apply x, g.map_rel_iff, f.down', exists_congr], intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃r s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (λ x, _), simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] }, cases f, cases g, have := rel_embedding.coe_fn_inj ef; congr' end⟩ theorem top_eq [is_well_order γ t] (e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order γ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.rel_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨rel_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down'.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl end principal_seg /-! ### Properties of initial and principal segments -/ /-- To an initial segment taking values in a well order, one can associate either a principal segment (if the range is not everything, hence one can take as top the minimum of the complement of the range) or an order isomorphism (if the range is everything). -/ def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) := if h : surjective f then sum.inr (rel_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a := @initial_seg.eq α β r s _ g f a theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a := initial_seg.eq (initial_seg.of_iso g) f a /-- Composition of an initial segment taking values in a well order and a principal segment. -/ def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] } end namespace rel_embedding /-- Given an order embedding into a well order, collapse the order embedding by filling the gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise, but the proof of the fact that it is an initial segment will be given in `collapse`. -/ def collapse_F [is_well_order β s] (f : r ↪r s) : Π a, {b // ¬ s (f a) b} := (rel_embedding.well_founded f $ is_well_order.wf).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.map_rel_iff.2 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.map_rel_iff.2 h, exact ⟨is_well_order.wf.min S ⟨_, this⟩, is_well_order.wf.not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ↪r s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ↪r s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding into a well order, by collapsing it to fill the gaps. -/ def collapse [is_well_order β s] (f : r ↪r s) : r ≼i s := by haveI := rel_embedding.is_well_order f; exact ⟨rel_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, acc.rec_on (is_well_order.wf.apply b : acc s b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S.nonempty := ⟨_, asymm h⟩, existsi (is_well_order.wf : well_founded r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf : well_founded r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact is_well_order.wf.not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order β s] (f : r ↪r s) (a) : collapse f a = (collapse_F f a).1 := rfl end rel_embedding /-! ### Well order on an arbitrary type -/ section well_ordering_thm parameter {σ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) := embedding.total.resolve_left $ λ ⟨⟨f, hf⟩⟩, let g : σ → cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≤ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- Any type can be endowed with a well order, obtained by pulling back the well order over cardinals by some embedding. -/ def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel := (rel_embedding.preimage _ _).is_well_order end well_ordering_thm /-! ### Definition of ordinals -/ /-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient of this type. -/ structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) attribute [instance] Well_order.wo namespace Well_order instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩ end Well_order /-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order isomorphism. -/ instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s), iseqv := ⟨λ⟨α, r, _⟩, ⟨rel_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. For the embedding as a principal segment, see `typein.principal_seg`. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : α → α → Prop) [wo : is_well_order α r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃r s) := quotient.eq @[simp] lemma type_out (o : ordinal) : type o.out.r = o := by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl } @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], by exactI C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-! ### The order on ordinals -/ /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ↪r s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl instance : partial_order ordinal := { le := (≤), lt := (<), le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } /-- Given two ordinals `α ≤ β`, then `initial_seg_out α β` is the initial segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def initial_seg_out {α β : ordinal} (h : α ≤ β) : initial_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α < β`, then `principal_seg_out α β` is the principal segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def principal_seg_out {α β : ordinal} (h : α < β) : principal_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α = β`, then `rel_iso_out α β` is the order isomorphism between two model types for `α` and `β`. -/ def rel_iso_out {α β : ordinal} (h : α = β) : α.out.r ≃r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice ∘ quotient.exact end theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ ((subrel.rel_embedding _ _).trans f) (λ ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.2 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.1 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma typein_injective (r : α → α → Prop) [is_well_order α r] : injective (typein r) := injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2) theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := injective.eq_iff (typein_injective r) /-! ### Enumerating elements in a well-order with ordinals. -/ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (rel_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein /-- A well order `r` is order isomorphic to the set of ordinals strictly smaller than the ordinal version of `r`. -/ def typein_iso (r : α → α → Prop) [is_well_order α r] : r ≃r subrel (<) (< type r) := ⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, λ x, enum r x.1 x.2, λ y, enum_typein r y, λ ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩, λ a b, (typein_lt_typein r)⟩ theorem enum_lt {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) : r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma rel_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma rel_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := rel_iso_enum' _ _ _ _ theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- Principal segment version of the `typein` function, embedding a well order into ordinals as a principal segment. -/ def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨rel_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-! ### Cardinality of ordinals -/ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (λ ⟨α, r, _⟩, mk α) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = mk α := rfl lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) : mk {y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ instance : inhabited ordinal := ⟨0⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨empty_equiv_pempty.symm, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl protected theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, ⟨⟨⟨embedding.of_is_empty, is_empty_elim⟩, is_empty_elim⟩⟩ @[simp] protected theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := by simp only [le_antisymm_iff, ordinal.zero_le, and_true] protected theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := by simp only [lt_iff_le_and_ne, ordinal.zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨punit_equiv_punit, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl /-! ### Lifting ordinals to a higher universe -/ /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version, see `lift.initial_seg`. -/ def lift (o : ordinal.{u}) : ordinal.{max u v} := quotient.lift_on o (λ ⟨α, r, wo⟩, @type _ _ (@rel_embedding.is_well_order _ _ (@equiv.ulift.{v} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{v} r) wo)) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] : ∃ wo', lift (type r) = @type _ (@equiv.ulift.{v} α ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $ (rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) ≤ lift.{v (max u w)} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃r s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $ f.trans (rel_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r ≺i s) := by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max v w)} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{(max v w)} r) _; haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max u w)} β ⁻¹'o s) s (rel_iso.preimage equiv.ulift.{(max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨pempty_equiv_pempty, λ a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨punit_equiv_punit, λ a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (mk β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := rel_iso.preimage f s, haveI := (g : ⇑f ⁻¹'o s ↪r s).is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as an initial segment when `u ≤ v`. -/ def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{u v}, λ a b, lift_inj.1⟩, λ a b, lift_lt⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-! ### The first infinite ordinal `omega` -/ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ localized "notation `ω` := ordinal.omega.{0}" in ordinal theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /-! ### Definition and first properties of addition on ordinals In this paragraph, we introduce the addition on ordinals, and prove just enough properties to deduce that the order on ordinals is total (and therefore well-founded). Further properties of the addition, together with properties of the other operations, are proved in `ordinal_arithmetic.lean`. -/ /-- `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. -/ instance : has_add ordinal.{u} := ⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩ @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] @[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(empty_sum pempty α).symm, λ a b, sum.lex_inr_inr⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(sum_empty α pempty).symm, λ a b, sum.lex_inl_inl⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, λ a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_map f, λ a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, λ a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa only [add_zero] using add_le_add_left (ordinal.zero_le b) a theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c := induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hr₂ hs)).2 ⟨⟨f.sum_map (embedding.refl _), λ a b, begin split; intro H, { cases a with a a; cases b with b b; cases H; constructor; [rwa ← fo, assumption] }, { cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa only [zero_add] using add_le_add_right (ordinal.zero_le b) a theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩, λ _ _, sum.lex_inl_inl⟩, sum.inr punit.star, λ b, sum.rec_on b (λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩) (λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@rel_embedding.of_monotone (α ⊕ punit) β _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.map_rel_iff.2 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ h₂ end instance : linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } instance : is_well_order ordinal (<) := ⟨wf⟩ @[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} : typein r x ≤ typein r x' ↔ ¬r x' x := by rw [←not_lt, typein_lt_typein] lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' := by rw [←@not_lt _ _ o' o, enum_lt ho'] /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ /-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as a principal segment when `u < v`. -/ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, introsI α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.map_rel_iff.2 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, introsI α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{u (max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-! ### Minimum -/ /-- The minimal element of a nonempty family of ordinals -/ def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in ⟨_, set.mem_range_self i⟩) theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ι I} {f : ι → ordinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm ▸ h theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) end ordinal /-! ### Representing a cardinal with an ordinal -/ namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/ def ord (c : cardinal) : ordinal := begin let ι := λ α, {r // is_well_order α r}, have : Π α, ι α := λ α, ⟨well_ordering_rel, by apply_instance⟩, let F := λ α, ordinal.min ⟨this _⟩ (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, le_antisymm (this h) (this (setoid.symm h)), intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _), haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨rel_iso.preimage f i.1⟩, exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end lemma ord_eq_min (α : Type u) : ord (mk α) = @ordinal.min {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (mk α) = @type α r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (mk α) ≤ ordinal.type r := @ordinal.min_le {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := quotient.induction_on c $ λ α, induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp only [mk_def, card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := rel_embedding.preimage f s, haveI := rel_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := ord_le.2 (le_refl _) lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord := by { rw [lt_ord], apply cardinal.lt_succ_self } @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : ℕ) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end lemma mk_ord_out (c : cardinal) : mk c.ord.out.α = c := by rw [←card_type c.ord.out.r, type_out, card_ord] lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α) (h : ord (mk α) = type r) : card (typein r x) < mk α := by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein c.ord.out.r x) < c := by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`. -/ def ord.order_embedding : cardinal ↪o ordinal := rel_embedding.order_embedding_of_lt_embedding (rel_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2) @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ def univ := lift.{(u+1) v} (mk ordinal) theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{u (u+1)} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{u (max (u+1) v)} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl end ordinal