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
9a9157e3b16c3bb6127b9448bbb4d89aaba4e9ea
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/galois_stdlib/src/galois/data/rbtree.lean
ebcb3c7ad614e082a172f35983002f835e51129e
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
738
lean
/- This defines functionality that could be in data.rbmap -/ namespace rbnode universes u variables {α : Type u} variable (lt : α → α → Prop) instance mem.decidable [h : decidable_rel lt] (a : α) (m:rbnode α) : decidable (rbnode.mem lt a m) := begin induction m, { simp [mem], apply_instance }, { let p := h a m_val, let q := h m_val a, exact @or.decidable _ _ m_ih_lchild (@or.decidable _ _ (@and.decidable _ _ (@not.decidable _ p) (@not.decidable _ q)) m_ih_rchild), }, { let p := h a m_val, let q := h m_val a, exact @or.decidable _ _ m_ih_lchild (@or.decidable _ _ (@and.decidable _ _ (@not.decidable _ p) (@not.decidable _ q)) m_ih_rchild), }, end end rbnode
7f3efc08abbaa33cc620517e7417730e25b8bdfe
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/laurent.lean
d504346dd9d9f5dd516663551821b01a439791e2
[ "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,665
lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.polynomial.taylor import field_theory.ratfunc /-! # Laurent expansions of rational functions ## Main declarations * `ratfunc.laurent`: the Laurent expansion of the rational function `f` at `r`, as an `alg_hom`. * `ratfunc.laurent_injective`: the Laurent expansion at `r` is unique ## Implementation details Implemented as the quotient of two Taylor expansions, over domains. An auxiliary definition is provided first to make the construction of the `alg_hom` easier, which works on `comm_ring` which are not necessarily domains. -/ universe u namespace ratfunc noncomputable theory open polynomial open_locale classical non_zero_divisors polynomial variables {R : Type u} [comm_ring R] [hdomain : is_domain R] (r s : R) (p q : R[X]) (f : ratfunc R) lemma taylor_mem_non_zero_divisors (hp : p ∈ R[X]⁰) : taylor r p ∈ R[X]⁰ := begin rw mem_non_zero_divisors_iff, intros x hx, have : x = taylor (r - r) x, { simp }, rwa [this, sub_eq_add_neg, ←taylor_taylor, ←taylor_mul, linear_map.map_eq_zero_iff _ (taylor_injective _), mul_right_mem_non_zero_divisors_eq_zero_iff hp, linear_map.map_eq_zero_iff _ (taylor_injective _)] at hx, end /-- The Laurent expansion of rational functions about a value. Auxiliary definition, usage when over integral domains should prefer `ratfunc.laurent`. -/ def laurent_aux : ratfunc R →+* ratfunc R := ratfunc.map_ring_hom (ring_hom.mk (taylor r) (taylor_one _) (taylor_mul _) (linear_map.map_zero _) (linear_map.map_add _)) (taylor_mem_non_zero_divisors _) lemma laurent_aux_of_fraction_ring_mk (q : R[X]⁰) : laurent_aux r (of_fraction_ring (localization.mk p q)) = of_fraction_ring (localization.mk (taylor r p) ⟨taylor r q, taylor_mem_non_zero_divisors r q q.prop⟩) := map_apply_of_fraction_ring_mk _ _ _ _ include hdomain lemma laurent_aux_div : laurent_aux r (algebra_map _ _ p / (algebra_map _ _ q)) = algebra_map _ _ (taylor r p) / (algebra_map _ _ (taylor r q)) := map_apply_div _ _ _ _ @[simp] lemma laurent_aux_algebra_map : laurent_aux r (algebra_map _ _ p) = algebra_map _ _ (taylor r p) := by rw [←mk_one, ←mk_one, mk_eq_div, laurent_aux_div, mk_eq_div, taylor_one, _root_.map_one] /-- The Laurent expansion of rational functions about a value. -/ def laurent : ratfunc R →ₐ[R] ratfunc R := ratfunc.map_alg_hom (alg_hom.mk (taylor r) (taylor_one _) (taylor_mul _) (linear_map.map_zero _) (linear_map.map_add _) (by simp [polynomial.algebra_map_apply])) (taylor_mem_non_zero_divisors _) lemma laurent_div : laurent r (algebra_map _ _ p / (algebra_map _ _ q)) = algebra_map _ _ (taylor r p) / (algebra_map _ _ (taylor r q)) := laurent_aux_div r p q @[simp] lemma laurent_algebra_map : laurent r (algebra_map _ _ p) = algebra_map _ _ (taylor r p) := laurent_aux_algebra_map _ _ @[simp] lemma laurent_X : laurent r X = X + C r := by rw [←algebra_map_X, laurent_algebra_map, taylor_X, _root_.map_add, algebra_map_C] @[simp] lemma laurent_C (x : R) : laurent r (C x) = C x := by rw [←algebra_map_C, laurent_algebra_map, taylor_C] @[simp] lemma laurent_at_zero : laurent 0 f = f := by { induction f using ratfunc.induction_on, simp } lemma laurent_laurent : laurent r (laurent s f) = laurent (r + s) f := begin induction f using ratfunc.induction_on, simp_rw [laurent_div, taylor_taylor] end lemma laurent_injective : function.injective (laurent r) := λ _ _ h, by simpa [laurent_laurent] using congr_arg (laurent (-r)) h end ratfunc
22b1d2c70ce651a832f52a1341cd16d7cd09afa2
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/lattice.lean
4989a35e79a7c0680cf139cbc7d19b737106c80c
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
2,545
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.limits import category_theory.limits.shapes.finite_products import order.complete_lattice universes u open category_theory namespace category_theory.limits variables {α : Type u} @[priority 100] -- see Note [lower instance priority] instance has_finite_limits_of_semilattice_inf_top [semilattice_inf_top α] : has_finite_limits.{u} α := { has_limits_of_shape := λ J 𝒥₁ 𝒥₂, by exactI { has_limit := λ F, { cone := { X := finset.univ.inf F.obj, π := { app := λ j, ⟨⟨finset.inf_le (fintype.complete _)⟩⟩ } }, is_limit := { lift := λ s, ⟨⟨finset.le_inf (λ j _, (s.π.app j).down.down)⟩⟩ } } } } @[priority 100] -- see Note [lower instance priority] instance has_finite_colimits_of_semilattice_sup_bot [semilattice_sup_bot α] : has_finite_colimits.{u} α := { has_colimits_of_shape := λ J 𝒥₁ 𝒥₂, by exactI { has_colimit := λ F, { cocone := { X := finset.univ.sup F.obj, ι := { app := λ i, ⟨⟨finset.le_sup (fintype.complete _)⟩⟩ } }, is_colimit := { desc := λ s, ⟨⟨finset.sup_le (λ j _, (s.ι.app j).down.down)⟩⟩ } } } } -- It would be nice to only use the `Inf` half of the complete lattice, but -- this seems not to have been described separately. @[priority 100] -- see Note [lower instance priority] instance has_limits_of_complete_lattice [complete_lattice α] : has_limits.{u} α := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, { cone := { X := Inf (set.range F.obj), π := { app := λ j, ⟨⟨complete_lattice.Inf_le _ _ (set.mem_range_self _)⟩⟩ } }, is_limit := { lift := λ s, ⟨⟨complete_lattice.le_Inf _ _ begin rintros _ ⟨j, rfl⟩, exact (s.π.app j).down.down, end⟩⟩ } } } } @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_complete_lattice [complete_lattice α] : has_colimits.{u} α := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, { cocone := { X := Sup (set.range F.obj), ι := { app := λ j, ⟨⟨complete_lattice.le_Sup _ _ (set.mem_range_self _)⟩⟩ } }, is_colimit := { desc := λ s, ⟨⟨complete_lattice.Sup_le _ _ begin rintros _ ⟨j, rfl⟩, exact (s.ι.app j).down.down, end⟩⟩ } } } } end category_theory.limits
e1fa3262b2de5fc47f4e0cb8255236d92a27e614
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world7/level2.lean
7f18fa980791343645f3aab336b315c22959323c
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
2,524
lean
/- # Advanced proposition world. ## Level 2: the `cases` tactic. If `P ∧ Q` is in the goal, then we can make progress with `split`. But what if `P ∧ Q` is a hypothesis? In this case, the `cases` tactic will enable us to extract proofs of `P` and `Q` from this hypothesis. The lemma below asks us to prove `P ∧ Q → Q ∧ P`, that is, symmetry of the "and" relation. The obvious first move is `intro h,` because the goal is an implication and this tactic is guaranteed to make progress. Now `h : P ∧ Q` is a hypothesis, and `cases h with p q,` will change `h`, the proof of `P ∧ Q`, into two proofs `p : P` and `q : Q`. From there, `split` and `exact` will get you home. -/ /- Lemma If $P$ and $Q$ are true/false statements, then $P\land Q\implies Q\land P$. -/ lemma and_symm (P Q : Prop) : P ∧ Q → Q ∧ P := begin intro h, cases h with p q, split, exact q, exact p, end /- Tactic : cases ## Summary: `cases` is a tactic which works on hypotheses. If `h : P ∧ Q` or `h : P ↔ Q` is a hypothesis then `cases h with h1 h2` will remove `h` from the list of hypotheses and replace it with the "ingredients" of `h`, i.e. `h1 : P` and `h2 : Q`, or `h1 : P → Q` and `h2 : Q → P`. Also works with `h : P ∨ Q` and `n : mynat`. ## Details How does one prove `P ∧ Q`? The way to do it is to prove `P` and to prove `Q`. There are hence two ingredients which go into a proof of `P ∧ Q`, and the `cases` tactic extracts them. More precisely, if the local context contains ``` h : P ∧ Q` ``` then after the tactic `cases h with p q,` the local context will change to ``` p : P, q : Q ``` and `h` will disappear. Similarly `h : P ↔ Q` is proved by proving `P → Q` and `Q → P`, and `cases h with hpq hqp` will delete our assumption `h` and replace it with ``` hpq : P → Q, hqp : Q → P ``` Be warned though -- `rw h` works with `h : P ↔ Q` (`rw` works with `=` and `↔`), whereas you cannot rewrite with an implication. `cases` also works with hypotheses of the form `P ∨ Q` and even with `n : mynat`. Here the situation is different however. To prove `P ∨ Q` you need to give either a proof of `P` *or* a proof of `Q`, so if `h : P ∨ Q` then `cases h with p q` will change one goal into two, one with `p : P` and the other with `q : Q`. Similarly, each natural is either `0` or `succ(d)` for `d` another natural, so if `n : mynat` then `cases n with d` also turns one goal into two, one with `n = 0` and the other with `d : mynat` and `n = succ(d)`. -/
6413f09119fe550da320fd265437c6478b3eef11
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/tensor_product.lean
95948ab5228f1f7ab750bd464a4c32b919d7ca17
[ "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
29,134
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin -/ import linear_algebra.tensor_product_basis import ring_theory.adjoin.basic /-! # The tensor product of R-algebras Let `R` be a (semi)ring and `A` an `R`-algebra. In this file we: - Define the `A`-module structure on `A ⊗ M`, for an `R`-module `M`. - Define the `R`-algebra structure on `A ⊗ B`, for another `R`-algebra `B`. and provide the structure isomorphisms * `R ⊗[R] A ≃ₐ[R] A` * `A ⊗[R] R ≃ₐ[R] A` * `A ⊗[R] B ≃ₐ[R] B ⊗[R] A` * `((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C))` ## Main declaration - `linear_map.base_change A f` is the `A`-linear map `A ⊗ f`, for an `R`-linear map `f`. ## Implementation notes The heterobasic definitions below such as: * `tensor_product.algebra_tensor_module.curry` * `tensor_product.algebra_tensor_module.uncurry` * `tensor_product.algebra_tensor_module.lcurry` * `tensor_product.algebra_tensor_module.lift` * `tensor_product.algebra_tensor_module.lift.equiv` * `tensor_product.algebra_tensor_module.mk` * `tensor_product.algebra_tensor_module.assoc` are just more general versions of the definitions already in `linear_algebra/tensor_product`. We could thus consider replacing the less general definitions with these ones. If we do this, we probably should still implement the less general ones as abbreviations to the more general ones with fewer type arguments. -/ universes u v₁ v₂ v₃ v₄ open_locale tensor_product open tensor_product namespace tensor_product variables {R A M N P : Type*} /-! ### The `A`-module structure on `A ⊗[R] M` -/ open linear_map open algebra (lsmul) namespace algebra_tensor_module section semiring 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 [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] [module A P] [is_scalar_tower R A P] lemma smul_eq_lsmul_rtensor (a : A) (x : M ⊗[R] N) : a • x = (lsmul R M a).rtensor N x := rfl /-- Heterobasic version of `tensor_product.curry`: Given a linear map `M ⊗[R] N →[A] P`, compose it with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` to form a bilinear map `M →[A] N →[R] P`. -/ @[simps] def curry (f : (M ⊗[R] N) →ₗ[A] P) : M →ₗ[A] (N →ₗ[R] P) := { map_smul' := λ c x, linear_map.ext $ λ y, f.map_smul c (x ⊗ₜ y), .. curry (f.restrict_scalars R) } lemma restrict_scalars_curry (f : (M ⊗[R] N) →ₗ[A] P) : restrict_scalars R (curry f) = curry (f.restrict_scalars R) := rfl /-- Just as `tensor_product.ext` is marked `ext` instead of `tensor_product.ext'`, this is a better `ext` lemma than `tensor_product.algebra_tensor_module.ext` below. See note [partially-applied ext lemmas]. -/ @[ext] lemma curry_injective : function.injective (curry : (M ⊗ N →ₗ[A] P) → (M →ₗ[A] N →ₗ[R] P)) := λ x y h, linear_map.restrict_scalars_injective R $ curry_injective $ (congr_arg (linear_map.restrict_scalars R) h : _) theorem ext {g h : (M ⊗[R] N) →ₗ[A] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := curry_injective $ linear_map.ext₂ H end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables [add_comm_monoid N] [module R N] variables [add_comm_monoid P] [module R P] [module A P] [is_scalar_tower R A P] /-- Heterobasic version of `tensor_product.lift`: Constructing a linear map `M ⊗[R] N →[A] P` given a bilinear map `M →[A] N →[R] P` with the property that its composition with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` is the given bilinear map `M →[A] N →[R] P`. -/ @[simps] def lift (f : M →ₗ[A] (N →ₗ[R] P)) : (M ⊗[R] N) →ₗ[A] P := { map_smul' := λ c, show ∀ x : M ⊗[R] N, (lift (f.restrict_scalars R)).comp (lsmul R _ c) x = (lsmul R _ c).comp (lift (f.restrict_scalars R)) x, from ext_iff.1 $ tensor_product.ext' $ λ x y, by simp only [comp_apply, algebra.lsmul_coe, smul_tmul', lift.tmul, coe_restrict_scalars_eq_coe, f.map_smul, smul_apply], .. lift (f.restrict_scalars R) } @[simp] lemma lift_tmul (f : M →ₗ[A] (N →ₗ[R] P)) (x : M) (y : N) : lift f (x ⊗ₜ y) = f x y := lift.tmul' x y variables (R A M N P) /-- Heterobasic version of `tensor_product.uncurry`: Linearly constructing a linear map `M ⊗[R] N →[A] P` given a bilinear map `M →[A] N →[R] P` with the property that its composition with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` is the given bilinear map `M →[A] N →[R] P`. -/ @[simps] def uncurry : (M →ₗ[A] (N →ₗ[R] P)) →ₗ[A] ((M ⊗[R] N) →ₗ[A] P) := { to_fun := lift, map_add' := λ f g, ext $ λ x y, by simp only [lift_tmul, add_apply], map_smul' := λ c f, ext $ λ x y, by simp only [lift_tmul, smul_apply, ring_hom.id_apply] } /-- Heterobasic version of `tensor_product.lcurry`: Given a linear map `M ⊗[R] N →[A] P`, compose it with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` to form a bilinear map `M →[A] N →[R] P`. -/ @[simps] def lcurry : ((M ⊗[R] N) →ₗ[A] P) →ₗ[A] (M →ₗ[A] (N →ₗ[R] P)) := { to_fun := curry, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } /-- Heterobasic version of `tensor_product.lift.equiv`: A linear equivalence constructing a linear map `M ⊗[R] N →[A] P` given a bilinear map `M →[A] N →[R] P` with the property that its composition with the canonical bilinear map `M →[A] N →[R] M ⊗[R] N` is the given bilinear map `M →[A] N →[R] P`. -/ def lift.equiv : (M →ₗ[A] (N →ₗ[R] P)) ≃ₗ[A] ((M ⊗[R] N) →ₗ[A] P) := linear_equiv.of_linear (uncurry R A M N P) (lcurry R A M N P) (linear_map.ext $ λ f, ext $ λ x y, lift_tmul _ x y) (linear_map.ext $ λ f, linear_map.ext $ λ x, linear_map.ext $ λ y, lift_tmul f x y) variables (R A M N P) /-- Heterobasic version of `tensor_product.mk`: The canonical bilinear map `M →[A] N →[R] M ⊗[R] N`. -/ @[simps] def mk : M →ₗ[A] N →ₗ[R] M ⊗[R] N := { map_smul' := λ c x, rfl, .. mk R M N } local attribute [ext] tensor_product.ext /-- Heterobasic version of `tensor_product.assoc`: Linear equivalence between `(M ⊗[A] N) ⊗[R] P` and `M ⊗[A] (N ⊗[R] P)`. -/ def assoc : ((M ⊗[A] P) ⊗[R] N) ≃ₗ[A] (M ⊗[A] (P ⊗[R] N)) := linear_equiv.of_linear (lift $ tensor_product.uncurry A _ _ _ $ comp (lcurry R A _ _ _) $ tensor_product.mk A M (P ⊗[R] N)) (tensor_product.uncurry A _ _ _ $ comp (uncurry R A _ _ _) $ by { apply tensor_product.curry, exact (mk R A _ _) }) (by { ext, refl, }) (by { ext, simp only [curry_apply, tensor_product.curry_apply, mk_apply, tensor_product.mk_apply, uncurry_apply, tensor_product.uncurry_apply, id_apply, lift_tmul, compr₂_apply, restrict_scalars_apply, function.comp_app, to_fun_eq_coe, lcurry_apply, linear_map.comp_apply] }) end comm_semiring end algebra_tensor_module end tensor_product namespace linear_map open tensor_product /-! ### The base-change of a linear map of `R`-modules to a linear map of `A`-modules -/ section semiring variables {R A B M N : Type*} [comm_semiring R] variables [semiring A] [algebra R A] [semiring B] [algebra R B] variables [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] variables (r : R) (f g : M →ₗ[R] N) variables (A) /-- `base_change A f` for `f : M →ₗ[R] N` is the `A`-linear map `A ⊗[R] M →ₗ[A] A ⊗[R] N`. -/ def base_change (f : M →ₗ[R] N) : A ⊗[R] M →ₗ[A] A ⊗[R] N := { to_fun := f.ltensor A, map_add' := (f.ltensor A).map_add, map_smul' := λ a x, show (f.ltensor A) (rtensor M (algebra.lmul R A a) x) = (rtensor N ((algebra.lmul R A) a)) ((ltensor A f) x), by { rw [← comp_apply, ← comp_apply], simp only [ltensor_comp_rtensor, rtensor_comp_ltensor] } } variables {A} @[simp] lemma base_change_tmul (a : A) (x : M) : f.base_change A (a ⊗ₜ x) = a ⊗ₜ (f x) := rfl lemma base_change_eq_ltensor : (f.base_change A : A ⊗ M → A ⊗ N) = f.ltensor A := rfl @[simp] lemma base_change_add : (f + g).base_change A = f.base_change A + g.base_change A := by { ext, simp [base_change_eq_ltensor], } @[simp] lemma base_change_zero : base_change A (0 : M →ₗ[R] N) = 0 := by { ext, simp [base_change_eq_ltensor], } @[simp] lemma base_change_smul : (r • f).base_change A = r • (f.base_change A) := by { ext, simp [base_change_tmul], } variables (R A M N) /-- `base_change` as a linear map. -/ @[simps] def base_change_hom : (M →ₗ[R] N) →ₗ[R] A ⊗[R] M →ₗ[A] A ⊗[R] N := { to_fun := base_change A, map_add' := base_change_add, map_smul' := base_change_smul } end semiring section ring variables {R A B M N : Type*} [comm_ring R] variables [ring A] [algebra R A] [ring B] [algebra R B] variables [add_comm_group M] [module R M] [add_comm_group N] [module R N] variables (f g : M →ₗ[R] N) @[simp] lemma base_change_sub : (f - g).base_change A = f.base_change A - g.base_change A := by { ext, simp [base_change_eq_ltensor], } @[simp] lemma base_change_neg : (-f).base_change A = -(f.base_change A) := by { ext, simp [base_change_eq_ltensor], } end ring end linear_map namespace algebra namespace tensor_product section semiring variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type v₂} [semiring B] [algebra R B] /-! ### The `R`-algebra structure on `A ⊗[R] B` -/ /-- (Implementation detail) The multiplication map on `A ⊗[R] B`, for a fixed pure tensor in the first argument, as an `R`-linear map. -/ def mul_aux (a₁ : A) (b₁ : B) : (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) := tensor_product.map (lmul_left R a₁) (lmul_left R b₁) @[simp] lemma mul_aux_apply (a₁ a₂ : A) (b₁ b₂ : B) : (mul_aux a₁ b₁) (a₂ ⊗ₜ[R] b₂) = (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂) := rfl /-- (Implementation detail) The multiplication map on `A ⊗[R] B`, as an `R`-bilinear map. -/ def mul : (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) := tensor_product.lift $ linear_map.mk₂ R mul_aux (λ x₁ x₂ y, tensor_product.ext' $ λ x' y', by simp only [mul_aux_apply, linear_map.add_apply, add_mul, add_tmul]) (λ c x y, tensor_product.ext' $ λ x' y', by simp only [mul_aux_apply, linear_map.smul_apply, smul_tmul', smul_mul_assoc]) (λ x y₁ y₂, tensor_product.ext' $ λ x' y', by simp only [mul_aux_apply, linear_map.add_apply, add_mul, tmul_add]) (λ c x y, tensor_product.ext' $ λ x' y', by simp only [mul_aux_apply, linear_map.smul_apply, smul_tmul, smul_tmul', smul_mul_assoc]) @[simp] lemma mul_apply (a₁ a₂ : A) (b₁ b₂ : B) : mul (a₁ ⊗ₜ[R] b₁) (a₂ ⊗ₜ[R] b₂) = (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂) := rfl lemma mul_assoc' (mul : (A ⊗[R] B) →ₗ[R] (A ⊗[R] B) →ₗ[R] (A ⊗[R] B)) (h : ∀ (a₁ a₂ a₃ : A) (b₁ b₂ b₃ : B), mul (mul (a₁ ⊗ₜ[R] b₁) (a₂ ⊗ₜ[R] b₂)) (a₃ ⊗ₜ[R] b₃) = mul (a₁ ⊗ₜ[R] b₁) (mul (a₂ ⊗ₜ[R] b₂) (a₃ ⊗ₜ[R] b₃))) : ∀ (x y z : A ⊗[R] B), mul (mul x y) z = mul x (mul y z) := begin intros, apply tensor_product.induction_on x, { simp only [linear_map.map_zero, linear_map.zero_apply], }, apply tensor_product.induction_on y, { simp only [linear_map.map_zero, forall_const, linear_map.zero_apply], }, apply tensor_product.induction_on z, { simp only [linear_map.map_zero, forall_const], }, { intros, simp only [h], }, { intros, simp only [linear_map.map_add, *], }, { intros, simp only [linear_map.map_add, *, linear_map.add_apply], }, { intros, simp only [linear_map.map_add, *, linear_map.add_apply], }, end lemma mul_assoc (x y z : A ⊗[R] B) : mul (mul x y) z = mul x (mul y z) := mul_assoc' mul (by { intros, simp only [mul_apply, mul_assoc], }) x y z lemma one_mul (x : A ⊗[R] B) : mul (1 ⊗ₜ 1) x = x := begin apply tensor_product.induction_on x; simp {contextual := tt}, end lemma mul_one (x : A ⊗[R] B) : mul x (1 ⊗ₜ 1) = x := begin apply tensor_product.induction_on x; simp {contextual := tt}, end instance : semiring (A ⊗[R] B) := { zero := 0, add := (+), one := 1 ⊗ₜ 1, mul := λ a b, mul a b, one_mul := one_mul, mul_one := mul_one, mul_assoc := mul_assoc, zero_mul := by simp, mul_zero := by simp, left_distrib := by simp, right_distrib := by simp, .. (by apply_instance : add_comm_monoid (A ⊗[R] B)) }. lemma one_def : (1 : A ⊗[R] B) = (1 : A) ⊗ₜ (1 : B) := rfl @[simp] lemma tmul_mul_tmul (a₁ a₂ : A) (b₁ b₂ : B) : (a₁ ⊗ₜ[R] b₁) * (a₂ ⊗ₜ[R] b₂) = (a₁ * a₂) ⊗ₜ[R] (b₁ * b₂) := rfl @[simp] lemma tmul_pow (a : A) (b : B) (k : ℕ) : (a ⊗ₜ[R] b)^k = (a^k) ⊗ₜ[R] (b^k) := begin induction k with k ih, { simp [one_def], }, { simp [pow_succ, ih], } end /-- The algebra map `R →+* (A ⊗[R] B)` giving `A ⊗[R] B` the structure of an `R`-algebra. -/ def tensor_algebra_map : R →+* (A ⊗[R] B) := { to_fun := λ r, algebra_map R A r ⊗ₜ[R] 1, map_one' := by { simp, refl }, map_mul' := by simp, map_zero' := by simp [zero_tmul], map_add' := by simp [add_tmul], } instance : algebra R (A ⊗[R] B) := { commutes' := λ r x, begin apply tensor_product.induction_on x, { simp, }, { intros a b, simp [tensor_algebra_map, algebra.commutes], }, { intros y y' h h', simp at h h', simp [mul_add, add_mul, h, h'], }, end, smul_def' := λ r x, begin apply tensor_product.induction_on x, { simp [smul_zero], }, { intros a b, rw [tensor_algebra_map, ←tmul_smul, ←smul_tmul, algebra.smul_def r a], simp, }, { intros, dsimp, simp [smul_add, mul_add, *], }, end, .. tensor_algebra_map, .. (by apply_instance : module R (A ⊗[R] B)) }. @[simp] lemma algebra_map_apply (r : R) : (algebra_map R (A ⊗[R] B)) r = ((algebra_map R A) r) ⊗ₜ[R] 1 := rfl variables {C : Type v₃} [semiring C] [algebra R C] @[ext] theorem ext {g h : (A ⊗[R] B) →ₐ[R] C} (H : ∀ a b, g (a ⊗ₜ b) = h (a ⊗ₜ b)) : g = h := begin apply @alg_hom.to_linear_map_injective R (A ⊗[R] B) C _ _ _ _ _ _ _ _, ext, simp [H], end /-- The algebra morphism `A →ₐ[R] A ⊗[R] B` sending `a` to `a ⊗ₜ 1`. -/ def include_left : A →ₐ[R] A ⊗[R] B := { to_fun := λ a, a ⊗ₜ 1, map_zero' := by simp, map_add' := by simp [add_tmul], map_one' := rfl, map_mul' := by simp, commutes' := by simp, } @[simp] lemma include_left_apply (a : A) : (include_left : A →ₐ[R] A ⊗[R] B) a = a ⊗ₜ 1 := rfl /-- The algebra morphism `B →ₐ[R] A ⊗[R] B` sending `b` to `1 ⊗ₜ b`. -/ def include_right : B →ₐ[R] A ⊗[R] B := { to_fun := λ b, 1 ⊗ₜ b, map_zero' := by simp, map_add' := by simp [tmul_add], map_one' := rfl, map_mul' := by simp, commutes' := λ r, begin simp only [algebra_map_apply], transitivity r • ((1 : A) ⊗ₜ[R] (1 : B)), { rw [←tmul_smul, algebra.smul_def], simp, }, { simp [algebra.smul_def], }, end, } @[simp] lemma include_right_apply (b : B) : (include_right : B →ₐ[R] A ⊗[R] B) b = 1 ⊗ₜ b := rfl end semiring section ring variables {R : Type u} [comm_ring R] variables {A : Type v₁} [ring A] [algebra R A] variables {B : Type v₂} [ring B] [algebra R B] instance : ring (A ⊗[R] B) := { .. (by apply_instance : add_comm_group (A ⊗[R] B)), .. (by apply_instance : semiring (A ⊗[R] B)) }. end ring section comm_ring variables {R : Type u} [comm_ring R] variables {A : Type v₁} [comm_ring A] [algebra R A] variables {B : Type v₂} [comm_ring B] [algebra R B] instance : comm_ring (A ⊗[R] B) := { mul_comm := λ x y, begin apply tensor_product.induction_on x, { simp, }, { intros a₁ b₁, apply tensor_product.induction_on y, { simp, }, { intros a₂ b₂, simp [mul_comm], }, { intros a₂ b₂ ha hb, simp [mul_add, add_mul, ha, hb], }, }, { intros x₁ x₂ h₁ h₂, simp [mul_add, add_mul, h₁, h₂], }, end .. (by apply_instance : ring (A ⊗[R] B)) }. end comm_ring /-- Verify that typeclass search finds the ring structure on `A ⊗[ℤ] B` when `A` and `B` are merely rings, by treating both as `ℤ`-algebras. -/ example {A : Type v₁} [ring A] {B : Type v₂} [ring B] : ring (A ⊗[ℤ] B) := by apply_instance /-- Verify that typeclass search finds the comm_ring structure on `A ⊗[ℤ] B` when `A` and `B` are merely comm_rings, by treating both as `ℤ`-algebras. -/ example {A : Type v₁} [comm_ring A] {B : Type v₂} [comm_ring B] : comm_ring (A ⊗[ℤ] B) := by apply_instance /-! We now build the structure maps for the symmetric monoidal category of `R`-algebras. -/ section monoidal section variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type v₂} [semiring B] [algebra R B] variables {C : Type v₃} [semiring C] [algebra R C] variables {D : Type v₄} [semiring D] [algebra R D] /-- Build an algebra morphism from a linear map out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_hom_of_linear_map_tensor_product (f : A ⊗[R] B →ₗ[R] C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), f ((a₁ * a₂) ⊗ₜ (b₁ * b₂)) = f (a₁ ⊗ₜ b₁) * f (a₂ ⊗ₜ b₂)) (w₂ : ∀ r, f ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R C) r): A ⊗[R] B →ₐ[R] C := { map_one' := by rw [←(algebra_map R C).map_one, ←w₂, (algebra_map R A).map_one]; refl, map_zero' := by rw [linear_map.to_fun_eq_coe, map_zero], map_mul' := λ x y, by { rw linear_map.to_fun_eq_coe, apply tensor_product.induction_on x, { rw [zero_mul, map_zero, zero_mul] }, { intros a₁ b₁, apply tensor_product.induction_on y, { rw [mul_zero, map_zero, mul_zero] }, { intros a₂ b₂, rw [tmul_mul_tmul, w₁] }, { intros x₁ x₂ h₁ h₂, rw [mul_add, map_add, map_add, mul_add, h₁, h₂] } }, { intros x₁ x₂ h₁ h₂, rw [add_mul, map_add, map_add, add_mul, h₁, h₂] } }, commutes' := λ r, by rw [linear_map.to_fun_eq_coe, algebra_map_apply, w₂], .. f } @[simp] lemma alg_hom_of_linear_map_tensor_product_apply (f w₁ w₂ x) : (alg_hom_of_linear_map_tensor_product f w₁ w₂ : A ⊗[R] B →ₐ[R] C) x = f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_tensor_product (f : A ⊗[R] B ≃ₗ[R] C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), f ((a₁ * a₂) ⊗ₜ (b₁ * b₂)) = f (a₁ ⊗ₜ b₁) * f (a₂ ⊗ₜ b₂)) (w₂ : ∀ r, f ((algebra_map R A) r ⊗ₜ[R] 1) = (algebra_map R C) r): A ⊗[R] B ≃ₐ[R] C := { .. alg_hom_of_linear_map_tensor_product (f : A ⊗[R] B →ₗ[R] C) w₁ w₂, .. f } @[simp] lemma alg_equiv_of_linear_equiv_tensor_product_apply (f w₁ w₂ x) : (alg_equiv_of_linear_equiv_tensor_product f w₁ w₂ : A ⊗[R] B ≃ₐ[R] C) x = f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a triple tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_triple_tensor_product (f : ((A ⊗[R] B) ⊗[R] C) ≃ₗ[R] D) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C), f ((a₁ * a₂) ⊗ₜ (b₁ * b₂) ⊗ₜ (c₁ * c₂)) = f (a₁ ⊗ₜ b₁ ⊗ₜ c₁) * f (a₂ ⊗ₜ b₂ ⊗ₜ c₂)) (w₂ : ∀ r, f (((algebra_map R A) r ⊗ₜ[R] (1 : B)) ⊗ₜ[R] (1 : C)) = (algebra_map R D) r) : (A ⊗[R] B) ⊗[R] C ≃ₐ[R] D := { to_fun := f, map_mul' := λ x y, begin apply tensor_product.induction_on x, { simp only [map_zero, zero_mul] }, { intros ab₁ c₁, apply tensor_product.induction_on y, { simp only [map_zero, mul_zero] }, { intros ab₂ c₂, apply tensor_product.induction_on ab₁, { simp only [zero_tmul, map_zero, zero_mul] }, { intros a₁ b₁, apply tensor_product.induction_on ab₂, { simp only [zero_tmul, map_zero, mul_zero] }, { intros, simp only [tmul_mul_tmul, w₁] }, { intros x₁ x₂ h₁ h₂, simp only [tmul_mul_tmul] at h₁ h₂, simp only [tmul_mul_tmul, mul_add, add_tmul, map_add, h₁, h₂] } }, { intros x₁ x₂ h₁ h₂, simp only [tmul_mul_tmul] at h₁ h₂, simp only [tmul_mul_tmul, add_mul, add_tmul, map_add, h₁, h₂] } }, { intros x₁ x₂ h₁ h₂, simp only [tmul_mul_tmul, map_add, mul_add, add_mul, h₁, h₂], }, }, { intros x₁ x₂ h₁ h₂, simp only [tmul_mul_tmul, map_add, mul_add, add_mul, h₁, h₂], } end, commutes' := λ r, by simp [w₂], .. f } @[simp] lemma alg_equiv_of_linear_equiv_triple_tensor_product_apply (f w₁ w₂ x) : (alg_equiv_of_linear_equiv_triple_tensor_product f w₁ w₂ : (A ⊗[R] B) ⊗[R] C ≃ₐ[R] D) x = f x := rfl end variables {R : Type u} [comm_semiring R] variables {A : Type v₁} [semiring A] [algebra R A] variables {B : Type v₂} [semiring B] [algebra R B] variables {C : Type v₃} [semiring C] [algebra R C] variables {D : Type v₄} [semiring D] [algebra R D] section variables (R A) /-- The base ring is a left identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def lid : R ⊗[R] A ≃ₐ[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.lid R A) (by simp [mul_smul]) (by simp [algebra.smul_def]) @[simp] theorem lid_tmul (r : R) (a : A) : (tensor_product.lid R A : (R ⊗ A → A)) (r ⊗ₜ a) = r • a := by simp [tensor_product.lid] /-- The base ring is a right identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def rid : A ⊗[R] R ≃ₐ[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.rid R A) (by simp [mul_smul]) (by simp [algebra.smul_def]) @[simp] theorem rid_tmul (r : R) (a : A) : (tensor_product.rid R A : (A ⊗ R → A)) (a ⊗ₜ r) = r • a := by simp [tensor_product.rid] section variables (R A B) /-- The tensor product of R-algebras is commutative, up to algebra isomorphism. -/ protected def comm : A ⊗[R] B ≃ₐ[R] B ⊗[R] A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.comm R A B) (by simp) (λ r, begin transitivity r • ((1 : B) ⊗ₜ[R] (1 : A)), { rw [←tmul_smul, algebra.smul_def], simp, }, { simp [algebra.smul_def], }, end) @[simp] theorem comm_tmul (a : A) (b : B) : (tensor_product.comm R A B : (A ⊗[R] B → B ⊗[R] A)) (a ⊗ₜ b) = (b ⊗ₜ a) := by simp [tensor_product.comm] lemma adjoin_tmul_eq_top : adjoin R {t : A ⊗[R] B | ∃ a b, a ⊗ₜ[R] b = t} = ⊤ := top_le_iff.mp $ (top_le_iff.mpr $ span_tmul_eq_top R A B).trans (span_le_adjoin R _) end section variables {R A B C} lemma assoc_aux_1 (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C) : (tensor_product.assoc R A B C) (((a₁ * a₂) ⊗ₜ[R] (b₁ * b₂)) ⊗ₜ[R] (c₁ * c₂)) = (tensor_product.assoc R A B C) ((a₁ ⊗ₜ[R] b₁) ⊗ₜ[R] c₁) * (tensor_product.assoc R A B C) ((a₂ ⊗ₜ[R] b₂) ⊗ₜ[R] c₂) := rfl lemma assoc_aux_2 (r : R) : (tensor_product.assoc R A B C) (((algebra_map R A) r ⊗ₜ[R] 1) ⊗ₜ[R] 1) = (algebra_map R (A ⊗ (B ⊗ C))) r := rfl variables (R A B C) /-- The associator for tensor product of R-algebras, as an algebra isomorphism. -/ protected def assoc : ((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C)) := alg_equiv_of_linear_equiv_triple_tensor_product (tensor_product.assoc.{u v₁ v₂ v₃} R A B C : (A ⊗ B ⊗ C) ≃ₗ[R] (A ⊗ (B ⊗ C))) (@algebra.tensor_product.assoc_aux_1.{u v₁ v₂ v₃} R _ A _ _ B _ _ C _ _) (@algebra.tensor_product.assoc_aux_2.{u v₁ v₂ v₃} R _ A _ _ B _ _ C _ _) variables {R A B C} @[simp] theorem assoc_tmul (a : A) (b : B) (c : C) : ((tensor_product.assoc R A B C) : (A ⊗[R] B) ⊗[R] C → A ⊗[R] (B ⊗[R] C)) ((a ⊗ₜ b) ⊗ₜ c) = a ⊗ₜ (b ⊗ₜ c) := rfl end variables {R A B C D} /-- The tensor product of a pair of algebra morphisms. -/ def map (f : A →ₐ[R] B) (g : C →ₐ[R] D) : A ⊗[R] C →ₐ[R] B ⊗[R] D := alg_hom_of_linear_map_tensor_product (tensor_product.map f.to_linear_map g.to_linear_map) (by simp) (by simp [alg_hom.commutes]) @[simp] theorem map_tmul (f : A →ₐ[R] B) (g : C →ₐ[R] D) (a : A) (c : C) : map f g (a ⊗ₜ c) = f a ⊗ₜ g c := rfl @[simp] lemma map_comp_include_left (f : A →ₐ[R] B) (g : C →ₐ[R] D) : (map f g).comp include_left = include_left.comp f := alg_hom.ext $ by simp @[simp] lemma map_comp_include_right (f : A →ₐ[R] B) (g : C →ₐ[R] D) : (map f g).comp include_right = include_right.comp g := alg_hom.ext $ by simp lemma map_range (f : A →ₐ[R] B) (g : C →ₐ[R] D) : (map f g).range = (include_left.comp f).range ⊔ (include_right.comp g).range := begin apply le_antisymm, { rw [←map_top, ←adjoin_tmul_eq_top, ←adjoin_image, adjoin_le_iff], rintros _ ⟨_, ⟨a, b, rfl⟩, rfl⟩, rw [map_tmul, ←_root_.mul_one (f a), ←_root_.one_mul (g b), ←tmul_mul_tmul], exact mul_mem_sup (alg_hom.mem_range_self _ a) (alg_hom.mem_range_self _ b) }, { rw [←map_comp_include_left f g, ←map_comp_include_right f g], exact sup_le (alg_hom.range_comp_le_range _ _) (alg_hom.range_comp_le_range _ _) }, end /-- Construct an isomorphism between tensor products of R-algebras from isomorphisms between the tensor factors. -/ def congr (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) : A ⊗[R] C ≃ₐ[R] B ⊗[R] D := alg_equiv.of_alg_hom (map f g) (map f.symm g.symm) (ext $ λ b d, by simp) (ext $ λ a c, by simp) @[simp] lemma congr_apply (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) (x) : congr f g x = (map (f : A →ₐ[R] B) (g : C →ₐ[R] D)) x := rfl @[simp] lemma congr_symm_apply (f : A ≃ₐ[R] B) (g : C ≃ₐ[R] D) (x) : (congr f g).symm x = (map (f.symm : B →ₐ[R] A) (g.symm : D →ₐ[R] C)) x := rfl end end monoidal section variables {R A B S : Type*} [comm_semiring R] [semiring A] [semiring B] [comm_semiring S] variables [algebra R A] [algebra R B] [algebra R S] variables (f : A →ₐ[R] S) (g : B →ₐ[R] S) variables (R) /-- `algebra.lmul'` is an alg_hom on commutative rings. -/ def lmul' : S ⊗[R] S →ₐ[R] S := alg_hom_of_linear_map_tensor_product (algebra.lmul' R) (λ a₁ a₂ b₁ b₂, by simp only [algebra.lmul'_apply, mul_mul_mul_comm]) (λ r, by simp only [algebra.lmul'_apply, _root_.mul_one]) variables {R} lemma lmul'_to_linear_map : (lmul' R : _ →ₐ[R] S).to_linear_map = algebra.lmul' R := rfl @[simp] lemma lmul'_apply_tmul (a b : S) : lmul' R (a ⊗ₜ[R] b) = a * b := lmul'_apply @[simp] lemma lmul'_comp_include_left : (lmul' R : _ →ₐ[R] S).comp include_left = alg_hom.id R S := alg_hom.ext $ λ _, (lmul'_apply_tmul _ _).trans (_root_.mul_one _) @[simp] lemma lmul'_comp_include_right : (lmul' R : _ →ₐ[R] S).comp include_right = alg_hom.id R S := alg_hom.ext $ λ _, (lmul'_apply_tmul _ _).trans (_root_.one_mul _) /-- If `S` is commutative, for a pair of morphisms `f : A →ₐ[R] S`, `g : B →ₐ[R] S`, We obtain a map `A ⊗[R] B →ₐ[R] S` that commutes with `f`, `g` via `a ⊗ b ↦ f(a) * g(b)`. -/ def product_map : A ⊗[R] B →ₐ[R] S := (lmul' R).comp (tensor_product.map f g) @[simp] lemma product_map_apply_tmul (a : A) (b : B) : product_map f g (a ⊗ₜ b) = f a * g b := by { unfold product_map lmul', simp } lemma product_map_left_apply (a : A) : product_map f g (include_left a) = f a := by simp @[simp] lemma product_map_left : (product_map f g).comp include_left = f := alg_hom.ext $ by simp lemma product_map_right_apply (b : B) : product_map f g (include_right b) = g b := by simp @[simp] lemma product_map_right : (product_map f g).comp include_right = g := alg_hom.ext $ by simp lemma product_map_range : (product_map f g).range = f.range ⊔ g.range := by rw [product_map, alg_hom.range_comp, map_range, map_sup, ←alg_hom.range_comp, ←alg_hom.range_comp, ←alg_hom.comp_assoc, ←alg_hom.comp_assoc, lmul'_comp_include_left, lmul'_comp_include_right, alg_hom.id_comp, alg_hom.id_comp] end end tensor_product end algebra lemma subalgebra.finite_dimensional_sup {K L : Type*} [field K] [comm_ring L] [algebra K L] (E1 E2 : subalgebra K L) [finite_dimensional K E1] [finite_dimensional K E2] : finite_dimensional K ↥(E1 ⊔ E2) := begin rw [←E1.range_val, ←E2.range_val, ←algebra.tensor_product.product_map_range], exact (algebra.tensor_product.product_map E1.val E2.val).to_linear_map.finite_dimensional_range, end
f70b1b12a01c12be5c1f58c584ca30e34559d067
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/inner_product_space/basic.lean
251be997c4c7c806451c4558fc7da78d3fefd9d6
[ "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
109,331
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import algebra.direct_sum.module import analysis.complex.basic import analysis.convex.uniform import analysis.normed_space.completion import analysis.normed_space.bounded_linear_maps /-! # Inner product space This file defines inner product spaces and proves the basic properties. We do not formally define Hilbert spaces, but they can be obtained using the pair of assumptions `[inner_product_space 𝕜 E] [complete_space E]`. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.inner_product_space.pi_L2`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that the inner product is continuous, `continuous_inner`, and bundle it as the the continuous sesquilinear map `innerSL` (see also `innerₛₗ` for the non-continuous version). - We define `orthonormal`, a predicate on a function `v : ι → E`, and prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`. Bessel's inequality, `orthonormal.tsum_inner_products_le`, states that given an orthonormal set `v` and a vector `x`, the sum of the norm-squares of the inner products `⟪v i, x⟫` is no more than the norm-square of `x`. For the existence of orthonormal bases, Hilbert bases, etc., see the file `analysis.inner_product_space.projection`. - The `orthogonal_complement` of a submodule `K` is defined, and basic API established. Some of the more subtle results about the orthogonal complement are delayed to `analysis.inner_product_space.projection`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, Hilbert space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators topological_space complex_conjugate variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation (name := inner.real) `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation (name := inner.complex) `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `‖x‖^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_add_comm_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ‖x‖^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_add_comm_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_nonempty_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := star_ring_end _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- **Cauchy–Schwarz inequality**. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul, add_monoid_hom.map_add, mul_re, conj_im, add_monoid_hom.map_sub, mul_neg, conj_re, neg_neg] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, map_div₀, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw ←mul_div_right_comm ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ‖x‖ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_mul_norm (x : F) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ‖x‖ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_mul_norm], ring, }, rw H, conv begin to_lhs, congr, rw [inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_add_comm_group : normed_add_comm_group F := add_group_norm.to_normed_add_comm_group { to_fun := λ x, sqrt (re ⟪x, x⟫), map_zero' := by simp only [sqrt_zero, inner_zero_right, map_zero], neg' := λ x, by simp only [inner_neg_left, neg_neg, inner_neg_right], add_le' := λ x y, begin have h₁ : abs ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ‖x‖ * ‖y‖ := by rwa [←inner_conj_sym, conj_re], have : ‖x + y‖ * ‖x + y‖ ≤ (‖x‖ + ‖y‖) * (‖x‖ + ‖y‖), { simp only [←inner_self_eq_norm_mul_norm, inner_add_add_self, mul_add, mul_comm, map_add], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this, end, eq_zero_of_map_eq_zero' := λ x hx, (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).1 $ begin change sqrt (re ⟪x, x⟫) = 0 at hx, rw [sqrt_eq_zero inner_self_nonneg] at hx, exact ext (by simp [hx]) (by simp [inner_self_im_zero]), end } local attribute [instance] to_normed_add_comm_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_add_comm_group F := @inner_product_space.of_core.to_normed_add_comm_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ‖x‖^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] variables [dec_E : decidable_eq E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := has_abs.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := star_ring_end _ export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := @inner_conj_sym ℝ _ _ _ x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], simp only [inner_conj_sym] } lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. Note that in the case `𝕜 = ℝ` this is a bilinear form. -/ @[simps] def sesq_form_of_inner : E →ₗ[𝕜] E →ₗ⋆[𝕜] 𝕜 := linear_map.mk₂'ₛₗ (ring_hom.id 𝕜) (star_ring_end _) (λ x y, ⟪y, x⟫) (λ x y z, inner_add_right) (λ r x y, inner_smul_right) (λ x y z, inner_add_left) (λ r x y, inner_smul_left) /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := (sesq_form_of_inner x).map_sum /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := (linear_map.flip sesq_form_of_inner x).map_sum /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] } lemma dfinsupp.sum_inner {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪l.sum f, x⟫ = l.sum (λ i a, ⟪f i a, x⟫) := by simp [dfinsupp.sum, sum_inner] {contextual := tt} lemma dfinsupp.inner_sum {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪x, l.sum f⟫ = l.sum (λ i a, ⟪x, f i a⟫) := by simp [dfinsupp.sum, inner_sum] {contextual := tt} @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp only [h.1, zero_re'], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (‖x‖ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ‖x‖ ^ 2, { simpa [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact is_R_or_C.abs_of_nonneg inner_self_nonneg, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw [←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp only [inner_add_add_self, this, add_left_inj], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp only [inner_sub_sub_self, this, add_left_inj], ring, end variable (𝕜) include 𝕜 lemma ext_inner_left {x y : E} (h : ∀ v, ⟪v, x⟫ = ⟪v, y⟫) : x = y := by rw [←sub_eq_zero, ←inner_self_eq_zero, inner_sub_right, sub_eq_zero, h (x - y)] lemma ext_inner_right {x y : E} (h : ∀ v, ⟪x, v⟫ = ⟪y, v⟫) : x = y := by rw [←sub_eq_zero, ←inner_self_eq_zero, inner_sub_left, sub_eq_zero, h (x - y)] omit 𝕜 variable {𝕜} /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul, add_monoid_hom.map_add, conj_im, add_monoid_hom.map_sub, mul_neg, conj_re, neg_neg, mul_re] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, map_div₀, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw ←mul_div_right_comm ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ‖v i‖ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} include dec_ι /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ‖v i‖ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ‖v i‖ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end omit dec_ι include dec_E /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end omit dec_E /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by classical; simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪v i, ∑ i in s, (l i) • (v i)⟫ = l i := by classical; simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv, hi] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := hv.inner_right_sum l (finset.mem_univ _) /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪∑ i in s, (l i) • (v i), v i⟫ = conj (l i) := by classical; simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv, hi] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := hv.inner_left_sum l (finset.mem_univ _) /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the first `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_left {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₁.sum (λ i y, conj y * l₂ i) := by simp [finsupp.total_apply _ l₁, finsupp.sum_inner, hv.inner_right_finsupp] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the second `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_right {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₂.sum (λ i y, conj (l₁ i) * y) := by simp [finsupp.total_apply _ l₂, finsupp.inner_sum, hv.inner_left_finsupp, mul_comm] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum. -/ lemma orthonormal.inner_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι → 𝕜) (s : finset ι) : ⟪∑ i in s, l₁ i • v i, ∑ i in s, l₂ i • v i⟫ = ∑ i in s, conj (l₁ i) * l₂ i := begin simp_rw [sum_inner, inner_smul_left], refine finset.sum_congr rfl (λ i hi, _), rw hv.inner_right_sum l₂ hi end /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by classical; simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa [hv.inner_right_finsupp] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin classical, rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- An injective family `v : ι → E` is orthonormal if and only if `coe : (range v) → E` is orthonormal. -/ lemma orthonormal_subtype_range {v : ι → E} (hv : function.injective v) : orthonormal 𝕜 (coe : set.range v → E) ↔ orthonormal 𝕜 v := begin let f : ι ≃ set.range v := equiv.of_injective v hv, refine ⟨λ h, h.comp f f.injective, λ h, _⟩, rw ← equiv.self_comp_of_injective_symm hv, exact h.comp f.symm f.symm.injective, end /-- If `v : ι → E` is an orthonormal family, then `coe : (range v) → E` is an orthonormal family. -/ lemma orthonormal.to_subtype_range {v : ι → E} (hv : orthonormal 𝕜 v) : orthonormal 𝕜 (coe : set.range v → E) := (orthonormal_subtype_range hv.linear_independent.injective).2 hv /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp [hv.inner_left_finsupp, hl i hi], end /-- Given an orthonormal family, a second family of vectors is orthonormal if every vector equals the corresponding vector in the original family or its negation. -/ lemma orthonormal.orthonormal_of_forall_eq_or_eq_neg {v w : ι → E} (hv : orthonormal 𝕜 v) (hw : ∀ i, w i = v i ∨ w i = -(v i)) : orthonormal 𝕜 w := begin classical, rw orthonormal_iff_ite at *, intros i j, cases hw i with hi hi; cases hw j with hj hj; split_ifs with h; simpa [hi, hj, h] using hv i j end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by classical; simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin classical, rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin obtain ⟨b, bi, sb, h⟩ := zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ‖v i‖ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ‖x‖ = sqrt (re ⟪x, x⟫) := begin have h₁ : ‖x‖^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ‖x‖ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_mul_norm (x : E) : re ⟪x, x⟫ = ‖x‖ * ‖x‖ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ‖x‖^2 := by rw [pow_two, inner_self_eq_norm_mul_norm] lemma real_inner_self_eq_norm_mul_norm (x : F) : ⟪x, x⟫_ℝ = ‖x‖ * ‖x‖ := by { have h := @inner_self_eq_norm_mul_norm ℝ F _ _ x, simpa using h } lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ‖x‖^2 := by rw [pow_two, real_inner_self_eq_norm_mul_norm] /-- Expand the square -/ lemma norm_add_sq {x y : E} : ‖x + y‖^2 = ‖x‖^2 + 2 * (re ⟪x, y⟫) + ‖y‖^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real {x y : F} : ‖x + y‖^2 = ‖x‖^2 + 2 * ⟪x, y⟫_ℝ + ‖y‖^2 := by { have h := @norm_add_sq ℝ F _ _, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * (re ⟪x, y⟫) + ‖y‖ * ‖y‖ := by { repeat {rw [← sq]}, exact norm_add_sq } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_sq {x y : E} : ‖x - y‖^2 = ‖x‖^2 - 2 * (re ⟪x, y⟫) + ‖y‖^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real {x y : F} : ‖x - y‖^2 = ‖x‖^2 - 2 * ⟪x, y⟫_ℝ + ‖y‖^2 := norm_sub_sq alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * re ⟪x, y⟫ + ‖y‖ * ‖y‖ := by { repeat {rw [← sq]}, exact norm_sub_sq } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ - 2 * ⟪x, y⟫_ℝ + ‖y‖ * ‖y‖ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_mul_norm], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end lemma norm_inner_le_norm (x y : E) : ‖⟪x, y⟫‖ ≤ ‖x‖ * ‖y‖ := (is_R_or_C.norm_eq_abs _).le.trans (abs_inner_le_norm x y) lemma nnnorm_inner_le_nnnorm (x y : E) : ‖⟪x, y⟫‖₊ ≤ ‖x‖₊ * ‖y‖₊ := norm_inner_le_norm x y lemma re_inner_le_norm (x y : E) : re ⟪x, y⟫ ≤ ‖x‖ * ‖y‖ := le_trans (re_le_abs (inner x y)) (abs_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ‖x‖ * ‖y‖ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ‖x‖ * ‖y‖ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm (x y : E) : ‖x + y‖ * ‖x + y‖ + ‖x - y‖ * ‖x - y‖ = 2 * (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) := begin simp only [← inner_self_eq_norm_mul_norm], rw [← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end lemma parallelogram_law_with_nnnorm (x y : E) : ‖x + y‖₊ * ‖x + y‖₊ + ‖x - y‖₊ * ‖x - y‖₊ = 2 * (‖x‖₊ * ‖x‖₊ + ‖y‖₊ * ‖y‖₊) := subtype.ext $ parallelogram_law_with_norm x y omit 𝕜 /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (‖x + y‖ * ‖x + y‖ - ‖x - y‖ * ‖x - y‖) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (‖x - IK • y‖ * ‖x - IK • y‖ - ‖x + IK • y‖ * ‖x + IK • y‖) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (‖x + y‖ ^ 2 - ‖x - y‖ ^ 2 + (‖x - IK • y‖ ^ 2 - ‖x + IK • y‖ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end /-- Formula for the distance between the images of two nonzero points under an inversion with center zero. See also `euclidean_geometry.dist_inversion_inversion` for inversions around a general point. -/ lemma dist_div_norm_sq_smul {x y : F} (hx : x ≠ 0) (hy : y ≠ 0) (R : ℝ) : dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = (R ^ 2 / (‖x‖ * ‖y‖)) * dist x y := have hx' : ‖x‖ ≠ 0, from norm_ne_zero_iff.2 hx, have hy' : ‖y‖ ≠ 0, from norm_ne_zero_iff.2 hy, calc dist ((R / ‖x‖) ^ 2 • x) ((R / ‖y‖) ^ 2 • y) = sqrt (‖(R / ‖x‖) ^ 2 • x - (R / ‖y‖) ^ 2 • y‖^2) : by rw [dist_eq_norm, sqrt_sq (norm_nonneg _)] ... = sqrt ((R ^ 2 / (‖x‖ * ‖y‖)) ^ 2 * ‖x - y‖ ^ 2) : congr_arg sqrt $ by { field_simp [sq, norm_sub_mul_self_real, norm_smul, real_inner_smul_left, inner_smul_right, real.norm_of_nonneg (mul_self_nonneg _)], ring } ... = (R ^ 2 / (‖x‖ * ‖y‖)) * dist x y : by rw [sqrt_mul (sq_nonneg _), sqrt_sq (norm_nonneg _), sqrt_sq (div_nonneg (sq_nonneg _) (mul_nonneg (norm_nonneg _) (norm_nonneg _))), dist_eq_norm] @[priority 100] -- See note [lower instance priority] instance inner_product_space.to_uniform_convex_space : uniform_convex_space F := ⟨λ ε hε, begin refine ⟨2 - sqrt (4 - ε^2), sub_pos_of_lt $ (sqrt_lt' zero_lt_two).2 _, λ x hx y hy hxy, _⟩, { norm_num, exact pow_pos hε _ }, rw sub_sub_cancel, refine le_sqrt_of_sq_le _, rw [sq, eq_sub_iff_add_eq.2 (parallelogram_law_with_norm x y), ←sq (‖x - y‖), hx, hy], norm_num, exact pow_le_pow_of_le_left hε.le hxy _, end⟩ section complex variables {V : Type*} [inner_product_space ℂ V] /-- A complex polarization identity, with a linear map -/ lemma inner_map_polarization (T : V →ₗ[ℂ] V) (x y : V): ⟪ T y, x ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ + complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ - complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end lemma inner_map_polarization' (T : V →ₗ[ℂ] V) (x y : V): ⟪ T x, y ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ - complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ + complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end /-- A linear map `T` is zero, if and only if the identity `⟪T x, x⟫_ℂ = 0` holds for all `x`. -/ lemma inner_map_self_eq_zero (T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪T x, x⟫_ℂ = 0) ↔ T = 0 := begin split, { intro hT, ext x, simp only [linear_map.zero_apply, ← inner_self_eq_zero, inner_map_polarization, hT], norm_num }, { rintro rfl x, simp only [linear_map.zero_apply, inner_zero_left] } end /-- Two linear maps `S` and `T` are equal, if and only if the identity `⟪S x, x⟫_ℂ = ⟪T x, x⟫_ℂ` holds for all `x`. -/ lemma ext_inner_map (S T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪S x, x⟫_ℂ = ⟪T x, x⟫_ℂ) ↔ S = T := begin rw [←sub_eq_zero, ←inner_map_self_eq_zero], refine forall_congr (λ x, _), rw [linear_map.sub_apply, inner_sub_left, sub_eq_zero], end end complex section variables {ι : Type*} {ι' : Type*} {ι'' : Type*} variables {E' : Type*} [inner_product_space 𝕜 E'] variables {E'' : Type*} [inner_product_space 𝕜 E''] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl /-- A linear isometry preserves the property of being orthonormal. -/ lemma linear_isometry.orthonormal_comp_iff {v : ι → E} (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) ↔ orthonormal 𝕜 v := begin classical, simp_rw [orthonormal_iff_ite, linear_isometry.inner_map_map] end /-- A linear isometry preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry {v : ι → E} (hv : orthonormal 𝕜 v) (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := by rwa f.orthonormal_comp_iff /-- A linear isometric equivalence preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry_equiv {v : ι → E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := hv.comp_linear_isometry f.to_linear_isometry /-- A linear isometric equivalence, applied with `basis.map`, preserves the property of being orthonormal. -/ lemma orthonormal.map_linear_isometry_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (v.map f.to_linear_equiv) := hv.comp_linear_isometry_equiv f /-- A linear map that sends an orthonormal basis to orthonormal vectors is a linear isometry. -/ def linear_map.isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E →ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, by rw [←v.total_repr x, ←v.total_repr y, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] @[simp] lemma linear_map.coe_isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_map.isometry_of_orthonormal_to_linear_map (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_map = f := rfl /-- A linear equivalence that sends an orthonormal basis to orthonormal vectors is a linear isometric equivalence. -/ def linear_equiv.isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E ≃ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, begin rw ←linear_equiv.coe_coe at hf, rw [←v.total_repr x, ←v.total_repr y, ←linear_equiv.coe_coe, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] end @[simp] lemma linear_equiv.coe_isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_equiv.isometry_of_orthonormal_to_linear_equiv (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_equiv = f := rfl /-- A linear isometric equivalence that sends an orthonormal basis to a given orthonormal basis. -/ def orthonormal.equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : E ≃ₗᵢ[𝕜] E' := (v.equiv v' e).isometry_of_orthonormal hv begin have h : (v.equiv v' e) ∘ v = v' ∘ e, { ext i, simp }, rw h, exact hv'.comp _ e.injective end @[simp] lemma orthonormal.equiv_to_linear_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).to_linear_equiv = v.equiv v' e := rfl @[simp] lemma orthonormal.equiv_apply {ι' : Type*} {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') (i : ι) : hv.equiv hv' e (v i) = v' (e i) := basis.equiv_apply _ _ _ _ @[simp] lemma orthonormal.equiv_refl {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) : hv.equiv hv (equiv.refl ι) = linear_isometry_equiv.refl 𝕜 E := v.ext_linear_isometry_equiv $ λ i, by simp @[simp] lemma orthonormal.equiv_symm {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).symm = hv'.equiv hv e.symm := v'.ext_linear_isometry_equiv $ λ i, (hv.equiv hv' e).injective (by simp) @[simp] lemma orthonormal.equiv_trans {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') {v'' : basis ι'' 𝕜 E''} (hv'' : orthonormal 𝕜 v'') (e' : ι' ≃ ι'') : (hv.equiv hv' e).trans (hv'.equiv hv'' e') = hv.equiv hv'' (e.trans e') := v.ext_linear_isometry_equiv $ λ i, by simp lemma orthonormal.map_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : v.map ((hv.equiv hv' e).to_linear_equiv) = v'.reindex e.symm := v.map_equiv _ _ end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (‖x + y‖ * ‖x + y‖ - ‖x‖ * ‖x‖ - ‖y‖ * ‖y‖) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - ‖x - y‖ * ‖x - y‖) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, if-and-if vector inner product form using square roots. -/ lemma norm_add_eq_sqrt_iff_real_inner_eq_zero {x y : F} : ‖x + y‖ = sqrt (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by rw [←norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (norm_nonneg _)] /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, if-and-if vector inner product form using square roots. -/ lemma norm_sub_eq_sqrt_iff_real_inner_eq_zero {x y : F} : ‖x - y‖ = sqrt (‖x‖ * ‖x‖ + ‖y‖ * ‖y‖) ↔ ⟪x, y⟫_ℝ = 0 := by rw [←norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, eq_comm, sqrt_eq_iff_mul_self_eq (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (norm_nonneg _)] /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ‖x‖ = ‖y‖ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_mul_norm, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ‖w - v‖ = ‖w + v‖ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp [h, ←inner_self_eq_norm_mul_norm, inner_add_left, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (‖x‖ * ‖y‖), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (‖x‖ * ‖y‖) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (‖x‖ * ‖y‖))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (‖x‖ * ‖x‖) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (‖x‖ * ‖x‖) := by rw [inner_smul_right, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (‖x‖ * ‖r • x‖) = 1 := begin have hx' : ‖x‖ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div, mul_div_cancel _ hx', ←div_div, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ‖x‖, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (‖x‖ * ‖r • x‖) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ‖x‖, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (‖x‖ * ‖y‖)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (‖x‖ * ‖x‖) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_mul_norm, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ‖r • x‖ / ‖t + r • x‖ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ‖r • x‖ ^ 2 = ‖t + r • x‖ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [sq, sq, ←inner_self_eq_norm_mul_norm, ←inner_self_eq_norm_mul_norm ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (‖x‖ * ‖y‖)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ‖x‖ * ‖y‖ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ‖x‖ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ‖y‖ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ‖x‖ * ‖y‖ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ‖x‖ * ‖y‖ ↔ abs (⟪x, y⟫ / (‖x‖ * ‖y‖)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], simp [hx0] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (‖x‖ * ‖y‖) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ (‖y‖ : 𝕜) • x = (‖x‖ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (‖x‖ : 𝕜) * ‖y‖ ↔ ‖x‖ * ‖y‖ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ‖x‖ * ‖y‖ * (‖x‖ * ‖y‖ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ‖(‖y‖:𝕜) • x - (‖x‖:𝕜) • y‖ * ‖(‖y‖:𝕜) • x - (‖x‖:𝕜) • y‖ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (‖y‖ : 𝕜) • x = (‖x‖ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ‖x‖ * ‖y‖`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ‖x‖ * ‖y‖`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ‖x‖ * ‖y‖ ↔ ‖y‖ • x = ‖x‖ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ‖y‖ • x ≠ ‖x‖ • y := calc ⟪x, y⟫_ℝ < ‖x‖ * ‖y‖ ↔ ⟪x, y⟫_ℝ ≠ ‖x‖ * ‖y‖ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ‖y‖ • x ≠ ‖x‖ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ‖x‖ = 1) (hy : ‖y‖ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (‖v₁ i₁ - v₂ i₂‖ * ‖v₁ i₁ - v₂ i₂‖)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product as a sesquilinear map. -/ def innerₛₗ : E →ₗ⋆[𝕜] E →ₗ[𝕜] 𝕜 := linear_map.mk₂'ₛₗ _ _ (λ v w, ⟪v, w⟫) (λ _ _ _, inner_add_left) (λ _ _ _, inner_smul_left) (λ _ _ _, inner_add_right) (λ _ _ _, inner_smul_right) @[simp] lemma innerₛₗ_apply_coe (v : E) : (innerₛₗ v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerₛₗ_apply (v w : E) : innerₛₗ v w = ⟪v, w⟫ := rfl /-- The inner product as a continuous sesquilinear map. Note that `to_dual_map` (resp. `to_dual`) in `inner_product_space.dual` is a version of this given as a linear isometry (resp. linear isometric equivalence). -/ def innerSL : E →L⋆[𝕜] E →L[𝕜] 𝕜 := linear_map.mk_continuous₂ innerₛₗ 1 (λ x y, by simp only [norm_inner_le_norm, one_mul, innerₛₗ_apply]) @[simp] lemma innerSL_apply_coe (v : E) : (innerSL v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerSL_apply (v w : E) : innerSL v w = ⟪v, w⟫ := rfl /-- `innerSL` is an isometry. Note that the associated `linear_isometry` is defined in `inner_product_space.dual` as `to_dual_map`. -/ @[simp] lemma innerSL_apply_norm {x : E} : ‖(innerSL x : E →L[𝕜] 𝕜)‖ = ‖x‖ := begin refine le_antisymm ((innerSL x : E →L[𝕜] 𝕜).op_norm_le_bound (norm_nonneg _) (λ y, norm_inner_le_norm _ _)) _, cases eq_or_lt_of_le (norm_nonneg x) with h h, { have : x = 0 := norm_eq_zero.mp (eq.symm h), simp [this] }, { refine (mul_le_mul_right h).mp _, calc ‖x‖ * ‖x‖ = ‖x‖ ^ 2 : by ring ... = re ⟪x, x⟫ : norm_sq_eq_inner _ ... ≤ abs ⟪x, x⟫ : re_le_abs _ ... = ‖innerSL x x‖ : by { rw [←is_R_or_C.norm_eq_abs], refl } ... ≤ ‖innerSL x‖ * ‖x‖ : (innerSL x : E →L[𝕜] 𝕜).le_op_norm _ } end /-- The inner product as a continuous sesquilinear map, with the two arguments flipped. -/ def innerSL_flip : E →L[𝕜] E →L⋆[𝕜] 𝕜 := @continuous_linear_map.flipₗᵢ' 𝕜 𝕜 𝕜 E E 𝕜 _ _ _ _ _ _ _ _ _ (ring_hom.id 𝕜) (star_ring_end 𝕜) _ _ innerSL @[simp] lemma innerSL_flip_apply {x y : E} : innerSL_flip x y = ⟪y, x⟫ := rfl namespace continuous_linear_map variables {E' : Type*} [inner_product_space 𝕜 E'] /-- Given `f : E →L[𝕜] E'`, construct the continuous sesquilinear form `λ x y, ⟪x, A y⟫`, given as a continuous linear map. -/ def to_sesq_form : (E →L[𝕜] E') →L[𝕜] E' →L⋆[𝕜] E →L[𝕜] 𝕜 := ↑((continuous_linear_map.flipₗᵢ' E E' 𝕜 (star_ring_end 𝕜) (ring_hom.id 𝕜)).to_continuous_linear_equiv) ∘L (continuous_linear_map.compSL E E' (E' →L⋆[𝕜] 𝕜) (ring_hom.id 𝕜) (ring_hom.id 𝕜) innerSL_flip) @[simp] lemma to_sesq_form_apply_coe (f : E →L[𝕜] E') (x : E') : to_sesq_form f x = (innerSL x).comp f := rfl lemma to_sesq_form_apply_norm_le {f : E →L[𝕜] E'} {v : E'} : ‖to_sesq_form f v‖ ≤ ‖f‖ * ‖v‖ := begin refine op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, intro x, have h₁ : ‖f x‖ ≤ ‖f‖ * ‖x‖ := le_op_norm _ _, have h₂ := @norm_inner_le_norm 𝕜 E' _ _ v (f x), calc ‖⟪v, f x⟫‖ ≤ ‖v‖ * ‖f x‖ : h₂ ... ≤ ‖v‖ * (‖f‖ * ‖x‖) : mul_le_mul_of_nonneg_left h₁ (norm_nonneg v) ... = ‖f‖ * ‖v‖ * ‖x‖ : by ring, end end continuous_linear_map /-- When an inner product space `E` over `𝕜` is considered as a real normed space, its inner product satisfies `is_bounded_bilinear_map`. In order to state these results, we need a `normed_space ℝ E` instance. We will later establish such an instance by restriction-of-scalars, `inner_product_space.is_R_or_C_to_real 𝕜 E`, but this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]`. -/ lemma is_bounded_bilinear_map_inner [normed_space ℝ E] : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ‖⟪v i, x⟫‖ ^ 2 ≤ ‖x‖ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ‖z‖ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ‖x - ∑ i in s, ⟪v i, x⟫ • (v i)‖ ^ 2 = ‖x‖ ^ 2 - ∑ i in s, ‖⟪v i, x⟫‖ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [norm_sub_sq, sub_add], simp only [inner_product_space.norm_sq_eq_inner, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_sym, ←mul_assoc, h₂, ←h₃, inner_conj_sym, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ‖⟪v i, x⟫‖ ^ 2 ≤ ‖x‖ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ‖⟪v i, x⟫‖ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ‖⟪v i, x⟫‖ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ‖x‖ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { to_normed_add_comm_group := non_unital_normed_ring.to_normed_add_comm_group, inner := λ x y, conj x * y, norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { to_normed_add_comm_group := submodule.normed_add_comm_group _, inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl lemma orthonormal.cod_restrict {ι : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (s : submodule 𝕜 E) (hvs : ∀ i, v i ∈ s) : @orthonormal 𝕜 s _ _ ι (set.cod_restrict v s hvs) := s.subtypeₗᵢ.orthonormal_comp_iff.mp hv lemma orthonormal_span {ι : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) : @orthonormal 𝕜 (submodule.span 𝕜 (set.range v)) _ _ ι (λ i : ι, ⟨v i, submodule.subset_span (set.mem_range_self i)⟩) := hv.cod_restrict (submodule.span 𝕜 (set.range v)) (λ i, submodule.subset_span (set.mem_range_self i)) /-! ### Families of mutually-orthogonal subspaces of an inner product space -/ section orthogonal_family variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) open_locale direct_sum /-- An indexed family of mutually-orthogonal subspaces of an inner product space `E`. The simple way to express this concept would be as a condition on `V : ι → submodule 𝕜 E`. We We instead implement it as a condition on a family of inner product spaces each equipped with an isometric embedding into `E`, thus making it a property of morphisms rather than subobjects. This definition is less lightweight, but allows for better definitional properties when the inner product space structure on each of the submodules is important -- for example, when considering their Hilbert sum (`pi_lp V 2`). For example, given an orthonormal set of vectors `v : ι → E`, we have an associated orthogonal family of one-dimensional subspaces of `E`, which it is convenient to be able to discuss using `ι → 𝕜` rather than `Π i : ι, span 𝕜 (v i)`. -/ def orthogonal_family {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] (V : Π i, G i →ₗᵢ[𝕜] E) : Prop := ∀ ⦃i j⦄, i ≠ j → ∀ v : G i, ∀ w : G j, ⟪V i v, V j w⟫ = 0 variables {𝕜} {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] {V : Π i, G i →ₗᵢ[𝕜] E} (hV : orthogonal_family 𝕜 V) [dec_V : Π i (x : G i), decidable (x ≠ 0)] lemma orthonormal.orthogonal_family {v : ι → E} (hv : orthonormal 𝕜 v) : @orthogonal_family 𝕜 _ _ _ _ (λ i : ι, 𝕜) _ (λ i, linear_isometry.to_span_singleton 𝕜 E (hv.1 i)) := λ i j hij a b, by simp [inner_smul_left, inner_smul_right, hv.2 hij] include hV dec_ι lemma orthogonal_family.eq_ite {i j : ι} (v : G i) (w : G j) : ⟪V i v, V j w⟫ = ite (i = j) ⟪V i v, V j w⟫ 0 := begin split_ifs, { refl }, { exact hV h v w } end include dec_V lemma orthogonal_family.inner_right_dfinsupp (l : ⨁ i, G i) (i : ι) (v : G i) : ⟪V i v, l.sum (λ j, V j)⟫ = ⟪v, l i⟫ := calc ⟪V i v, l.sum (λ j, V j)⟫ = l.sum (λ j, λ w, ⟪V i v, V j w⟫) : dfinsupp.inner_sum (λ j, V j) l (V i v) ... = l.sum (λ j, λ w, ite (i=j) ⟪V i v, V j w⟫ 0) : congr_arg l.sum $ funext $ λ j, funext $ hV.eq_ite v ... = ⟪v, l i⟫ : begin simp only [dfinsupp.sum, submodule.coe_inner, finset.sum_ite_eq, ite_eq_left_iff, dfinsupp.mem_support_to_fun], split_ifs with h h, { simp }, { simp [of_not_not h] }, end omit dec_ι dec_V lemma orthogonal_family.inner_right_fintype [fintype ι] (l : Π i, G i) (i : ι) (v : G i) : ⟪V i v, ∑ j : ι, V j (l j)⟫ = ⟪v, l i⟫ := by classical; calc ⟪V i v, ∑ j : ι, V j (l j)⟫ = ∑ j : ι, ⟪V i v, V j (l j)⟫: by rw inner_sum ... = ∑ j, ite (i = j) ⟪V i v, V j (l j)⟫ 0 : congr_arg (finset.sum finset.univ) $ funext $ λ j, (hV.eq_ite v (l j)) ... = ⟪v, l i⟫ : by simp lemma orthogonal_family.inner_sum (l₁ l₂ : Π i, G i) (s : finset ι) : ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ i in s, ⟪l₁ i, l₂ i⟫ := by classical; calc ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ j in s, ∑ i in s, ⟪V i (l₁ i), V j (l₂ j)⟫ : by simp [sum_inner, inner_sum] ... = ∑ j in s, ∑ i in s, ite (i = j) ⟪V i (l₁ i), V j (l₂ j)⟫ 0 : begin congr' with i, congr' with j, apply hV.eq_ite, end ... = ∑ i in s, ⟪l₁ i, l₂ i⟫ : by simp [finset.sum_ite_of_true] lemma orthogonal_family.norm_sum (l : Π i, G i) (s : finset ι) : ‖∑ i in s, V i (l i)‖ ^ 2 = ∑ i in s, ‖l i‖ ^ 2 := begin have : (‖∑ i in s, V i (l i)‖ ^ 2 : 𝕜) = ∑ i in s, ‖l i‖ ^ 2, { simp [← inner_self_eq_norm_sq_to_K, hV.inner_sum] }, exact_mod_cast this, end /-- The composition of an orthogonal family of subspaces with an injective function is also an orthogonal family. -/ lemma orthogonal_family.comp {γ : Type*} {f : γ → ι} (hf : function.injective f) : orthogonal_family 𝕜 (λ g : γ, (V (f g) : G (f g) →ₗᵢ[𝕜] E)) := λ i j hij v w, hV (hf.ne hij) v w lemma orthogonal_family.orthonormal_sigma_orthonormal {α : ι → Type*} {v_family : Π i, (α i) → G i} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (λ a : Σ i, α i, V a.1 (v_family a.1 a.2)) := begin split, { rintros ⟨i, v⟩, simpa using (hv_family i).1 v }, rintros ⟨i, v⟩ ⟨j, w⟩ hvw, by_cases hij : i = j, { subst hij, have : v ≠ w := by simpa using hvw, simpa using (hv_family i).2 this }, { exact hV hij (v_family i v) (v_family j w) } end include dec_ι lemma orthogonal_family.norm_sq_diff_sum (f : Π i, G i) (s₁ s₂ : finset ι) : ‖∑ i in s₁, V i (f i) - ∑ i in s₂, V i (f i)‖ ^ 2 = ∑ i in s₁ \ s₂, ‖f i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖f i‖ ^ 2 := begin rw [← finset.sum_sdiff_sub_sum_sdiff, sub_eq_add_neg, ← finset.sum_neg_distrib], let F : Π i, G i := λ i, if i ∈ s₁ then f i else - (f i), have hF₁ : ∀ i ∈ s₁ \ s₂, F i = f i := λ i hi, if_pos (finset.sdiff_subset _ _ hi), have hF₂ : ∀ i ∈ s₂ \ s₁, F i = - f i := λ i hi, if_neg (finset.mem_sdiff.mp hi).2, have hF : ∀ i, ‖F i‖ = ‖f i‖, { intros i, dsimp [F], split_ifs; simp, }, have : ‖∑ i in s₁ \ s₂, V i (F i) + ∑ i in s₂ \ s₁, V i (F i)‖ ^ 2 = ∑ i in s₁ \ s₂, ‖F i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖F i‖ ^ 2, { have hs : disjoint (s₁ \ s₂) (s₂ \ s₁) := disjoint_sdiff_sdiff, simpa only [finset.sum_union hs] using hV.norm_sum F (s₁ \ s₂ ∪ s₂ \ s₁) }, convert this using 4, { refine finset.sum_congr rfl (λ i hi, _), simp [hF₁ i hi] }, { refine finset.sum_congr rfl (λ i hi, _), simp [hF₂ i hi] }, { simp [hF] }, { simp [hF] }, end omit dec_ι /-- A family `f` of mutually-orthogonal elements of `E` is summable, if and only if `(λ i, ‖f i‖ ^ 2)` is summable. -/ lemma orthogonal_family.summable_iff_norm_sq_summable [complete_space E] (f : Π i, G i) : summable (λ i, V i (f i)) ↔ summable (λ i, ‖f i‖ ^ 2) := begin classical, simp only [summable_iff_cauchy_seq_finset, normed_add_comm_group.cauchy_seq_iff, real.norm_eq_abs], split, { intros hf ε hε, obtain ⟨a, H⟩ := hf _ (sqrt_pos.mpr hε), use a, intros s₁ hs₁ s₂ hs₂, rw ← finset.sum_sdiff_sub_sum_sdiff, refine (_root_.abs_sub _ _).trans_lt _, have : ∀ i, 0 ≤ ‖f i‖ ^ 2 := λ i : ι, sq_nonneg _, simp only [finset.abs_sum_of_nonneg' this], have : ∑ i in s₁ \ s₂, ‖f i‖ ^ 2 + ∑ i in s₂ \ s₁, ‖f i‖ ^ 2 < (sqrt ε) ^ 2, { rw [← hV.norm_sq_diff_sum, sq_lt_sq, _root_.abs_of_nonneg (sqrt_nonneg _), _root_.abs_of_nonneg (norm_nonneg _)], exact H s₁ hs₁ s₂ hs₂ }, have hη := sq_sqrt (le_of_lt hε), linarith }, { intros hf ε hε, have hε' : 0 < ε ^ 2 / 2 := half_pos (sq_pos_of_pos hε), obtain ⟨a, H⟩ := hf _ hε', use a, intros s₁ hs₁ s₂ hs₂, refine (abs_lt_of_sq_lt_sq' _ (le_of_lt hε)).2, have has : a ≤ s₁ ⊓ s₂ := le_inf hs₁ hs₂, rw hV.norm_sq_diff_sum, have Hs₁ : ∑ (x : ι) in s₁ \ s₂, ‖f x‖ ^ 2 < ε ^ 2 / 2, { convert H _ hs₁ _ has, have : s₁ ⊓ s₂ ⊆ s₁ := finset.inter_subset_left _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, have Hs₂ : ∑ (x : ι) in s₂ \ s₁, ‖f x‖ ^ 2 < ε ^ 2 /2, { convert H _ hs₂ _ has, have : s₁ ⊓ s₂ ⊆ s₂ := finset.inter_subset_right _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, linarith }, end omit hV /-- An orthogonal family forms an independent family of subspaces; that is, any collection of elements each from a different subspace in the family is linearly independent. In particular, the pairwise intersections of elements of the family are 0. -/ lemma orthogonal_family.independent {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : complete_lattice.independent V := begin classical, apply complete_lattice.independent_of_dfinsupp_lsum_injective, rw [← @linear_map.ker_eq_bot _ _ _ _ _ _ (direct_sum.add_comm_group (λ i, V i)), submodule.eq_bot_iff], intros v hv, rw linear_map.mem_ker at hv, ext i, suffices : ⟪(v i : E), v i⟫ = 0, { simpa using this }, calc ⟪(v i : E), v i⟫ = ⟪(v i : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) v⟫ : by simpa [dfinsupp.sum_add_hom_apply, submodule.coe_subtype] using (hV.inner_right_dfinsupp v i (v i)).symm ... = 0 : by simp [hv], end include dec_ι lemma direct_sum.is_internal.collected_basis_orthonormal {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) (hV_sum : direct_sum.is_internal (λ i, V i)) {α : ι → Type*} {v_family : Π i, basis (α i) 𝕜 (V i)} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (hV_sum.collected_basis v_family) := by simpa using hV.orthonormal_sigma_orthonormal hv_family end orthogonal_family section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { to_normed_add_comm_group := inner_product_space.to_normed_add_comm_group 𝕜, norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G @[simp] protected lemma complex.inner (w z : ℂ) : ⟪w, z⟫_ℝ = (conj w * z).re := rfl /-- The inner product on an inner product space of dimension 2 can be evaluated in terms of a complex-number representation of the space. -/ lemma inner_map_complex [inner_product_space ℝ G] (f : G ≃ₗᵢ[ℝ] ℂ) (x y : G) : ⟪x, y⟫_ℝ = (conj (f x) * f y).re := by rw [← complex.inner, f.inner_map_map] end is_R_or_C_to_real section continuous /-! ### Continuity of the inner product -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, exact is_bounded_bilinear_map_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) @[continuity] lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section re_apply_inner_self /-- Extract a real bilinear form from an operator `T`, by taking the pairing `λ x, re ⟪T x, x⟫`. -/ def continuous_linear_map.re_apply_inner_self (T : E →L[𝕜] E) (x : E) : ℝ := re ⟪T x, x⟫ lemma continuous_linear_map.re_apply_inner_self_apply (T : E →L[𝕜] E) (x : E) : T.re_apply_inner_self x = re ⟪T x, x⟫ := rfl lemma continuous_linear_map.re_apply_inner_self_continuous (T : E →L[𝕜] E) : continuous T.re_apply_inner_self := re_clm.continuous.comp $ T.continuous.inner continuous_id lemma continuous_linear_map.re_apply_inner_self_smul (T : E →L[𝕜] E) (x : E) {c : 𝕜} : T.re_apply_inner_self (c • x) = ‖c‖ ^ 2 * T.re_apply_inner_self x := by simp only [continuous_linear_map.map_smul, continuous_linear_map.re_apply_inner_self_apply, inner_smul_left, inner_smul_right, ← mul_assoc, mul_conj, norm_sq_eq_def', ← smul_re, algebra.smul_def (‖c‖ ^ 2) ⟪T x, x⟫, algebra_map_eq_of_real] end re_apply_inner_self /-! ### The orthogonal complement -/ section orthogonal variables (K : submodule 𝕜 E) /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector orthogonal to `u` lies in `(𝕜 ∙ u)ᗮ`. -/ lemma mem_orthogonal_singleton_of_inner_right (u : E) {v : E} (hv : ⟪u, v⟫ = 0) : v ∈ (𝕜 ∙ u)ᗮ := begin intros w hw, rw submodule.mem_span_singleton at hw, obtain ⟨c, rfl⟩ := hw, simp [inner_smul_left, hv], end /-- A vector orthogonal to `u` lies in `(𝕜 ∙ u)ᗮ`. -/ lemma mem_orthogonal_singleton_of_inner_left (u : E) {v : E} (hv : ⟪v, u⟫ = 0) : v ∈ (𝕜 ∙ u)ᗮ := mem_orthogonal_singleton_of_inner_right u $ inner_eq_zero_sym.2 hv lemma submodule.sub_mem_orthogonal_of_inner_left {x y : E} (h : ∀ (v : K), ⟪x, v⟫ = ⟪y, v⟫) : x - y ∈ Kᗮ := begin rw submodule.mem_orthogonal', intros u hu, rw [inner_sub_left, sub_eq_zero], exact h ⟨u, hu⟩, end lemma submodule.sub_mem_orthogonal_of_inner_right {x y : E} (h : ∀ (v : K), ⟪(v : E), x⟫ = ⟪(v : E), y⟫) : x - y ∈ Kᗮ := begin intros u hu, rw [inner_sub_right, sub_eq_zero], exact h ⟨u, hu⟩, end variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, linear_map.ker (innerSL (v:E) : E →L[𝕜] 𝕜) := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, have := λ v : K, continuous_linear_map.is_closed_ker (innerSL (v:E) : E →L[𝕜] 𝕜), convert is_closed_Inter this, simp only [submodule.infi_coe], end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (submodule 𝕜 E)ᵒᵈ _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end lemma submodule.orthogonal_family_self : @orthogonal_family 𝕜 E _ _ _ (λ b, ((cond b K Kᗮ : submodule 𝕜 E) : Type*)) _ (λ b, (cond b K Kᗮ).subtypeₗᵢ) | tt tt := absurd rfl | tt ff := λ _ x y, submodule.inner_right_of_mem_orthogonal x.prop y.prop | ff tt := λ _ x y, submodule.inner_left_of_mem_orthogonal y.prop x.prop | ff ff := absurd rfl end orthogonal namespace uniform_space.completion open uniform_space function instance {𝕜' E' : Type*} [topological_space 𝕜'] [uniform_space E'] [has_inner 𝕜' E'] : has_inner 𝕜' (completion E') := { inner := curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (uncurry inner) } @[simp] lemma inner_coe (a b : E) : inner (a : completion E) (b : completion E) = (inner a b : 𝕜) := (dense_inducing_coe.prod dense_inducing_coe).extend_eq (continuous_inner : continuous (uncurry inner : E × E → 𝕜)) (a, b) protected lemma continuous_inner : continuous (uncurry inner : completion E × completion E → 𝕜) := begin let inner' : E →+ E →+ 𝕜 := { to_fun := λ x, (innerₛₗ x).to_add_monoid_hom, map_zero' := by ext x; exact inner_zero_left, map_add' := λ x y, by ext z; exact inner_add_left }, have : continuous (λ p : E × E, inner' p.1 p.2) := continuous_inner, rw [completion.has_inner, uncurry_curry _], change continuous (((dense_inducing_to_compl E).prod (dense_inducing_to_compl E)).extend (λ p : E × E, inner' p.1 p.2)), exact (dense_inducing_to_compl E).extend_Z_bilin (dense_inducing_to_compl E) this, end protected lemma continuous.inner {α : Type*} [topological_space α] {f g : α → completion E} (hf : continuous f) (hg : continuous g) : continuous (λ x : α, inner (f x) (g x) : α → 𝕜) := uniform_space.completion.continuous_inner.comp (hf.prod_mk hg : _) instance : inner_product_space 𝕜 (completion E) := { to_normed_add_comm_group := infer_instance, norm_sq_eq_inner := λ x, completion.induction_on x (is_closed_eq (continuous_norm.pow 2) (continuous_re.comp (continuous.inner continuous_id' continuous_id'))) (λ a, by simp only [norm_coe, inner_coe, inner_self_eq_norm_sq]), conj_sym := λ x y, completion.induction_on₂ x y (is_closed_eq (continuous_conj.comp (continuous.inner continuous_snd continuous_fst)) (continuous.inner continuous_fst continuous_snd)) (λ a b, by simp only [inner_coe, inner_conj_sym]), add_left := λ x y z, completion.induction_on₃ x y z (is_closed_eq (continuous.inner (continuous_fst.add (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) ((continuous.inner continuous_fst (continuous_snd.comp continuous_snd)).add (continuous.inner (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (λ a b c, by simp only [← coe_add, inner_coe, inner_add_left]), smul_left := λ x y c, completion.induction_on₂ x y (is_closed_eq (continuous.inner (continuous_fst.const_smul c) continuous_snd) ((continuous_mul_left _).comp (continuous.inner continuous_fst continuous_snd))) (λ a b, by simp only [← coe_smul c a, inner_coe, inner_smul_left]) } end uniform_space.completion
556398eb7ccc313ff82a3d408d0ecb515455d49b
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/indimp.lean
3e124076cd4a8966fb6748b467246ec2babe1e2a
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
492
lean
definition Prop := Type.{0} inductive nat := zero : nat, succ : nat → nat inductive list (A : Type) := nil {} : list A, cons : A → list A → list A inductive list2 (A : Type) : Type := nil2 {} : list2 A, cons2 : A → list2 A → list2 A inductive and (A B : Prop) : Prop := and_intro : A → B → and A B inductive cls {T1 : Type} (R1 : T1 → T1 → Prop) {T2 : Type} (R2 : T2 → T2 → Prop) (f : T1 → T2) := mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → cls R1 R2 f
24a61ca21cf293240165972a58c1e053884685f3
495c02489c2d6a1db94dfdba71dd800d3cc67df2
/group_theory/finsubg.lean
3cd189e8e92fe32dab9c54c615f58011fff41e50
[ "Apache-2.0" ]
permissive
leodemoura/leanproved
e0fcbe4f4d72bf0dad9a962ed111b5975cf90712
de56e0af159dd0c0421733289c76aa79c78a0191
refs/heads/master
1,606,822,676,898
1,435,711,541,000
1,435,711,541,000
36,675,856
0
0
null
1,433,178,724,000
1,433,178,724,000
null
UTF-8
Lean
false
false
4,553
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ -- develop the concept of finite subgroups based on finsets so that the properties -- can be used directly without translating from the set based theory first import data algebra.group .subgroup open function algebra set finset -- ⁻¹ in eq.ops conflicts with group ⁻¹ open eq.ops namespace group open ops section subg -- we should be able to prove properties using finsets directly variable {G : Type} variable [ambientG : group G] include ambientG definition finset_mul_closed_on [reducible] (H : finset G) : Prop := ∀ (x y : G), x ∈ H → y ∈ H → x * y ∈ H definition finset_has_inv (H : finset G) : Prop := ∀ (a : G), a ∈ H → a⁻¹ ∈ H structure is_finsubg [class] (H : finset G) : Type := (has_one : 1 ∈ H) (mul_closed : finset_mul_closed_on H) (has_inv : finset_has_inv H) definition univ_is_finsubg [instance] [finG : fintype G] : is_finsubg (@finset.univ G _) := is_finsubg.mk !mem_univ (λ x y Px Py, !mem_univ) (λ a Pa, !mem_univ) lemma finsubg_has_one (H : finset G) [h : is_finsubg H] : 1 ∈ H := @is_finsubg.has_one G _ H h lemma finsubg_mul_closed (H : finset G) [h : is_finsubg H] : finset_mul_closed_on H := @is_finsubg.mul_closed G _ H h lemma finsubg_has_inv (H : finset G) [h : is_finsubg H] : finset_has_inv H := @is_finsubg.has_inv G _ H h variable [deceqG : decidable_eq G] include deceqG definition finsubg_to_subg [instance] {H : finset G} [h : is_finsubg H] : is_subgroup (ts H) := is_subgroup.mk (mem_eq_mem_to_set H 1 ▸ finsubg_has_one H) (take x y, begin repeat rewrite -mem_eq_mem_to_set, apply finsubg_mul_closed H end) (take a, begin repeat rewrite -mem_eq_mem_to_set, apply finsubg_has_inv H end) end subg section lagrange -- this is work based on is_subgroup. will test is_finsubg somewhere else first. variable {A : Type} variable [deceq : decidable_eq A] include deceq variable [s : group A] include s definition fin_lcoset (H : finset A) (a : A) := finset.image (lmul_by a) H definition fin_lcosets (H G : finset A) := image (fin_lcoset H) G variable {H : finset A} lemma fin_lcoset_eq (a : A) : ts (fin_lcoset H a) = a ∘> (ts H) := calc ts (fin_lcoset H a) = coset.l a (ts H) : to_set_image ... = a ∘> (ts H) : glcoset_eq_lcoset lemma fin_lcoset_card (a : A) : card (fin_lcoset H a) = card H := card_image_eq_of_inj_on (lmul_inj_on a (ts H)) lemma fin_lcosets_card_eq {G : finset A} : ∀ gH, gH ∈ fin_lcosets H G → card gH = card H := take gH, assume Pcosets, obtain g Pg, from exists_of_mem_image Pcosets, and.right Pg ▸ fin_lcoset_card g variable [is_subgH : is_subgroup (to_set H)] include is_subgH lemma fin_lcoset_same (x a : A) : x ∈ (fin_lcoset H a) = (fin_lcoset H x = fin_lcoset H a) := begin rewrite mem_eq_mem_to_set, rewrite [eq_eq_to_set_eq, *(fin_lcoset_eq x), fin_lcoset_eq a], exact (subg_lcoset_same x a) end lemma fin_mem_lcoset (g : A) : g ∈ fin_lcoset H g := have P : g ∈ g ∘> ts H, from and.left (subg_in_coset_refl g), assert P1 : g ∈ ts (fin_lcoset H g), from eq.symm (fin_lcoset_eq g) ▸ P, eq.symm (mem_eq_mem_to_set _ g) ▸ P1 lemma fin_lcoset_subset {S : finset A} (Psub : S ⊆ H) : ∀ x, x ∈ H → fin_lcoset S x ⊆ H := assert Psubs : set.subset (ts S) (ts H), from subset_eq_to_set_subset S H ▸ Psub, take x, assume Pxs : x ∈ ts H, assert Pcoset : set.subset (x ∘> ts S) (ts H), from subg_lcoset_subset_subg Psubs x Pxs, by rewrite [subset_eq_to_set_subset, fin_lcoset_eq x]; exact Pcoset variable {G : finset A} variable [is_subgG : is_subgroup (to_set G)] include is_subgG open finset.partition definition fin_lcoset_partition_subg (Psub : H ⊆ G) := partition.mk G (fin_lcoset H) fin_lcoset_same (restriction_imp_union (fin_lcoset H) fin_lcoset_same (fin_lcoset_subset Psub)) open nat theorem lagrange_theorem (Psub : H ⊆ G) : card G = card (fin_lcosets H G) * card H := calc card G = nat.Sum (fin_lcosets H G) card : class_equation (fin_lcoset_partition_subg Psub) ... = nat.Sum (fin_lcosets H G) (λ x, card H) : nat.Sum_ext (take g P, fin_lcosets_card_eq g P) ... = card (fin_lcosets H G) * card H : Sum_const_eq_card_mul end lagrange end group
3452499127d603a0234d7ec60f13ce8b44323ca0
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/concatElim.lean
73b93c171fa2d0e2be68f140d8977dad1c45a298
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,700
lean
universes u def concat {α} : List α → α → List α | [], a => [a] | x::xs, a => x :: concat xs a def last {α} : (xs : List α) → xs ≠ [] → α | [], h => absurd rfl h | [a], h => a | _::a::as, h => last (a::as) (fun h => by injection h) def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as variable {α} theorem concatEq (xs : List α) (h : xs ≠ []) : concat (dropLast xs) (last xs h) = xs := by match xs, h with | [], h => exact absurd rfl h | [x], h => rfl | x₁::x₂::xs, h => simp [concat, last, concatEq (x₂::xs) List.noConfusion] theorem lengthCons {α} (x : α) (xs : List α) : (x::xs).length = xs.length + 1 := let rec aux (a : α) (xs : List α) : (n : Nat) → (a::xs).lengthAux n = xs.lengthAux n + 1 := match xs with | [] => fun _ => rfl | x::xs => fun n => aux a xs (n+1) aux x xs 0 theorem eqNilOfLengthZero {α} : (xs : List α) → xs.length = 0 → xs = [] | [], h => rfl | x::xs, h => by rw [lengthCons] at h; injection h theorem dropLastLen {α} (xs : List α) : (n : Nat) → xs.length = n+1 → (dropLast xs).length = n := by match xs with | [] => intro _ h; injection h | [a] => intro n h have 1 = n + 1 from h have 0 = n by injection this; assumption subst this rfl | x₁::x₂::xs => intro n h cases n with | zero => simp [lengthCons] at h injection h with h injection h | succ n => have (x₁ :: x₂ :: xs).length = xs.length + 2 by simp [lengthCons] have xs.length = n by rw [this] at h; injection h with h; injection h with h; assumption simp [dropLast, lengthCons, dropLastLen (x₂::xs) xs.length (lengthCons ..), this] @[inline] def concatElim {α} (motive : List α → Sort u) (base : Unit → motive []) (ind : (xs : List α) → (a : α) → motive xs → motive (concat xs a)) (xs : List α) : motive xs := let rec @[specialize] aux : (n : Nat) → (xs : List α) → xs.length = n → motive xs | 0, xs, h => by have aux := eqNilOfLengthZero _ h subst aux apply base () | n+1, xs, h => by have notNil : xs ≠ [] by intro h1; subst h1; injection h let ih := aux n (dropLast xs) (dropLastLen _ _ h) let aux := ind (dropLast xs) (last xs notNil) ih rw [concatEq] at aux exact aux aux xs.length xs rfl -- The generated code is tail recursive def test (xs : List Nat) : IO Unit := concatElim (motive := fun _ => IO Unit) (fun _ => pure ()) (fun xs x r => do IO.println s!"step xs: {xs} x: {x}"; r) xs #eval test [1, 2, 3, 4]
8e6c87a2f3be5aa3792981cdabf2def5c3867b44
626e312b5c1cb2d88fca108f5933076012633192
/src/field_theory/galois.lean
1ad1668274b6dbbef62050888934583958f772c9
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,088
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.normal import field_theory.primitive_element import field_theory.fixed import ring_theory.power_basis /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `is_galois F E` where `E` is an extension of `F` - `fixed_field H` where `H : subgroup (E ≃ₐ[F] E)` - `fixing_subgroup K` where `K : intermediate_field F E` - `galois_correspondence` where `E/F` is finite dimensional and Galois ## Main results - `fixing_subgroup_of_fixed_field` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixing_subgroup (fixed_field H) = H` - `fixed_field_of_fixing_subgroup`: If `E/F` is finite dimensional and Galois then `fixed_field (fixing_subgroup K) = K` Together, these two result prove the Galois correspondence - `is_galois.tfae` : Equivalent characterizations of a Galois extension of finite degree -/ noncomputable theory open_locale classical open finite_dimensional alg_equiv section variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-- A field extension E/F is galois if it is both separable and normal -/ class is_galois : Prop := [to_is_separable : is_separable F E] [to_normal : normal F E] variables {F E} theorem is_galois_iff : is_galois F E ↔ is_separable F E ∧ normal F E := ⟨λ h, ⟨h.1, h.2⟩, λ h, { to_is_separable := h.1, to_normal := h.2 }⟩ attribute [instance, priority 100] -- see Note [lower instance priority] is_galois.to_is_separable is_galois.to_normal variables (F E) namespace is_galois instance self : is_galois F F := ⟨⟩ variables (F) {E} lemma integral [is_galois F E] (x : E) : is_integral F x := normal.is_integral' x lemma separable [is_galois F E] (x : E) : (minpoly F x).separable := is_separable.separable F x lemma splits [is_galois F E] (x : E) : (minpoly F x).splits (algebra_map F E) := normal.splits' x variables (F E) instance of_fixed_field (G : Type*) [group G] [fintype G] [mul_semiring_action G E] : is_galois (fixed_points.subfield G E) E := ⟨⟩ lemma intermediate_field.adjoin_simple.card_aut_eq_finrank [finite_dimensional F E] {α : E} (hα : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F F⟮α⟯)) : fintype.card (F⟮α⟯ ≃ₐ[F] F⟮α⟯) = finrank F F⟮α⟯ := begin letI : fintype (F⟮α⟯ →ₐ[F] F⟮α⟯) := intermediate_field.fintype_of_alg_hom_adjoin_integral F hα, rw intermediate_field.adjoin.finrank hα, rw ← intermediate_field.card_alg_hom_adjoin_integral F hα h_sep h_splits, exact fintype.card_congr (alg_equiv_equiv_alg_hom F F⟮α⟯) end lemma card_aut_eq_finrank [finite_dimensional F E] [is_galois F E] : fintype.card (E ≃ₐ[F] E) = finrank F E := begin cases field.exists_primitive_element F E with α hα, let iso : F⟮α⟯ ≃ₐ[F] E := { to_fun := λ e, e.val, inv_fun := λ e, ⟨e, by { rw hα, exact intermediate_field.mem_top }⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, rfl, map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, commutes' := λ _, rfl }, have H : is_integral F α := is_galois.integral F α, have h_sep : (minpoly F α).separable := is_galois.separable F α, have h_splits : (minpoly F α).splits (algebra_map F E) := is_galois.splits F α, replace h_splits : polynomial.splits (algebra_map F F⟮α⟯) (minpoly F α), { convert polynomial.splits_comp_of_splits (algebra_map F E) iso.symm.to_alg_hom.to_ring_hom h_splits }, rw ← linear_equiv.finrank_eq iso.to_linear_equiv, rw ← intermediate_field.adjoin_simple.card_aut_eq_finrank F E H h_sep h_splits, apply fintype.card_congr, apply equiv.mk (λ ϕ, iso.trans (trans ϕ iso.symm)) (λ ϕ, iso.symm.trans (trans ϕ iso)), { intro ϕ, ext1, simp only [trans_apply, apply_symm_apply] }, { intro ϕ, ext1, simp only [trans_apply, symm_apply_apply] }, end end is_galois end section is_galois_tower variables (F K E : Type*) [field F] [field K] [field E] {E' : Type*} [field E'] [algebra F E'] variables [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_galois.tower_top_of_is_galois [is_galois F E] : is_galois K E := { to_is_separable := is_separable_tower_top_of_is_separable F K E, to_normal := normal.tower_top_of_normal F K E } variables {F E} @[priority 100] -- see Note [lower instance priority] instance is_galois.tower_top_intermediate_field (K : intermediate_field F E) [h : is_galois F E] : is_galois K E := is_galois.tower_top_of_is_galois F K E lemma is_galois_iff_is_galois_bot : is_galois (⊥ : intermediate_field F E) E ↔ is_galois F E := begin split, { introI h, exact is_galois.tower_top_of_is_galois (⊥ : intermediate_field F E) F E }, { introI h, apply_instance }, end lemma is_galois.of_alg_equiv [h : is_galois F E] (f : E ≃ₐ[F] E') : is_galois F E' := { to_is_separable := is_separable.of_alg_hom F E f.symm, to_normal := normal.of_alg_equiv f } lemma alg_equiv.transfer_galois (f : E ≃ₐ[F] E') : is_galois F E ↔ is_galois F E' := ⟨λ h, by exactI is_galois.of_alg_equiv f, λ h, by exactI is_galois.of_alg_equiv f.symm⟩ lemma is_galois_iff_is_galois_top : is_galois F (⊤ : intermediate_field F E) ↔ is_galois F E := (intermediate_field.top_equiv).transfer_galois instance is_galois_bot : is_galois F (⊥ : intermediate_field F E) := (intermediate_field.bot_equiv F E).transfer_galois.mpr (is_galois.self F) end is_galois_tower section galois_correspondence variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] variables (H : subgroup (E ≃ₐ[F] E)) (K : intermediate_field F E) namespace intermediate_field /-- The intermediate_field fixed by a subgroup -/ def fixed_field : intermediate_field F E := { carrier := mul_action.fixed_points H E, zero_mem' := λ g, smul_zero g, add_mem' := λ a b hx hy g, by rw [smul_add g a b, hx, hy], neg_mem' := λ a hx g, by rw [smul_neg g a, hx], one_mem' := λ g, smul_one g, mul_mem' := λ a b hx hy g, by rw [smul_mul' g a b, hx, hy], inv_mem' := λ a hx g, by rw [smul_inv' _ g a, hx], algebra_map_mem' := λ a g, commutes g a } lemma finrank_fixed_field_eq_card [finite_dimensional F E] : finrank (fixed_field H) E = fintype.card H := fixed_points.finrank_eq_card H E /-- The subgroup fixing an intermediate_field -/ def fixing_subgroup : subgroup (E ≃ₐ[F] E) := { carrier := λ ϕ, ∀ x : K, ϕ x = x, one_mem' := λ _, rfl, mul_mem' := λ _ _ hx hy _, (congr_arg _ (hy _)).trans (hx _), inv_mem' := λ _ hx _, (equiv.symm_apply_eq (to_equiv _)).mpr (hx _).symm } lemma le_iff_le : K ≤ fixed_field H ↔ H ≤ fixing_subgroup K := ⟨λ h g hg x, h (subtype.mem x) ⟨g, hg⟩, λ h x hx g, h (subtype.mem g) ⟨x, hx⟩⟩ /-- The fixing_subgroup of `K : intermediate_field F E` is isomorphic to `E ≃ₐ[K] E` -/ def fixing_subgroup_equiv : fixing_subgroup K ≃* (E ≃ₐ[K] E) := { to_fun := λ ϕ, of_bijective (alg_hom.mk ϕ (map_one ϕ) (map_mul ϕ) (map_zero ϕ) (map_add ϕ) (ϕ.mem)) (bijective ϕ), inv_fun := λ ϕ, ⟨of_bijective (alg_hom.mk ϕ (ϕ.map_one) (ϕ.map_mul) (ϕ.map_zero) (ϕ.map_add) (λ r, ϕ.commutes (algebra_map F K r))) (ϕ.bijective), ϕ.commutes⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl }, map_mul' := λ _ _, by { ext, refl } } theorem fixing_subgroup_fixed_field [finite_dimensional F E] : fixing_subgroup (fixed_field H) = H := begin have H_le : H ≤ (fixing_subgroup (fixed_field H)) := (le_iff_le _ _).mp (le_refl _), suffices : fintype.card H = fintype.card (fixing_subgroup (fixed_field H)), { exact set_like.coe_injective (set.eq_of_inclusion_surjective ((fintype.bijective_iff_injective_and_card (set.inclusion H_le)).mpr ⟨set.inclusion_injective H_le, this⟩).2).symm }, apply fintype.card_congr, refine (fixed_points.to_alg_hom_equiv H E).trans _, refine (alg_equiv_equiv_alg_hom (fixed_field H) E).symm.trans _, exact (fixing_subgroup_equiv (fixed_field H)).to_equiv.symm end instance fixed_field.algebra : algebra K (fixed_field (fixing_subgroup K)) := { smul := λ x y, ⟨x*y, λ ϕ, by rw [smul_mul', (show ϕ • ↑x = ↑x, by exact subtype.mem ϕ x), (show ϕ • ↑y = ↑y, by exact subtype.mem y ϕ)]⟩, to_fun := λ x, ⟨x, λ ϕ, subtype.mem ϕ x⟩, map_zero' := rfl, map_add' := λ _ _, rfl, map_one' := rfl, map_mul' := λ _ _, rfl, commutes' := λ _ _, mul_comm _ _, smul_def' := λ _ _, rfl } instance fixed_field.is_scalar_tower : is_scalar_tower K (fixed_field (fixing_subgroup K)) E := ⟨λ _ _ _, mul_assoc _ _ _⟩ end intermediate_field namespace is_galois theorem fixed_field_fixing_subgroup [finite_dimensional F E] [h : is_galois F E] : intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) = K := begin have K_le : K ≤ intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) := (intermediate_field.le_iff_le _ _).mpr (le_refl _), suffices : finrank K E = finrank (intermediate_field.fixed_field (intermediate_field.fixing_subgroup K)) E, { exact (intermediate_field.eq_of_le_of_finrank_eq' K_le this).symm }, rw [intermediate_field.finrank_fixed_field_eq_card, fintype.card_congr (intermediate_field.fixing_subgroup_equiv K).to_equiv], exact (card_aut_eq_finrank K E).symm, end lemma card_fixing_subgroup_eq_finrank [finite_dimensional F E] [is_galois F E] : fintype.card (intermediate_field.fixing_subgroup K) = finrank K E := by conv { to_rhs, rw [←fixed_field_fixing_subgroup K, intermediate_field.finrank_fixed_field_eq_card] } /-- The Galois correspondence from intermediate fields to subgroups -/ def intermediate_field_equiv_subgroup [finite_dimensional F E] [is_galois F E] : intermediate_field F E ≃o order_dual (subgroup (E ≃ₐ[F] E)) := { to_fun := intermediate_field.fixing_subgroup, inv_fun := intermediate_field.fixed_field, left_inv := λ K, fixed_field_fixing_subgroup K, right_inv := λ H, intermediate_field.fixing_subgroup_fixed_field H, map_rel_iff' := λ K L, by { rw [←fixed_field_fixing_subgroup L, intermediate_field.le_iff_le, fixed_field_fixing_subgroup L, ←order_dual.dual_le], refl } } /-- The Galois correspondence as a galois_insertion -/ def galois_insertion_intermediate_field_subgroup [finite_dimensional F E] : galois_insertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ K _, intermediate_field.fixing_subgroup K, gc := λ K H, (intermediate_field.le_iff_le H K).symm, le_l_u := λ H, le_of_eq (intermediate_field.fixing_subgroup_fixed_field H).symm, choice_eq := λ K _, rfl } /-- The Galois correspondence as a galois_coinsertion -/ def galois_coinsertion_intermediate_field_subgroup [finite_dimensional F E] [is_galois F E] : galois_coinsertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ H _, intermediate_field.fixed_field H, gc := λ K H, (intermediate_field.le_iff_le H K).symm, u_l_le := λ K, le_of_eq (fixed_field_fixing_subgroup K), choice_eq := λ H _, rfl } end is_galois end galois_correspondence section galois_equivalent_definitions variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] namespace is_galois lemma is_separable_splitting_field [finite_dimensional F E] [is_galois F E] : ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E := begin cases field.exists_primitive_element F E with α h1, use [minpoly F α, separable F α, is_galois.splits F α], rw [eq_top_iff, ←intermediate_field.top_to_subalgebra, ←h1], rw intermediate_field.adjoin_simple_to_subalgebra_of_integral F α (integral F α), apply algebra.adjoin_mono, rw [set.singleton_subset_iff, finset.mem_coe, multiset.mem_to_finset, polynomial.mem_roots], { dsimp only [polynomial.is_root], rw [polynomial.eval_map, ←polynomial.aeval_def], exact minpoly.aeval _ _ }, { exact polynomial.map_ne_zero (minpoly.ne_zero (integral F α)) } end lemma of_fixed_field_eq_bot [finite_dimensional F E] (h : intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥) : is_galois F E := begin rw [←is_galois_iff_is_galois_bot, ←h], exact is_galois.of_fixed_field E (⊤ : subgroup (E ≃ₐ[F] E)), end lemma of_card_aut_eq_finrank [finite_dimensional F E] (h : fintype.card (E ≃ₐ[F] E) = finrank F E) : is_galois F E := begin apply of_fixed_field_eq_bot, have p : 0 < finrank (intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E))) E := finrank_pos, rw [←intermediate_field.finrank_eq_one_iff, ←mul_left_inj' (ne_of_lt p).symm, finrank_mul_finrank, ←h, one_mul, intermediate_field.finrank_fixed_field_eq_card], apply fintype.card_congr, exact { to_fun := λ g, ⟨g, subgroup.mem_top g⟩, inv_fun := coe, left_inv := λ g, rfl, right_inv := λ _, by { ext, refl } }, end variables {F} {E} {p : polynomial F} lemma of_separable_splitting_field_aux [hFE : finite_dimensional F E] [sp : p.is_splitting_field F E] (hp : p.separable) (K : intermediate_field F E) {x : E} (hx : x ∈ (p.map (algebra_map F E)).roots) : fintype.card ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) = fintype.card (K →ₐ[F] E) * finrank K K⟮x⟯ := begin have h : is_integral K x := is_integral_of_is_scalar_tower x (is_integral_of_noetherian hFE x), have h1 : p ≠ 0 := λ hp, by rwa [hp, polynomial.map_zero, polynomial.roots_zero] at hx, have h2 : (minpoly K x) ∣ p.map (algebra_map F K), { apply minpoly.dvd, rw [polynomial.aeval_def, polynomial.eval₂_map, ←polynomial.eval_map], exact (polynomial.mem_roots (polynomial.map_ne_zero h1)).mp hx }, let key_equiv : ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) ≃ Σ (f : K →ₐ[F] E), @alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f) := equiv.trans (alg_equiv.arrow_congr (intermediate_field.lift2_alg_equiv K⟮x⟯) (alg_equiv.refl)) alg_hom_equiv_sigma, haveI : Π (f : K →ₐ[F] E), fintype (@alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f)) := λ f, by { apply fintype.of_injective (sigma.mk f) (λ _ _ H, eq_of_heq ((sigma.mk.inj H).2)), exact fintype.of_equiv _ key_equiv }, rw [fintype.card_congr key_equiv, fintype.card_sigma, intermediate_field.adjoin.finrank h], apply finset.sum_const_nat, intros f hf, rw ← @intermediate_field.card_alg_hom_adjoin_integral K _ E _ _ x E _ (ring_hom.to_algebra f) h, { apply fintype.card_congr, refl }, { exact polynomial.separable.of_dvd ((polynomial.separable_map (algebra_map F K)).mpr hp) h2 }, { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero h1) _ h2, rw [polynomial.splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact sp.splits }, end lemma of_separable_splitting_field [sp : p.is_splitting_field F E] (hp : p.separable) : is_galois F E := begin haveI hFE : finite_dimensional F E := polynomial.is_splitting_field.finite_dimensional E p, let s := (p.map (algebra_map F E)).roots.to_finset, have adjoin_root : intermediate_field.adjoin F ↑s = ⊤, { apply intermediate_field.to_subalgebra_injective, rw [intermediate_field.top_to_subalgebra, ←top_le_iff, ←sp.adjoin_roots], apply intermediate_field.algebra_adjoin_le_adjoin, }, let P : intermediate_field F E → Prop := λ K, fintype.card (K →ₐ[F] E) = finrank F K, suffices : P (intermediate_field.adjoin F ↑s), { rw adjoin_root at this, apply of_card_aut_eq_finrank, rw ← eq.trans this (linear_equiv.finrank_eq intermediate_field.top_equiv.to_linear_equiv), exact fintype.card_congr (equiv.trans (alg_equiv_equiv_alg_hom F E) (alg_equiv.arrow_congr intermediate_field.top_equiv.symm alg_equiv.refl)) }, apply intermediate_field.induction_on_adjoin_finset s P, { have key := intermediate_field.card_alg_hom_adjoin_integral F (show is_integral F (0 : E), by exact is_integral_zero), rw [minpoly.zero, polynomial.nat_degree_X] at key, specialize key polynomial.separable_X (polynomial.splits_X (algebra_map F E)), rw [←@subalgebra.finrank_bot F E _ _ _, ←intermediate_field.bot_to_subalgebra] at key, refine eq.trans _ key, apply fintype.card_congr, rw intermediate_field.adjoin_zero }, intros K x hx hK, simp only [P] at *, rw [of_separable_splitting_field_aux hp K (multiset.mem_to_finset.mp hx), hK, finrank_mul_finrank], exact (linear_equiv.finrank_eq (intermediate_field.lift2_alg_equiv K⟮x⟯).to_linear_equiv).symm, end /--Equivalent characterizations of a Galois extension of finite degree-/ theorem tfae [finite_dimensional F E] : tfae [is_galois F E, intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥, fintype.card (E ≃ₐ[F] E) = finrank F E, ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E] := begin tfae_have : 1 → 2, { exact λ h, order_iso.map_bot (@intermediate_field_equiv_subgroup F _ E _ _ _ h).symm }, tfae_have : 1 → 3, { introI _, exact card_aut_eq_finrank F E }, tfae_have : 1 → 4, { introI _, exact is_separable_splitting_field F E }, tfae_have : 2 → 1, { exact of_fixed_field_eq_bot F E }, tfae_have : 3 → 1, { exact of_card_aut_eq_finrank F E }, tfae_have : 4 → 1, { rintros ⟨h, hp1, _⟩, exactI of_separable_splitting_field hp1 }, tfae_finish, end end is_galois end galois_equivalent_definitions
2cec5fec96e4662bba82934235b0b51013d61b93
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/convPatternAtLetIssue.lean
2ced3e81eaed919050bef979b6bf7e7f4a2eaa9e
[ "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
224
lean
def f (x : Nat) := x def test : (λ x => f x) = (λ x : Nat => let foo := λ y => id (id y) foo x) := by conv => pattern (id _) trace_state simp trace_state
0f140ac8147c4c041b2fb967a3b233f69c9437d5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed/field/unit_ball.lean
9de3087c3a72d083ea3ddac325d40e60e475af9e
[ "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
7,409
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth -/ import analysis.normed.field.basic import analysis.normed.group.ball_sphere /-! # Algebraic structures on unit balls and spheres In this file we define algebraic structures (`semigroup`, `comm_semigroup`, `monoid`, `comm_monoid`, `group`, `comm_group`) on `metric.ball (0 : 𝕜) 1`, `metric.closed_ball (0 : 𝕜) 1`, and `metric.sphere (0 : 𝕜) 1`. In each case we use the weakest possible typeclass assumption on `𝕜`, from `non_unital_semi_normed_ring` to `normed_field`. -/ open set metric variables {𝕜 : Type*} /-- Unit ball in a non unital semi normed ring as a bundled `subsemigroup`. -/ def subsemigroup.unit_ball (𝕜 : Type*) [non_unital_semi_normed_ring 𝕜] : subsemigroup 𝕜 := { carrier := ball (0 : 𝕜) 1, mul_mem' := λ x y hx hy, begin rw [mem_ball_zero_iff] at *, exact (norm_mul_le x y).trans_lt (mul_lt_one_of_nonneg_of_lt_one_left (norm_nonneg _) hx hy.le) end } instance [non_unital_semi_normed_ring 𝕜] : semigroup (ball (0 : 𝕜) 1) := mul_mem_class.to_semigroup (subsemigroup.unit_ball 𝕜) instance [non_unital_semi_normed_ring 𝕜] : has_continuous_mul (ball (0 : 𝕜) 1) := (subsemigroup.unit_ball 𝕜).has_continuous_mul instance [semi_normed_comm_ring 𝕜] : comm_semigroup (ball (0 : 𝕜) 1) := mul_mem_class.to_comm_semigroup (subsemigroup.unit_ball 𝕜) instance [non_unital_semi_normed_ring 𝕜] : has_distrib_neg (ball (0 : 𝕜) 1) := subtype.coe_injective.has_distrib_neg (coe : ball (0 : 𝕜) 1 → 𝕜) (λ _, rfl) (λ _ _, rfl) @[simp, norm_cast] lemma coe_mul_unit_ball [non_unital_semi_normed_ring 𝕜] (x y : ball (0 : 𝕜) 1) : ↑(x * y) = (x * y : 𝕜) := rfl /-- Closed unit ball in a non unital semi normed ring as a bundled `subsemigroup`. -/ def subsemigroup.unit_closed_ball (𝕜 : Type*) [non_unital_semi_normed_ring 𝕜] : subsemigroup 𝕜 := { carrier := closed_ball 0 1, mul_mem' := λ x y hx hy, begin rw [mem_closed_ball_zero_iff] at *, exact (norm_mul_le x y).trans (mul_le_one hx (norm_nonneg _) hy) end } instance [non_unital_semi_normed_ring 𝕜] : semigroup (closed_ball (0 : 𝕜) 1) := mul_mem_class.to_semigroup (subsemigroup.unit_closed_ball 𝕜) instance [non_unital_semi_normed_ring 𝕜] : has_distrib_neg (closed_ball (0 : 𝕜) 1) := subtype.coe_injective.has_distrib_neg (coe : closed_ball (0 : 𝕜) 1 → 𝕜) (λ _, rfl) (λ _ _, rfl) instance [non_unital_semi_normed_ring 𝕜] : has_continuous_mul (closed_ball (0 : 𝕜) 1) := (subsemigroup.unit_closed_ball 𝕜).has_continuous_mul @[simp, norm_cast] lemma coe_mul_unit_closed_ball [non_unital_semi_normed_ring 𝕜] (x y : closed_ball (0 : 𝕜) 1) : ↑(x * y) = (x * y : 𝕜) := rfl /-- Closed unit ball in a semi normed ring as a bundled `submonoid`. -/ def submonoid.unit_closed_ball (𝕜 : Type*) [semi_normed_ring 𝕜] [norm_one_class 𝕜] : submonoid 𝕜 := { carrier := closed_ball 0 1, one_mem' := mem_closed_ball_zero_iff.2 norm_one.le, .. subsemigroup.unit_closed_ball 𝕜 } instance [semi_normed_ring 𝕜] [norm_one_class 𝕜] : monoid (closed_ball (0 : 𝕜) 1) := submonoid_class.to_monoid (submonoid.unit_closed_ball 𝕜) instance [semi_normed_comm_ring 𝕜] [norm_one_class 𝕜] : comm_monoid (closed_ball (0 : 𝕜) 1) := submonoid_class.to_comm_monoid (submonoid.unit_closed_ball 𝕜) @[simp, norm_cast] lemma coe_one_unit_closed_ball [semi_normed_ring 𝕜] [norm_one_class 𝕜] : ((1 : closed_ball (0 : 𝕜) 1) : 𝕜) = 1 := rfl @[simp, norm_cast] lemma coe_pow_unit_closed_ball [semi_normed_ring 𝕜] [norm_one_class 𝕜] (x : closed_ball (0 : 𝕜) 1) (n : ℕ) : ↑(x ^ n) = (x ^ n : 𝕜) := rfl /-- Unit sphere in a normed division ring as a bundled `submonoid`. -/ def submonoid.unit_sphere (𝕜 : Type*) [normed_division_ring 𝕜] : submonoid 𝕜 := { carrier := sphere (0 : 𝕜) 1, mul_mem' := λ x y hx hy, by { rw [mem_sphere_zero_iff_norm] at *, simp * }, one_mem' := mem_sphere_zero_iff_norm.2 norm_one } instance [normed_division_ring 𝕜] : has_inv (sphere (0 : 𝕜) 1) := ⟨λ x, ⟨x⁻¹, mem_sphere_zero_iff_norm.2 $ by rw [norm_inv, mem_sphere_zero_iff_norm.1 x.coe_prop, inv_one]⟩⟩ @[simp, norm_cast] lemma coe_inv_unit_sphere [normed_division_ring 𝕜] (x : sphere (0 : 𝕜) 1) : ↑x⁻¹ = (x⁻¹ : 𝕜) := rfl instance [normed_division_ring 𝕜] : has_div (sphere (0 : 𝕜) 1) := ⟨λ x y, ⟨x / y, mem_sphere_zero_iff_norm.2 $ by rw [norm_div, mem_sphere_zero_iff_norm.1 x.coe_prop, mem_sphere_zero_iff_norm.1 y.coe_prop, div_one]⟩⟩ @[simp, norm_cast] lemma coe_div_unit_sphere [normed_division_ring 𝕜] (x y : sphere (0 : 𝕜) 1) : ↑(x / y) = (x / y : 𝕜) := rfl instance [normed_division_ring 𝕜] : has_pow (sphere (0 : 𝕜) 1) ℤ := ⟨λ x n, ⟨x ^ n, by rw [mem_sphere_zero_iff_norm, norm_zpow, mem_sphere_zero_iff_norm.1 x.coe_prop, one_zpow]⟩⟩ @[simp, norm_cast] lemma coe_zpow_unit_sphere [normed_division_ring 𝕜] (x : sphere (0 : 𝕜) 1) (n : ℤ) : ↑(x ^ n) = (x ^ n : 𝕜) := rfl instance [normed_division_ring 𝕜] : monoid (sphere (0 : 𝕜) 1) := submonoid_class.to_monoid (submonoid.unit_sphere 𝕜) @[simp, norm_cast] lemma coe_one_unit_sphere [normed_division_ring 𝕜] : ((1 : sphere (0 : 𝕜) 1) : 𝕜) = 1 := rfl @[simp, norm_cast] lemma coe_mul_unit_sphere [normed_division_ring 𝕜] (x y : sphere (0 : 𝕜) 1) : ↑(x * y) = (x * y : 𝕜) := rfl @[simp, norm_cast] lemma coe_pow_unit_sphere [normed_division_ring 𝕜] (x : sphere (0 : 𝕜) 1) (n : ℕ) : ↑(x ^ n) = (x ^ n : 𝕜) := rfl /-- Monoid homomorphism from the unit sphere to the group of units. -/ def unit_sphere_to_units (𝕜 : Type*) [normed_division_ring 𝕜] : sphere (0 : 𝕜) 1 →* units 𝕜 := units.lift_right (submonoid.unit_sphere 𝕜).subtype (λ x, units.mk0 x $ ne_zero_of_mem_unit_sphere _) (λ x, rfl) @[simp] lemma unit_sphere_to_units_apply_coe [normed_division_ring 𝕜] (x : sphere (0 : 𝕜) 1) : (unit_sphere_to_units 𝕜 x : 𝕜) = x := rfl lemma unit_sphere_to_units_injective [normed_division_ring 𝕜] : function.injective (unit_sphere_to_units 𝕜) := λ x y h, subtype.eq $ by convert congr_arg units.val h instance [normed_division_ring 𝕜] : group (sphere (0 : 𝕜) 1) := unit_sphere_to_units_injective.group (unit_sphere_to_units 𝕜) (units.ext rfl) (λ x y, units.ext rfl) (λ x, units.ext rfl) (λ x y, units.ext $ div_eq_mul_inv _ _) (λ x n, units.ext (units.coe_pow (unit_sphere_to_units 𝕜 x) n).symm) (λ x n, units.ext (units.coe_zpow (unit_sphere_to_units 𝕜 x) n).symm) instance [normed_division_ring 𝕜] : has_distrib_neg (sphere (0 : 𝕜) 1) := subtype.coe_injective.has_distrib_neg (coe : sphere (0 : 𝕜) 1 → 𝕜) (λ _, rfl) (λ _ _, rfl) instance [normed_division_ring 𝕜] : topological_group (sphere (0 : 𝕜) 1) := { to_has_continuous_mul := (submonoid.unit_sphere 𝕜).has_continuous_mul, continuous_inv := (continuous_subtype_coe.inv₀ ne_zero_of_mem_unit_sphere).subtype_mk _ } instance [normed_field 𝕜] : comm_group (sphere (0 : 𝕜) 1) := { .. metric.sphere.group, .. submonoid_class.to_comm_monoid (submonoid.unit_sphere 𝕜) }
bc433978fba80f154cb37d1cfd2c9ffd0c7ee82e
c055f4b7c29cf1aac2223bd8c1ac8d181a7c6447
/src/categories/opposites.lean
f955e33cb03a06261fc0bf93050f22fa9518c668
[ "Apache-2.0" ]
permissive
rwbarton/lean-category-theory-pr
77207b6674eeec1e258ec85dea58f3bff8d27065
591847d70c6a11c4d5561cd0eaf69b1fe85a70ab
refs/heads/master
1,584,595,111,303
1,528,029,041,000
1,528,029,041,000
135,919,126
0
0
null
1,528,041,805,000
1,528,041,805,000
null
UTF-8
Lean
false
false
3,692
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .functor import .products import .types open categories open categories.functor open categories.products open categories.types namespace categories.opposites universes u₁ v₁ u₂ v₂ def op (C : Type u₁) : Type u₁ := C notation C `ᵒᵖ` := op C section variable {C : Type u₁} variable [C_cat : category.{u₁ v₁} C] include C_cat instance Opposite : category.{u₁ v₁} (Cᵒᵖ) := { Hom := λ X Y : C, Y ⟶ X, compose := λ _ _ _ f g, g ≫ f, identity := λ X, 𝟙 X, left_identity := begin -- `obviously'` says: intros, simp end, right_identity := begin -- `obviously'` says: intros, simp end, associativity := begin -- `obviously'` says: intros, simp end } variable {D : Type u₂} variable [D_cat : category.{u₂ v₂} D] include D_cat definition OppositeFunctor (F : C ↝ D) : (Cᵒᵖ) ↝ (Dᵒᵖ) := { onObjects := λ X, F.onObjects X, -- notation (F +> X) fails here, because C ≠ Cᵒᵖ onMorphisms := λ X Y f, F &> f, identities := begin -- `obviously'` says: intros, erw [Functor.identities_lemma], refl, end, functoriality := begin -- `obviously'` says: intros, erw [Functor.functoriality_lemma], refl, end } -- TODO are these @s really needed? @[simp,ematch] lemma ContravariantFunctor.functoriality (F : (Cᵒᵖ) ↝ D) (X Y Z : (Cᵒᵖ)) (f : X ⟶ Y) (g : Y ⟶ Z) : F &> ((@categories.category.compose C _ _ _ _ g f) : X ⟶ Z) = (F &> f) ≫ (F &> g) := begin -- `obviously'` says: erw [Functor.functoriality_lemma] end @[simp,ematch] lemma ContravariantFunctor.identities (F : (Cᵒᵖ) ↝ D) (X : (Cᵒᵖ)) : (F &> (@categories.category.identity C _ X)) = 𝟙 (F +> X) := begin -- `obviously'` says: erw [Functor.identities_lemma], end end definition HomPairing (C : Type u₁) [category.{u₁ v₁} C] : Functor (Cᵒᵖ × C) (Type v₁) := { onObjects := λ p, @category.Hom C _ p.1 p.2, onMorphisms := λ X Y f, λ h, f.1 ≫ h ≫ f.2, identities := begin -- `obviously'` says: intros, apply funext, intros, cases X, dsimp, dsimp at *, simp, erw [category.left_identity_lemma], end, functoriality := begin -- `obviously'` says: --- intros, apply funext, intros, cases g, cases f, cases Z, cases Y, cases X, dsimp, dsimp at *, simp, dsimp, erw [category.associativity_lemma] --- end } -- PROJECT prove C^op^op is C -- definition OppositeOpposite (C : Category) : Equivalence (Opposite (Opposite C)) C := sorry -- PROJECT opposites preserve products, functors, slices. end categories.opposites
7c3ad127b209e26f64814991f1cced751216c94c
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/macroid.lean
6c7301035098a77d9c5c4d8450155b73f1f8c2a7
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
622
lean
new_frontend syntax "[" ident "↦" term "]" : term macro_rules `([$x ↦ $v]) => `(fun $x => $v) #check [x ↦ x + 1] syntax "case!" ident ":" term "with" term "," term : term macro_rules `(case! $h : $c with $t, $e) => `((fun $h => cond $h $t $e) $c) #check case! h : 0 == 0 with h, not h syntax "case2!" ident ":" term "with" term "," term : term macro_rules `(case2! $h : $c with $t, $e) => `(let $h := $c; cond $h $t $e) #check case2! h : 0 == 0 with h, not h syntax "test" term : term macro_rules `(test $x:ident) => `(let $x := 0; $x) #check fun (x : Nat) => test x #check x where y := 1; where x := y + 1
8d202edd782ebb79d9d06e218c1e663bd09f47af
a6f55abce20abcd06e718cb3e5fba7bf8a230fa1
/topic/fruit.lean
0bde883c4e2f59b4e8e24c15173831f695993953
[]
no_license
sonna0909/abc
b8a53e906d4d000d1f2347173a1cd4221757fabf
ff7b4c621cdf6d53937f2d1b6def28de2085a2aa
refs/heads/master
1,599,114,664,248
1,573,634,309,000
1,573,634,309,000
219,406,484
0
0
null
null
null
null
UTF-8
Lean
false
false
20,305
lean
[ { "key": "apple", "title": "Apple", "spelling": "/’æpl/", "subs": [ { "key": "apple", "title": "An apple", "spelling": "" }, { "key": "apples", "title": "Apples", "spelling": "" }, { "key": "apple", "title": "There is an apple", "spelling": "" }, { "key": "3_apples", "title": "There are 3 apples", "spelling": "" } ] }, { "key": "orange", "title": "Orange", "spelling": "/ɒrɪndʒ/", "subs": [ { "key": "an_orange", "title": "An orange", "spelling": "" }, { "key": "oranges", "title": "Oranges", "spelling": "" }, { "key": "an_orange1", "title": "There is an orange", "spelling": "" }, { "key": "4_oranges", "title": "There are 4 oranges", "spelling": "" } ] }, { "key": "banana", "title": "Banana", "spelling": "/bə’nɑ:nə/", "subs": [ { "key": "a_Banana", "title": "a banana", "spelling": "" }, { "key": "bananas", "title": "Bananas", "spelling": "" }, { "key": "a_Banana1", "title": "There is a banana", "spelling": "" }, { "key": "5_Bananas", "title": "There are 5 bananas", "spelling": "" } ] }, { "key": "grape", "title": "Grape", "spelling": "/greɪp/", "subs": [ { "key": "a_Grape", "title": "a Grape", "spelling": "" }, { "key": "grapes", "title": "Grapes", "spelling": "" }, { "key": "a_Grape1", "title": "There is a grape", "spelling": "" }, { "key": "3_Grapes", "title": "There are 3 grapes", "spelling": "" } ] }, { "key": "grapefruit", "title": "Grapefruit", "spelling": "/’greipfru:t/", "subs": [ { "key": "a_grapefruit", "title": "a Grapefruit", "spelling": "" }, { "key": "grapefruits", "title": "Grapefruits", "spelling": "" }, { "key": "a_grapefruit1", "title": "There is a grapefruit", "spelling": "" }, { "key": "2_grapefruits", "title": "There are 2 grapefruits", "spelling": "" } ] }, { "key": "starfruit", "title": "Starfruit", "spelling": "/’stɑ:r.fru:t/", "subs": [ { "key": "a_starfruit", "title": "A starfruit", "spelling": "" }, { "key": "starfruits", "title": "Starfruits", "spelling": "" }, { "key": "a_starfruit1", "title": "There is a starfruit", "spelling": "" }, { "key": "6_starfruits", "title": "There are 6 starfruits", "spelling": "" } ] }, { "key": "mango", "title": "Mango", "spelling": "/´mæηgou/", "subs": [ { "key": "a_mango", "title": "a Mango", "spelling": "" }, { "key": "mangos", "title": "Mangos", "spelling": "" }, { "key": "a_mango1", "title": "There is a mango", "spelling": "" }, { "key": "7_mangos", "title": "There are 7 mangos", "spelling": "" } ] }, { "key": "ambarella", "title": "Ambarella", "spelling": "/’æmbə’rælə/", "subs": [ { "key": "an_ambarella", "title": "An ambarella", "spelling": "" }, { "key": "ambarellas", "title": "Ambarellas", "spelling": "" }, { "key": "an_ambarella1", "title": "There is an ambarella", "spelling": "" }, { "key": "8_ambarellas", "title": "There are 8 ambarellas", "spelling": "" } ] }, { "key": "apricot", "title": "Apricot", "spelling": "/ˈæ.prɪ.kɒt/", "subs": [ { "key": "an_apricot", "title": "An apricot", "spelling": "" }, { "key": "apricots", "title": "Apricots", "spelling": "" }, { "key": "an_apricot1", "title": "There is an apricot", "spelling": "" }, { "key": "9_apricots", "title": "There are 9 apricots", "spelling": "" } ] }, { "key": "avocado", "title": "Avocado", "spelling": "/¸ævə´ka:dou/", "subs": [ { "key": "an_avocado", "title": "An avocado", "spelling": "" }, { "key": "avocadoes", "title": "Avocadoes", "spelling": "" }, { "key": "an_avocado1", "title": "There is an avocado", "spelling": "" }, { "key": "4_avocados", "title": "There are 4 avocados", "spelling": "" } ] }, { "key": "berry", "title": "Berry", "spelling": "/’beri/", "subs": [ { "key": "a_berry", "title": "A berry", "spelling": "" }, { "key": "berries", "title": "Berries", "spelling": "" }, { "key": "a_berry1", "title": "There is a berry", "spelling": "" }, { "key": "4_berries", "title": "There are 4 berries", "spelling": "" } ] }, { "key": "cherry", "title": "Cherry", "spelling": "/´tʃeri/", "subs": [ { "key": "a_cherry", "title": "A cherry", "spelling": "" }, { "key": "cherries", "title": "Cherries", "spelling": "" }, { "key": "a_cherry1", "title": "There is a cherry", "spelling": "" }, { "key": "4_cherries", "title": "There are 4 cherries", "spelling": "" } ] }, { "key": "citron", "title": "Citron", "spelling": "/´sitrən/", "subs": [ { "key": "a_citron", "title": "A citron", "spelling": "" }, { "key": "citrons", "title": "Citrons", "spelling": "" }, { "key": "a_citron1", "title": "There is a citron", "spelling": "" }, { "key": "10_citrons", "title": "There are 10 citrons", "spelling": "" } ] }, { "key": "coconut", "title": "Coconut", "spelling": "/’koukənʌt/", "subs": [ { "key": "a_coconut", "title": "A coconut", "spelling": "" }, { "key": "coconuts", "title": "Coconuts", "spelling": "" }, { "key": "a_coconut1", "title": "There is a coconut", "spelling": "" }, { "key": "10_coconuts", "title": "There are 10 coconuts", "spelling": "" } ] }, { "key": "custard-apple", "title": "Custard-apple", "spelling": "/’kʌstəd,æpl/", "subs": [ { "key": "a_custard-apple", "title": "A custard-apple", "spelling": "" }, { "key": "custard-apples", "title": "Custard-apples", "spelling": "" }, { "key": "a_custard-apple1", "title": "There is a custard-apple", "spelling": "" }, { "key": "9_custard-apples", "title": "There are 9 custard-apples", "spelling": "" } ] }, { "key": "date", "title": "Date", "spelling": "/deit/", "subs": [ { "key": "a_date", "title": "A date", "spelling": "" }, { "key": "dates", "title": "Dates", "spelling": "" }, { "key": "a_date1", "title": "There is a date", "spelling": "" }, { "key": "15_dates", "title": "There are 15 dates", "spelling": "" } ] }, { "key": "dracontomelon", "title": "Dracontomelon", "spelling": "/ˈdrækʌntɒnmelən/", "subs": [ { "key": "a_dracontomelon", "title": "A dracontomelon", "spelling": "" }, { "key": "dracontomelons", "title": "Dracontomelons", "spelling": "" }, { "key": "a_dracontomelon1", "title": "There is a dracontomelon", "spelling": "" }, { "key": "17_dracontomelons", "title": "There are 17 dracontomelons", "spelling": "" } ] }, { "key": "durian", "title": "Durian", "spelling": "/´duəriən/", "subs": [ { "key": "a_durian", "title": "A durian", "spelling": "" }, { "key": "durians", "title": "Durians", "spelling": "" }, { "key": "a_durian1", "title": "There is a durian", "spelling": "" }, { "key": "18_durians", "title": "There are 18 durians", "spelling": "" } ] }, { "key": "fig", "title": "Fig", "spelling": "/fig/", "subs": [ { "key": "a_fig", "title": "A fig", "spelling": "" }, { "key": "figs", "title": "Figs", "spelling": "" }, { "key": "a_fig1", "title": "There is a fig", "spelling": "" }, { "key": "19_figs", "title": "There are 19 figs", "spelling": "" } ] }, { "key": "guava", "title": "Guava", "spelling": "/´gwa:və/", "subs": [ { "key": "a_guava", "title": "A guava", "spelling": "" }, { "key": "guavas", "title": "Guavas", "spelling": "" }, { "key": "a_guava1", "title": "There is a guava", "spelling": "" }, { "key": "20_guavas", "title": "There are 20 guavas", "spelling": "" } ] }, { "key": "kumquat", "title": "Kumquat", "spelling": "/´’kʌmkwɔt/", "subs": [ { "key": "a_kumquat", "title": "A kumquat", "spelling": "" }, { "key": "kumquats", "title": "Kumquats", "spelling": "" }, { "key": "a_kumquat1", "title": "There is a kumquat", "spelling": "" }, { "key": "21_kumquats", "title": "There are 21 kumquats", "spelling": "" } ] }, { "key": "lime", "title": "Lime", "spelling": "/laim/", "subs": [ { "key": "a_lime", "title": "A lime", "spelling": "" }, { "key": "limes", "title": "Limes", "spelling": "" }, { "key": "a_lime1", "title": "There is a lime", "spelling": "" }, { "key": "22_limes", "title": "There are 22 limes", "spelling": "" } ] }, { "key": "longan", "title": "Longan", "spelling": "/lɔɳgən/", "subs": [ { "key": "a_longan", "title": "A longan", "spelling": "" }, { "key": "longans", "title": "Longans", "spelling": "" }, { "key": "a_longan1", "title": "There is a longan", "spelling": "" }, { "key": "23_longans", "title": "There are 23 longans", "spelling": "" } ] }, { "key": "lychee", "title": "Lychee", "spelling": "/’li:tʃi:/", "subs": [ { "key": "a_lychee", "title": "A lychee", "spelling": "" }, { "key": "lychees", "title": "Lychees", "spelling": "" }, { "key": "a_lychee1", "title": "There is a lychee", "spelling": "" }, { "key": "24_lychees", "title": "There are 24 lychees", "spelling": "" } ] }, { "key": "peach", "title": "Peach", "spelling": "/pitʃ/", "subs": [ { "key": "a_peach", "title": "A peach", "spelling": "" }, { "key": "peaches", "title": "Peaches", "spelling": "" }, { "key": "a_peach1", "title": "There is a peach", "spelling": "" }, { "key": "25_peaches", "title": "There are 25 peaches", "spelling": "" } ] }, { "key": "pear", "title": "Pear", "spelling": "/peə/", "subs": [ { "key": "a_pear", "title": "A pear", "spelling": "" }, { "key": "pears", "title": "Pears", "spelling": "" }, { "key": "a_pear2", "title": "There is a pear", "spelling": "" }, { "key": "26_pears", "title": "There are 26 pears", "spelling": "" } ] }, { "key": "persimmon", "title": "Persimmon", "spelling": "/pə´simən/", "subs": [ { "key": "a_persimmon", "title": "A persimmon", "spelling": "" }, { "key": "persimmons", "title": "Persimmons", "spelling": "" }, { "key": "a_persimmon3", "title": "There is a persimmon", "spelling": "" }, { "key": "27_persimmons", "title": "There are 27 persimmons", "spelling": "" } ] }, { "key": "pineapple", "title": "Pineapple", "spelling": "/pə´simən/", "subs": [ { "key": "a_pineapple", "title": "A pineapple", "spelling": "" }, { "key": "pineapples", "title": "Pineapples", "spelling": "" }, { "key": "a_pineapple2", "title": "There is a pineapple", "spelling": "" }, { "key": "28_pineapples", "title": "There are 28 pineapples", "spelling": "" } ] }, { "key": "pitaya", "title": "Pitaya", "spelling": "/pɪˈtaɪ.ə/", "subs": [ { "key": "a_pitaya", "title": "A pitaya", "spelling": "" }, { "key": "pitayas", "title": "Pitayas", "spelling": "" }, { "key": "a_pitaya2", "title": "There is a pitaya", "spelling": "" }, { "key": "28_pitayas", "title": "There are 29 pitayas", "spelling": "" } ] }, { "key": "plum", "title": "Plum", "spelling": "/plʌm/", "subs": [ { "key": "a_plum", "title": "A plum", "spelling": "" }, { "key": "plums", "title": "Plums", "spelling": "" }, { "key": "a_plum2", "title": "There is a plum", "spelling": "" }, { "key": "29_plums", "title": "There are 29 plums", "spelling": "" } ] }, { "key": "pomegranate", "title": "Pomegranate", "spelling": "/´pɔm¸grænit/", "subs": [ { "key": "a_pomegranate", "title": "A pomegranate", "spelling": "" }, { "key": "pomegranates", "title": "Pomegranates", "spelling": "" }, { "key": "a_pomegranate1", "title": "There is a pomegranate", "spelling": "" }, { "key": "30_pomegranates", "title": "There are 30 pomegranates", "spelling": "" } ] }, { "key": "pomelo", "title": "Pomelo", "spelling": "/ˈpɒmələʊ/", "subs": [ { "key": "a_pomelo", "title": "A pomelo", "spelling": "" }, { "key": "pomeloes", "title": "Pomeloes", "spelling": "" }, { "key": "a_pomelo2", "title": "There is a pomelo", "spelling": "" }, { "key": "31_pomeloes", "title": "There are 31 pomeloes", "spelling": "" } ] }, { "key": "rambutan", "title": "Rambutan", "spelling": "/ræmˈbuːtən/", "subs": [ { "key": "a_rambutan", "title": "A rambutan", "spelling": "" }, { "key": "rambutans", "title": "Rambutans", "spelling": "" }, { "key": "a_rambutan2", "title": "There is a rambutan", "spelling": "" }, { "key": "32_rambutans", "title": "There are 32 rambutans", "spelling": "" } ] }, { "key": "sapota", "title": "Sapota", "spelling": "/sə’poutə/", "subs": [ { "key": "a_sapota", "title": "A sapota", "spelling": "" }, { "key": "sapotas", "title": "Sapotas", "spelling": "" }, { "key": "a_sapota2", "title": "There is a sapota", "spelling": "" }, { "key": "33_sapotas", "title": "There are 33 sapotas", "spelling": "" } ] }, { "key": "soursop", "title": "Soursop", "spelling": "/’sɔ:sɔp/", "subs": [ { "key": "a_soursop", "title": "A soursop", "spelling": "" }, { "key": "soursops", "title": "Soursops", "spelling": "" }, { "key": "a_soursop1", "title": "There is a soursop", "spelling": "" }, { "key": "34_soursops", "title": "There are 34 soursops", "spelling": "" } ] }, { "key": "watermelon", "title": "Watermelon", "spelling": "/’wɔ:tə´melən/", "subs": [ { "key": "a_watermelon", "title": "A watermelon", "spelling": "" }, { "key": "watermelons", "title": "Watermelons", "spelling": "" }, { "key": "a_watermelon1", "title": "There is a watermelon", "spelling": "" }, { "key": "35_watermelons", "title": "There are 35 watermelons", "spelling": "" } ] }, { "key": "cantaloupe", "title": "Cantaloupe", "spelling": "/’kæntəlu:p/", "subs": [ { "key": "a_Cantaloupe", "title": "A cantaloupe", "spelling": "" }, { "key": "cantaloupes", "title": "Cantaloupes", "spelling": "" }, { "key": "a_cantaloupe2", "title": "There is a cantaloupe", "spelling": "" }, { "key": "36_Cantaloupes", "title": "There are 36 cantaloupes", "spelling": "" } ] }, { "key": "chestnut", "title": "Chestnut", "spelling": "/´tʃestnʌt/", "subs": [ { "key": "a_chestnut", "title": "A chestnut", "spelling": "" }, { "key": "Chestnuts", "title": "Chestnuts", "spelling": "" }, { "key": "a_chestnut1", "title": "There is a chestnut", "spelling": "" }, { "key": "37_chestnuts", "title": "There are 37 chestnuts", "spelling": "" } ] }, { "key": "tamarind", "title": "Tamarind", "spelling": "/´tʃestnʌt/", "subs": [ { "key": "a_tamarind", "title": "A tamarind", "spelling": "" }, { "key": "tamarinds", "title": "Tamarinds", "spelling": "" }, { "key": "a_tamarind3", "title": "There is a tamarind", "spelling": "" }, { "key": "38_tamarinds", "title": "There are 38 tamarinds", "spelling": "" } ] } ]
5110912a1412243e2eeef34974db31a19eab4700
4fa161becb8ce7378a709f5992a594764699e268
/src/number_theory/lucas_lehmer.lean
afe1eacbbafedbc39d31e665f32937378a639d3e
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
17,085
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Scott Morrison, Ainsley Pahljina -/ import data.nat.parity import data.zmod.basic import group_theory.order_of_element import ring_theory.fintype /-! # The Lucas-Lehmer test for Mersenne primes. We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`. We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic required to calculate the residue, and enables us to prove ``` example : prime (mersenne 127) := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test) ``` ## TODO - Show reverse implication. - Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`. - Find some bigger primes! ## History This development began as a student project by Ainsley Pahljina, and was then cleaned up for mathlib by Scott Morrison. The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro. -/ /-- The Mersenne numbers, 2^p - 1. -/ def mersenne (p : ℕ) : ℕ := 2^p - 1 lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p := begin dsimp [mersenne], calc 0 < 2^1 - 1 : by norm_num ... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h) end namespace lucas_lehmer open nat /-! We now define three(!) different versions of the recurrence `s (i+1) = (s i)^2 - 2`. These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or in `ℤ` but applying `% (2^p - 1)` at each step. They are each useful at different points in the proof, so we take a moment setting up the lemmas relating them. -/ /-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/ def s : ℕ → ℤ | 0 := 4 | (i+1) := (s i)^2 - 2 /-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/ def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1) | 0 := 4 | (i+1) := (s_zmod i)^2 - 2 /-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/ def s_mod (p : ℕ) : ℕ → ℤ | 0 := 4 % (2^p - 1) | (i+1) := ((s_mod i)^2 - 2) % (2^p - 1) lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 := begin apply ne_of_gt, simp only [gt_iff_lt, sub_pos], exact_mod_cast nat.one_lt_two_pow p w, end lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i := begin cases i; dsimp [s_mod], { trivial, }, { apply int.mod_nonneg, exact mersenne_int_ne_zero p w }, end lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i := by cases i; simp [s_mod] lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 := begin rw ←s_mod_mod, convert int.mod_lt _ _, { refine (abs_of_nonneg _).symm, simp only [sub_nonneg, ge_iff_le], exact_mod_cast nat.one_le_two_pow p, }, { exact mersenne_int_ne_zero p w, }, end lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):= begin induction i with i ih, { dsimp [s, s_zmod], norm_num, }, { push_cast [s, s_zmod, ih] }, end -- These next two don't make good `norm_cast` lemmas. lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) := begin have : 1 ≤ b^p := nat.one_le_pow p b w, push_cast [this], end lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) := int.coe_nat_pow_pred 2 p dec_trivial lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) := by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *] /-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/ def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2) lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) : lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 := begin dsimp [lucas_lehmer_residue], rw s_zmod_eq_s_mod p, split, { -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1` -- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`. intro h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h, apply s_mod_nonneg _ (nat.lt_of_succ_lt w), convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2), push_cast [nat.one_le_two_pow p], refl, }, { intro h, rw h, simp, }, end /-- A Mersenne number `2^p-1` is prime if and only if the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero. -/ @[derive decidable_pred] def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0 /-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/ def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩ instance fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := q.2 /-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/ -- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3), -- obtaining the ring structure for free, -- but that seems to be more trouble than it's worth; -- if it were easy to make the definition, -- cardinality calculations would be somewhat more involved, too. @[derive [add_comm_group, decidable_eq, fintype, inhabited]] def X (q : ℕ+) : Type := (zmod q) × (zmod q) namespace X variable {q : ℕ+} @[ext] lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := begin cases x, cases y, congr; assumption end @[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl @[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl @[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl @[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl instance : has_mul (X q) := { mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) } @[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl @[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl instance : has_one (X q) := { one := ⟨1,0⟩ } @[simp] lemma one_fst : (1 : X q).1 = 1 := rfl @[simp] lemma one_snd : (1 : X q).2 = 0 := rfl @[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl @[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl @[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl @[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, } instance : monoid (X q) := { mul_assoc := λ x y z, by { ext; { dsimp, ring }, }, one := ⟨1,0⟩, one_mul := λ x, by { ext; simp, }, mul_one := λ x, by { ext; simp, }, ..(infer_instance : has_mul (X q)) } lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z := by { ext; { dsimp, ring }, } lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z := by { ext; { dsimp, ring }, } instance : ring (X q) := { left_distrib := left_distrib, right_distrib := right_distrib, ..(infer_instance : add_comm_group (X q)), ..(infer_instance : monoid (X q)) } instance : comm_ring (X q) := { mul_comm := λ x y, by { ext; { dsimp, ring }, }, ..(infer_instance : ring (X q))} instance [fact (1 < (q : ℕ))] : nonzero (X q) := { zero_ne_one := λ h, begin injection h with h1 _, exact zero_ne_one h1, end, } @[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_left_inj], exact n_ih, } end @[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_zero], exact n_ih, } end @[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := by { induction n; simp, } @[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := by { induction n; simp, } @[norm_cast] lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) := by { ext; simp; ring } @[norm_cast] lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) := by { ext; simp, } /-- The cardinality of `X` is `q^2`. -/ lemma X_card : fintype.card (X q) = q^2 := begin dsimp [X], rw [fintype.card_prod, zmod.card q], ring, end /-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/ lemma units_card (w : 1 < q) : fintype.card (units (X q)) < q^2 := begin haveI : fact (1 < (q : ℕ)) := w, convert card_units_lt (X q), rw X_card, end /-- We define `ω = 2 + √3`. -/ def ω : X q := (2, 1) /-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/ def ωb : X q := (2, -1) lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 := begin dsimp [ω, ωb], ext; simp; ring, end lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 := begin dsimp [ω, ωb], ext; simp; ring, end /-- A closed form for the recurrence relation. -/ lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) := begin induction i with i ih, { dsimp [s, ω, ωb], ext; { simp; refl, }, }, { calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl ... = ((s i : X q)^2 - 2) : by push_cast ... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih ... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring ... = (ω^(2^i))^2 + (ωb^(2^i))^2 : by rw [←mul_pow ωb ω, ωb_mul_ω, _root_.one_pow, mul_one, add_sub_cancel] ... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, nat.pow_succ] } end end X open X /-! Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`. -/ /-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/ lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin by_contradiction, simp at a, interval_cases q (p'+2); clear a, { -- If q = 1, we get a contradiction from 2^p = 2 dsimp [q] at h, injection h with h', clear h, simp [mersenne] at h', exact lt_irrefl 2 (calc 2 ≤ p'+2 : nat.le_add_left _ _ ... < 2^(p'+2) : nat.lt_two_pow _ ... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), }, { -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1 dsimp [q] at h, injection h with h', clear h, rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, nat.pow_succ, nat.mul_comm] at h', exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', } end theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : ∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) = k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 := begin dsimp [lucas_lehmer_residue] at h, rw s_zmod_eq_s p' at h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, cases h with k h, use k, replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q dsimp at h, rw closed_form at h, replace h := congr_arg (λ x, ω^2^p' * x) h, dsimp at h, have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp, rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, _root_.one_pow] at h, rw [mul_comm, coe_mul] at h, rw [mul_comm _ (k : X (q (p'+2)))] at h, replace h := eq_sub_of_add_eq h, exact_mod_cast h, end /-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/ theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 := begin ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd], apply nat.min_fac_dvd, end theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+1)) = -1 := begin cases ω_pow_formula p' h with k w, rw [mersenne_coe_X] at w, simpa using w, end theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+2)) = 1 := calc (ω : X (q (p'+2)))^2^(p'+2) = (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←nat.pow_succ, nat.succ_eq_add_one] ... = (-1)^2 : by rw ω_pow_eq_neg_one p' h ... = 1 : by simp /-- `ω` as an element of the group of units. -/ def ω_unit (p : ℕ) : units (X (q p)) := { val := ω, inv := ωb, val_inv := by simp [ω_mul_ωb], inv_val := by simp [ωb_mul_ω], } @[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl /-- The order of `ω` in the unit group is exactly `2^p`. -/ theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : order_of (ω_unit (p'+2)) = 2^(p'+2) := begin apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p { norm_num, }, { intro o, have ω_pow := order_of_dvd_iff_pow_eq_one.1 o, replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) : units (X (q (p'+2))) → X (q (p'+2))) ω_pow, simp at ω_pow, have h : (1 : zmod (q (p'+2))) = -1 := congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)), haveI : fact (2 < (q (p'+2) : ℕ)) := two_lt_q _, apply zmod.neg_one_ne_one h.symm, }, { apply order_of_dvd_iff_pow_eq_one.2, apply units.ext, push_cast, exact ω_pow_eq_one p' h, } end lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 := calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm ... ≤ fintype.card (units (X _)) : order_of_le_card_univ ... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _)) end lucas_lehmer export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue) open lucas_lehmer theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime := begin let p' := p - 2, have z : p = p' + 2 := (nat.sub_eq_iff_eq_add w).mp rfl, have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl), contrapose, intros a t, rw z at a, rw z at t, have h₁ := order_ineq p' t, have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a, have h := lt_of_lt_of_le h₁ h₂, exact not_lt_of_ge (nat.sub_le _ _) h, end -- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better. example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial -- Next we use `norm_num` to calculate each `s p i`. namespace lucas_lehmer open tactic meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ lemma s_mod_succ {p a i b c} (h1 : (2^p - 1 : ℤ) = a) (h2 : s_mod p i = b) (h3 : (b * b - 2) % a = c) : s_mod p (i+1) = c := by { dsimp [s_mod, mersenne], rw [h1, h2, _root_.pow_two, h3] } /-- Given a goal of the form `lucas_lehmer_test p`, attempt to do the calculation using `norm_num` to certify each step. -/ meta def run_test : tactic unit := do `(lucas_lehmer_test %%p) ← target, `[dsimp [lucas_lehmer_test]], `[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num], p ← eval_expr ℕ p, -- Calculate the candidate Mersenne prime let M : ℤ := 2^p - 1, t ← to_expr ``(2^%%p - 1 = %%M), v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M), w ← assertv `w t v, -- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`. -- We could make a better `has_to_pexpr ℤ` instance, or just: `[simp only [int.coe_nat_zero, int.coe_nat_succ, int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w], -- base case t ← to_expr ``(s_mod %%p 0 = 4), v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4), h ← assertv `h t v, -- step case, repeated p-2 times iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })], -- now close the goal h ← get_local `h, exact h end lucas_lehmer /-- We verify that the tactic works to prove `127.prime`. -/ example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test). /-! This implementation works successfully to prove `(2^127 - 1).prime`, and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean]. `(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!), and unfortunately the next Mersenne prime `(2^521 - 1)`, which was the first "computer era" prime, is out of reach with the current implementation. There's still low hanging fruit available to do faster computations based on the formula n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1] and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation. Someone should do this, too! -/ lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] := -- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446 begin conv in k {rw [← nat.mod_add_div k (2^n), add_comm]}, refine nat.modeq.modeq_add _ (by refl), conv {congr, skip, skip, rw ← one_mul (k/2^n)}, refine nat.modeq.modeq_mul _ (by refl), symmetry, rw [nat.modeq.modeq_iff_dvd, int.coe_nat_sub], exact nat.pow_pos dec_trivial _ end -- It's hard to know what the limiting factor for large Mersenne primes would be. -- In the purely computational world, I think it's the squaring operation in `s`.
4f48bf5646c2a18820e9a9a351e0e5da9fe1d92b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/category/basic.lean
60477f4fe162f823340a8d9971e13d5079fba727
[ "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
10,961
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import combinatorics.quiver.basic import tactic.basic /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces (type as `\hom`), * `𝟙 X` for the identity morphism on `X` (type as `\b1`), * `f ≫ g` for composition in the 'arrows' convention (type as `\gg`). Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ /-- The typeclass `category C` describes morphisms associated to objects of type `C : Type u`. The universe levels of the objects and morphisms are independent, and will often need to be specified explicitly, as `category.{v} C`. Typically any concrete example will either be a `small_category`, where `v = u`, which can be introduced as ``` universes u variables {C : Type u} [small_category C] ``` or a `large_category`, where `u = v+1`, which can be introduced as ``` universes u variables {C : Type (u+1)} [large_category C] ``` In order for the library to handle these cases uniformly, we generally work with the unconstrained `category.{v u}`, for which objects live in `Type u` and morphisms live in `Type v`. Because the universe parameter `u` for the objects can be inferred from `C` when we write `category C`, while the universe parameter `v` for the morphisms can not be automatically inferred, through the category theory library we introduce universe parameters with morphism levels listed first, as in ``` universes v u ``` or ``` universes v₁ v₂ u₁ u₂ ``` when multiple independent universes are needed. This has the effect that we can simply write `category.{v} C` (that is, only specifying a single parameter) while `u` will be inferred. Often, however, it's not even necessary to include the `.{v}`. (Although it was in earlier versions of Lean.) If it is omitted a "free" universe will be used. -/ library_note "category_theory universes" universes v u namespace category_theory /-- A preliminary structure on the way to defining a category, containing the data, but none of the axioms. -/ class category_struct (obj : Type u) extends quiver.{v+1} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) See <https://stacks.math.columbia.edu/tag/0014>. -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} initialize_simps_projections category (to_category_struct_to_quiver_hom → hom, to_category_struct_comp → comp, to_category_struct_id → id, -to_category_struct) /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma comp_ite {P : Prop} [decidable P] {X Y Z : C} (f : X ⟶ Y) (g g' : (Y ⟶ Z)) : (f ≫ if P then g else g') = (if P then f ≫ g else f ≫ g') := by { split_ifs; refl } lemma ite_comp {P : Prop} [decidable P] {X Y Z : C} (f f' : (X ⟶ Y)) (g : Y ⟶ Z) : (if P then f else f') ≫ g = (if P then f ≫ g else f' ≫ g) := by { split_ifs; refl } lemma comp_dite {P : Prop} [decidable P] {X Y Z : C} (f : X ⟶ Y) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) : (f ≫ if h : P then g h else g' h) = (if h : P then f ≫ g h else f ≫ g' h) := by { split_ifs; refl } lemma dite_comp {P : Prop} [decidable P] {X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) : (if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) := by { split_ifs; refl } /-- A morphism `f` is an epimorphism if it can be "cancelled" when precomposed: `f ≫ g = f ≫ h` implies `g = h`. See <https://stacks.math.columbia.edu/tag/003B>. -/ class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) /-- A morphism `f` is a monomorphism if it can be "cancelled" when postcomposed: `g ≫ f = h ≫ f` implies `g = h`. See <https://stacks.math.columbia.edu/tag/003B>. -/ class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨λ p, epi.left_cancellation g h p, congr_arg _⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨λ p, mono.right_cancellation g h p, congr_arg _⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { substI h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by substI h; exact epi_of_epi f g end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory /-- Many proofs in the category theory library use the `dsimp, simp` pattern, which typically isn't necessary elsewhere. One would usually hope that the same effect could be achieved simply with `simp`. The essential issue is that composition of morphisms involves dependent types. When you have a chain of morphisms being composed, say `f : X ⟶ Y` and `g : Y ⟶ Z`, then `simp` can operate succesfully on the morphisms (e.g. if `f` is the identity it can strip that off). However if we have an equality of objects, say `Y = Y'`, then `simp` can't operate because it would break the typing of the composition operations. We rarely have interesting equalities of objects (because that would be "evil" --- anything interesting should be expressed as an isomorphism and tracked explicitly), except of course that we have plenty of definitional equalities of objects. `dsimp` can apply these safely, even inside a composition. After `dsimp` has cleared up the object level, `simp` can resume work on the morphism level --- but without the `dsimp` step, because `simp` looks at expressions syntactically, the relevant lemmas might not fire. There's no bound on how many times you potentially could have to switch back and forth, if the `simp` introduced new objects we again need to `dsimp`. In practice this does occur, but only rarely, because `simp` tends to shorten chains of compositions (i.e. not introduce new objects at all). -/ library_note "dsimp, simp"
5a60d1c1952a9e651eb781b00eb861ccbe5223fc
8f67b34bba98f894155dedf263bc8d61c31e89cd
/2ltt/limit.lean
03c7575db4b14fdab01663a7800a1b7c8f039827
[]
no_license
5HT/two-level
3b1523db242cba819681b862fbc8f490d9571a66
370f5a91311db3b463b10a31891370721e2476e2
refs/heads/master
1,648,254,367,420
1,576,269,550,000
1,576,269,550,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,307
lean
import data.equiv algebra.category .facts open natural_transformation sigma.ops open category function equiv notation X `≃ₛ` Y := equiv X Y -- Given categories J and C, we have a canonical functor [const_funct] from the category C to the functor category C^J. -- Here, we do not define this functor in full, but we define the object and morphism part. -- These are called [const_funct_obj] and [const_funct_morph]. -- It would be very easy to complete this to an actual functor, but we do not need this. definition const_funct_obj [reducible] [unfold_full] (J C : Category) (c : C) : J ⇒ C := ⦃ functor, object := λ i, c, morphism := λ i j g, id, respect_id := λ i, eq.refl _, respect_comp := λi j k f g, by rewrite id_left ⦄ definition const_funct_morph [reducible] (J C : Category) (c d : C) (f : c ⟶ d) : (const_funct_obj J C c) ⟹ (const_funct_obj J C d) := mk (λ j, f) begin intros, esimp, rewrite id_left, rewrite id_right end -- Given categories J and C as before, and a functor D : J ⇒ C, we have a category of cones. -- We present it as "fibred" over C. For each object [tip : C] we have a category (here only a type) of cones -- with "tip" [tip]. This is just the type of natural transformations between the functor constantly [tip] and D. definition cone_with_tip [reducible] [unfold_full] {J C : Category} (D : J ⇒ C) (tip : C) := const_funct_obj _ _ tip ⟹ D open functor -- For [f : tip₁ ⟶ tip₂], we have a function between the type of cones with tip tip₂, and the onew with tip tip₁. definition cone_with_tip_functorial [reducible] [unfold_full] {J C : Category} (D : J ⇒ C) (tip₁ tip₂ : C) (f : tip₁ ⟶ tip₂) (c₂ : cone_with_tip D tip₂) : cone_with_tip D tip₁ := natural_transformation.compose c₂ (const_funct_morph J C tip₁ tip₂ f) -- A cone is a tip together with a cone under this tip. definition cone [reducible] [unfold_full] {J C : Category} (D : J ⇒ C) := Σ c, cone_with_tip D c -- morphisms of cones. structure cone_hom {J C : Category} {D : J ⇒ C} (c : cone D ) (c' : cone D) : Type := (chom : c.1 ⟶ c'.1) (commute_triangle : ∀ i, natural_map c.2 i = natural_map c'.2 i ∘ chom) open cone_hom definition cone_hom_eq {J C : Category} {D : J ⇒ C } {c c' : cone D} {f f': cone_hom c c'} (p : chom f = chom f') : f = f' := begin cases f, cases f', cases p, reflexivity end -- Lemma stating that equality between nat. transf. is equality of morphisms (laws trivially equal) -- Danil : It seems that the second goal (laws) is resolved automatically. So, we could use congruence -- tactic directly to compare two natural transformations, but I'll leave this here as an example. definition cone_with_tip_eq {J C : Category} (D : J ⇒ C) (tip : C) (c₁ c₂ : cone_with_tip D tip) : (natural_map c₁ = natural_map c₂) → c₁ = c₂ := begin intros NatMapEq, cases c₁, cases c₂, congruence, esimp at *, apply NatMapEq end definition cone_hom_comp {J C : Category} {D : J ⇒ C } {c c' c'': cone D} (f' : cone_hom c' c'') (f : cone_hom c c') := ⦃ cone_hom, chom := chom f' ∘ chom f, commute_triangle := λ i, by rewrite [assoc, -commute_triangle f', commute_triangle f] ⦄ definition cone_category [instance] [reducible] [unfold_full] {J C : Category} (D : J ⇒ C) : category (cone D) := ⦃ category, hom := λ c c', cone_hom c c', comp := λ a b c f g, cone_hom_comp f g, ID := λi, ⦃ cone_hom, chom := id, commute_triangle := λ i, by rewrite id_right ⦄, assoc := λ a b c p q h g, by cases h; cases q; cases g; apply cone_hom_eq; apply assoc, id_left := λ a b f, cone_hom_eq (id_left (chom f)), id_right := λ a b f, cone_hom_eq (id_right (chom f)) ⦄ definition ConeCat [reducible] {J C : Category} (D : J ⇒ C) : Category := category.Mk (cone_category D) set_option formatter.hide_full_terms false -- CAVEAT: I (Nicolai) have changed this. structure is_terminal [class] {C : Category} (c : C) := (term_hom : ∀ c', hom c' c) (unique_term_hom : ∀ c' (f : hom c' c), f = term_hom c') structure has_terminal_obj [class] (C : Category) := (terminal : C) (is_terminal_obj : is_terminal terminal) open has_terminal_obj definition limit {J C : Category} (D : J ⇒ C) : Type := has_terminal_obj (ConeCat D) definition limit_obj [reducible] [unfold_full] {J C : Category} {D : J ⇒ C} : limit D → objects C | limit_obj (has_terminal_obj.mk c _) := c.1 notation `Nat` `(` F `,` G `)` := F ⟹ G open eq.ops open functor natural_transformation definition nat_transf_sigma_iso {C D : Category} {F G : C ⇒ D} : F ⟹ G ≃ₛ Σ (η : Π(a : C), hom (F a) (G a)), (Π{a b : C} (f : hom a b), G f ∘ η a = η b ∘ F f) := equiv.mk (λ N, match N with |mk η NatSq := ⟨η, NatSq⟩ end) (λ S, match S with | ⟨η, NatSq⟩ := mk η NatSq end) begin unfold function.left_inverse, intro x, cases x, esimp end begin unfold function.right_inverse, unfold function.left_inverse, intro x, cases x, esimp end open eq set_option pp.all true open equiv poly_unit definition poly_unit_arrow_equiv [instance] [simp] (A : Type) : (poly_unit → A) ≃ A := mk (λ f, f star) (λ a, (λ u, a)) (λ f, funext (λ x, by cases x; reflexivity)) (λ u, rfl) definition to_unit [reducible] [unfold_full] {C : Category} {X : C ⇒ Type_category } (f : Π a, poly_unit → X a) y := f y star definition pi_unit_arrow_equiv {C : Category} {X : C ⇒ Type_category } : (Π a, object (const_funct_obj C Type_category poly_unit) a⟶ X a) ≃ Π y, X y := begin esimp, refine equiv.mk to_unit (λ f y x, f y) _ (λx, rfl), unfold function.left_inverse, intros, apply funext, intros, apply funext, intros, cases x_2, reflexivity end definition nat_unit_sigma_equiv [instance] {C : Category.{1 1}} {X : C ⇒ Type_category} : (const_funct_obj C Type_category poly_unit ⟹ X) ≃ₛ Σ (c : Π y, X y), Π (y y' : C) (f : y ⟶ y'), (X f) (c y) = c y' := begin apply equiv.trans (nat_transf_sigma_iso), apply @sigma_congr, intros ff, apply @pi_congr₂, intro, apply @pi_congr₂, intro b, apply @pi_congr₂, intro f', esimp at *, rewrite id_right, refine equiv.mk _ _ _ _, apply pi_unit_arrow_equiv, { intro p, apply happly p }, { intro p, esimp at *, apply funext, intro x, cases x, apply p }, { unfold function.left_inverse, intro, esimp }, { unfold function.right_inverse, unfold function.left_inverse, intro p, esimp }, end definition one_funct [reducible] [unfold_full] {C : Category.{1}} := const_funct_obj C Type_category poly_unit notation `𝟙` := one_funct -- binary product as a limit open bool prod eq.ops -- it's a bit akward to use definition of Category_two from library, -- so we use this definition definition cat_two : category bool := ⦃ category, hom := λ a b, a = b, comp := λ a b c p q, q ⬝ p, ID := λ a, eq.refl _, assoc := λ a b c d h g f, by cases h; cases g; cases f; reflexivity, id_left := λ a b f, by cases f; reflexivity, id_right := λ a b f, by cases f; reflexivity ⦄ definition CatTwo := Mk cat_two definition c2_functor (C : Category) (A B : C) : CatTwo ⇒ C := ⦃ functor, object := bool.rec A B, morphism := (bool.rec (bool.rec (λf, id) (by contradiction)) (bool.rec (by contradiction) (λf, id))), respect_id := bool.rec rfl rfl, respect_comp := λi j k f g, by cases f: cases g: cases k: esimp: rewrite id_left ⦄ definition product {C : Category} (A B : C) (L : limit (c2_functor _ A B)) := limit_obj L -- Type_category limits --set_option pp.universes true open natural_transformation open - [notation] category open functor poly_unit universe variable u definition cone_in_pretype [reducible] {J : Category.{1}} (D : J ⇒ Type_category.{max 1 u}) : cone D := ⟨ cone_with_tip _ poly_unit, -- (const_funct_obj _ _ unit) ⟹ D , natural_transformation.mk (λ a L, natural_map L a star) (λ a b f, funext (λ L, happly (naturality L f) _)) ⟩ open function -- just for rewriting in limit_in_pretype, because projections are left not simplified sometimes definition natural_map_proj {C D : Category} (F G: functor C D) (η :Π a, F a ⟶ G a) (nat : Π⦃a b : C⦄ (f : a ⟶ b), G f ∘ η a = η b ∘ F f) : natural_map (natural_transformation.mk η nat) = η := rfl definition nat_trans_eq {C D : Category} {F G : C ⇒ D} {N M: F ⟹ G} {p : natural_map N = natural_map M} : N = M := begin cases N with [η, NatSq], cases M with [η', NatSq'], unfold natural_map at *, cases p, congruence end definition natural_map_eq {C D : Category} {F G : C ⇒ D} {N M: F ⟹ G} (p : N = M) : natural_map N = natural_map M := begin cases N with [η, NatSq], cases M with [η', NatSq'], unfold natural_map, injection p, assumption end definition limit_in_pretype {J : Category.{1}} (D : J ⇒ Type_category) : limit D := ⦃ has_terminal_obj _, terminal := cone_in_pretype D, is_terminal_obj := ⦃ is_terminal _, term_hom := λ C, mk (λ x, cone_with_tip_functorial D poly_unit C.1 (λ tt, x) C.2) (λ x, rfl), unique_term_hom := begin intros C f, cases f with [chom', ct], apply cone_hom_eq, apply funext, intro x, esimp, -- now: need to show equality of two cones with tip unit: apply cone_with_tip_eq, apply funext, intro j, apply funext, intro t, -- now: have do show an equality in D(j). esimp at *, unfold natural_transformation.compose, repeat rewrite natural_map_proj, unfold cone_in_pretype at *, rewrite natural_map_proj at ct, rewrite ct, -- we have to assert the same goal, but explicitly say that composition is just composition of functions, -- because some definitions related to class instances are not unfolded assert HH : natural_map (chom' x) j t = #function (((λ L, natural_map L j star)∘chom')∘λ tt, x) t, begin esimp, cases t, reflexivity end, exact HH end ⦄ ⦄ -- construction of the product in Pretype (aka Type_category) using the -- limit of the diagramm 𝟚 ⇒ Type_category definition product_in_pretype (A B : Type) := product A B (@limit_in_pretype CatTwo (c2_functor Type_category A B)) open prod.ops -- showing that constructed product is isomophic to the product type definition lim_prod_iso {A B : Type_category} : (product_in_pretype A B) ≃ (A × B) := begin refine equiv.mk _ _ _ _, { intro, cases a with [η, comm_tr], esimp, refine (η ff poly_unit.star, η tt poly_unit.star) }, { intro p, refine natural_transformation.mk _ _, { intro a uu, cases a, apply p.1, apply p.2 }, { intros, cases f, cases b, esimp, apply funext, intro x, reflexivity }}, { intros, refine nat_trans_eq, cases x with [η, comm_tr], rewrite natural_map_proj, rewrite natural_map_proj, apply funext, intros b, apply funext, intro uu, cases uu, cases b: esimp }, { intros, esimp, cases x, esimp } end
3533b0dce84db43679f67cf7009098dcff902489
8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4
/induction_base_k.lean
d98c99d679f27f3077bd8c24a3f272a54e6e3908
[]
no_license
picrin/lean
420f4d08bb3796b911d56d0938e4410e1da0e072
3d10c509c79704aa3a88ebfb24d08b30ce1137cc
refs/heads/master
1,611,166,610,726
1,536,671,438,000
1,536,671,438,000
60,029,899
0
0
null
null
null
null
UTF-8
Lean
false
false
2,926
lean
lemma same_lt {a : nat} (P : a < a) : false := have H : a = a, from eq.refl a, ne_of_lt P H lemma nat.lte_zero (n : nat) : 0 ≤ n := @nat.rec_on (λ k', 0 ≤ k') n (le_refl 0) (λ k (p : 0 ≤ k), have q : 0 ≤ 1, from nat.le_add_left 0 1, show (0 ≤ k + 1), from le_add_of_le_of_nonneg p q ) lemma lt_eq {a b c : nat} (h1 : b = c) (h2 : a < b) : (a < c) := eq.subst h1 h2 lemma biggerIsBigger {a b c : nat} (h1: a < b) : (a < b + c) := have H1: c + b = b + c, from nat.add_comm c b, lt_eq H1 (lt_add_of_nonneg_of_lt (nat.lte_zero c) h1) def nothing_lt_zero : ∀ {k}, ¬ k < 0 := assume k, nat.rec_on k (assume H : 0 < 0, show false, from have 0 = 0, from rfl, same_lt ‹0 < 0›) (assume k (H2 : ¬ k < 0), show k + 1 < 0 → false, from (assume C : k + 1 < 0, or.elim (lt_or_ge k 0) (λ H : k < 0, H2 H) (λ H : 0 ≤ k, or.elim (lt_or_eq_of_le H) (λ H : 0 < k, have k + 1 < k, from lt_trans C H, have k + 1 < k + 1, from biggerIsBigger ‹k + 1 < k ›, same_lt ‹k + 1 < k + 1›) (λ H : 0 = k, have 1 < 0, from @eq.subst _ (λ a, a + 1 < 0) _ _ (eq.symm (‹0 = k›)) C, same_lt (lt.trans ‹1 < 0› zero_lt_one) ) ))) def induction_above_k {motive : ℕ → Prop} (n : ℕ) (k : ℕ) (base_case : motive (k + 1)) (inductive_step : Π (a : ℕ), (k < a) → motive a → motive (a + 1) ) : k < n → motive n := @nat.rec_on (assume m', k < m' → motive m') n ( assume (P : k < 0), have H1 : false, from nothing_lt_zero P, false.elim H1 ) ( assume m (IH : k < m → motive m), have nat_in_two : k < m ∨ k ≥ m, from (lt_or_ge k m), or.elim nat_in_two (assume H : k < m, have motive m, from IH H, show k < m + 1 → motive (m + 1), from assume H1: k < m + 1, show motive (m + 1), from (inductive_step m H ‹motive m›) ) (assume H1 : k ≥ m, show k < m + 1 → motive (m + 1), from assume H : k < m + 1, have m < k, from sorry, have m < m + 1, from nat.lt_trans ‹m < k› H, have H1 : k = m, from sorry, eq.subst H1 base_case ) ) lemma one_lt_twice (m : nat) : 0 < m → 1 < 2 * m := induction_above_k m 0 (show (1 : nat) < 2 * 1, from of_as_true trivial) (λ k (H : 0 < k) (IH : 1 < 2 * k), show 1 < 2 * (k + 1), from have 1 < 2 * k + 2, from biggerIsBigger IH, have 2 * k + 2 = 2 * (k + 1), by simp [mul_add], eq.subst ‹2 * k + 2 = 2 * (k + 1)› ‹1 < 2 * k + 2› )
8fe2f7bdac8388b8a9a1f5986a392ed6d6a6dc04
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/data/repr.lean
3f0c1b3426d1d46cf1e38853d2b501faf415b07a
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
4,437
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.string.basic init.data.bool.basic init.data.subtype.basic import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div open sum subtype nat universes u v /-- Implement `has_repr` if the output string is valid lean code that evaluates back to the original object. If you just want to view the object as a string for a trace message, use `has_to_string`. ### Example: ``` #eval to_string "hello world" -- [Lean] "hello world" #eval repr "hello world" -- [Lean] "\"hello world\"" ``` Reference: https://github.com/leanprover/lean/issues/1664 -/ class has_repr (α : Type u) := (repr : α → string) /-- `repr` is similar to `to_string` except that we should have the property `eval (repr x) = x` for most sensible datatypes. Hence, `repr "hello"` has the value `"\"hello\""` not `"hello"`. -/ def repr {α : Type u} [has_repr α] : α → string := has_repr.repr instance : has_repr bool := ⟨λ b, cond b "tt" "ff"⟩ instance {p : Prop} : has_repr (decidable p) := -- Remark: type class inference will not consider local instance `b` in the new elaborator ⟨λ b : decidable p, @ite p b _ "tt" "ff"⟩ protected def list.repr_aux {α : Type u} [has_repr α] : bool → list α → string | b [] := "" | tt (x::xs) := repr x ++ list.repr_aux ff xs | ff (x::xs) := ", " ++ repr x ++ list.repr_aux ff xs protected def list.repr {α : Type u} [has_repr α] : list α → string | [] := "[]" | (x::xs) := "[" ++ list.repr_aux tt (x::xs) ++ "]" instance {α : Type u} [has_repr α] : has_repr (list α) := ⟨list.repr⟩ instance : has_repr unit := ⟨λ u, "star"⟩ instance {α : Type u} [has_repr α] : has_repr (option α) := ⟨λ o, match o with | none := "none" | (some a) := "(some " ++ repr a ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_repr α] [has_repr β] : has_repr (α ⊕ β) := ⟨λ s, match s with | (inl a) := "(inl " ++ repr a ++ ")" | (inr b) := "(inr " ++ repr b ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_repr α] [has_repr β] : has_repr (α × β) := ⟨λ ⟨a, b⟩, "(" ++ repr a ++ ", " ++ repr b ++ ")"⟩ instance {α : Type u} {β : α → Type v} [has_repr α] [s : ∀ x, has_repr (β x)] : has_repr (sigma β) := ⟨λ ⟨a, b⟩, "⟨" ++ repr a ++ ", " ++ repr b ++ "⟩"⟩ instance {α : Type u} {p : α → Prop} [has_repr α] : has_repr (subtype p) := ⟨λ s, repr (val s)⟩ namespace nat def digit_char (n : ℕ) : char := if n = 0 then '0' else if n = 1 then '1' else if n = 2 then '2' else if n = 3 then '3' else if n = 4 then '4' else if n = 5 then '5' else if n = 6 then '6' else if n = 7 then '7' else if n = 8 then '8' else if n = 9 then '9' else if n = 0xa then 'a' else if n = 0xb then 'b' else if n = 0xc then 'c' else if n = 0xd then 'd' else if n = 0xe then 'e' else if n = 0xf then 'f' else '*' def digit_succ (base : ℕ) : list ℕ → list ℕ | [] := [1] | (d::ds) := if d+1 = base then 0 :: digit_succ ds else (d+1) :: ds def to_digits (base : ℕ) : ℕ → list ℕ | 0 := [0] | (n+1) := digit_succ base (to_digits n) protected def repr (n : ℕ) : string := ((to_digits 10 n).map digit_char).reverse.as_string end nat instance : has_repr nat := ⟨nat.repr⟩ def hex_digit_repr (n : nat) : string := string.singleton $ nat.digit_char n def char_to_hex (c : char) : string := let n := char.to_nat c, d2 := n / 16, d1 := n % 16 in hex_digit_repr d2 ++ hex_digit_repr d1 def char.quote_core (c : char) : string := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if c.to_nat <= 31 ∨ c = '\x7f' then "\\x" ++ char_to_hex c else string.singleton c instance : has_repr char := ⟨λ c, "'" ++ char.quote_core c ++ "'"⟩ def string.quote_aux : list char → string | [] := "" | (x::xs) := char.quote_core x ++ string.quote_aux xs def string.quote (s : string) : string := if s.is_empty = tt then "\"\"" else "\"" ++ string.quote_aux s.to_list ++ "\"" instance : has_repr string := ⟨string.quote⟩ instance (n : nat) : has_repr (fin n) := ⟨λ f, repr (fin.val f)⟩ instance : has_repr unsigned := ⟨λ n, repr (fin.val n)⟩ def char.repr (c : char) : string := repr c
dabc03c7282d1ad08bf9c143f4604b838a03d7c2
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/category/monad/basic.lean
738738929ca1861c0dff2bc54436cc611279fa05
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
1,319
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import tactic.basic /-! # Monad ## Attributes * extensionality * functor_norm * monad_norm ## Implementation Details Set of rewrite rules and automation for monads in general and `reader_t`, `state_t`, `except_t` and `option_t` in particular. The rewrite rules for monads are carefully chosen so that `simp with functor_norm` will not introduce monadic vocabulary in a context where applicatives would do just fine but will handle monadic notation already present in an expression. In a context where monadic reasoning is desired `simp with monad_norm` will translate functor and applicative notation into monad notation and use regular `functor_norm` rules as well. ## Tags functor, applicative, monad, simp -/ run_cmd mk_simp_attr `monad_norm [`functor_norm] attribute [extensionality] reader_t.ext state_t.ext except_t.ext option_t.ext attribute [functor_norm] bind_assoc pure_bind bind_pure attribute [monad_norm] seq_eq_bind_map universes u v @[monad_norm] lemma map_eq_bind_pure_comp (m : Type u → Type v) [monad m] [is_lawful_monad m] {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := by rw bind_pure_comp_eq_map
285e9d4e00f37eb9812cdcf54bddabc310349a6a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/quote_error_pos.lean
e1ef36df03b04444bc16cc3adf994cfe2b7b5e40
[ "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
562
lean
open tactic class add_monoid (α : Type) extends has_zero α, has_add α := (zero_add : ∀ a : α, 0 + a = a) lemma zero_add {α : Type} [add_monoid α] (a : α) : (0 : α) + a = a := add_monoid.zero_add a meta def apply_zero_add (a : pexpr) : tactic unit := to_expr ``(zero_add %%a) >>= exact example (a : nat) : 0 + a = a := begin apply_zero_add ``(tt), -- Error should be here end meta def apply_zero_add2 (a : pexpr) : tactic unit := `[apply zero_add %%a] example (a : nat) : 0 + a = a := begin apply_zero_add2 ``(tt), -- Error should be here end
7065e82841542ffe0a6519aff99f327b0ce964ff
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/mv_polynomial/homogeneous.lean
e3b3e6e53cbd8ef63c6447c40d6e583660780ef9
[ "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
10,970
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Eric Wieser -/ import algebra.direct_sum.internal import algebra.graded_monoid import data.mv_polynomial.variables /-! # Homogeneous polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_submodule σ R n`: the submodule of homogeneous polynomials of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ open_locale big_operators namespace mv_polynomial variables {σ : Type*} {τ : Type*} {R : Type*} {S : Type*} /- TODO * create definition for `∑ i in d.support, d i` * show that `mv_polynomial σ R ≃ₐ[R] ⨁ i, homogeneous_submodule σ R i` -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ ⦃d⦄, coeff d φ ≠ 0 → ∑ i in d.support, d i = n variables (σ R) /-- The submodule of homogeneous `mv_polynomial`s of degree `n`. -/ def homogeneous_submodule [comm_semiring R] (n : ℕ) : submodule R (mv_polynomial σ R) := { carrier := { x | x.is_homogeneous n }, smul_mem' := λ r a ha c hc, begin rw coeff_smul at hc, apply ha, intro h, apply hc, rw h, exact smul_zero r, end, zero_mem' := λ d hd, false.elim (hd $ coeff_zero _), add_mem' := λ a b ha hb c hc, begin rw coeff_add at hc, obtain h|h : coeff c a ≠ 0 ∨ coeff c b ≠ 0, { contrapose! hc, simp only [hc, add_zero] }, { exact ha h }, { exact hb h } end } variables {σ R} @[simp] lemma mem_homogeneous_submodule [comm_semiring R] (n : ℕ) (p : mv_polynomial σ R) : p ∈ homogeneous_submodule σ R n ↔ p.is_homogeneous n := iff.rfl variables (σ R) /-- While equal, the former has a convenient definitional reduction. -/ lemma homogeneous_submodule_eq_finsupp_supported [comm_semiring R] (n : ℕ) : homogeneous_submodule σ R n = finsupp.supported _ R {d | ∑ i in d.support, d i = n} := begin ext, rw [finsupp.mem_supported, set.subset_def], simp only [finsupp.mem_support_iff, finset.mem_coe], refl, end variables {σ R} lemma homogeneous_submodule_mul [comm_semiring R] (m n : ℕ) : homogeneous_submodule σ R m * homogeneous_submodule σ R n ≤ homogeneous_submodule σ R (m + n) := begin rw submodule.mul_le, intros φ hφ ψ hψ c hc, rw [coeff_mul] at hc, obtain ⟨⟨d, e⟩, hde, H⟩ := finset.exists_ne_zero_of_sum_ne_zero hc, have aux : coeff d φ ≠ 0 ∧ coeff e ψ ≠ 0, { contrapose! H, by_cases h : coeff d φ = 0; simp only [*, ne.def, not_false_iff, zero_mul, mul_zero] at * }, specialize hφ aux.1, specialize hψ aux.2, rw finsupp.mem_antidiagonal at hde, classical, have hd' : d.support ⊆ d.support ∪ e.support := finset.subset_union_left _ _, have he' : e.support ⊆ d.support ∪ e.support := finset.subset_union_right _ _, rw [← hde, ← hφ, ← hψ, finset.sum_subset (finsupp.support_add), finset.sum_subset hd', finset.sum_subset he', ← finset.sum_add_distrib], { congr }, all_goals { intros i hi, apply finsupp.not_mem_support_iff.mp }, end section variables [comm_semiring R] variables {σ R} lemma is_homogeneous_monomial (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : ∑ i in d.support, d i = n) : is_homogeneous (monomial d r) n := begin intros c hc, classical, rw coeff_monomial at hc, split_ifs at hc with h, { subst c, exact hn }, { contradiction } end variables (σ) {R} lemma is_homogeneous_of_total_degree_zero {p : mv_polynomial σ R} (hp : p.total_degree = 0) : is_homogeneous p 0 := begin erw [total_degree, finset.sup_eq_bot_iff] at hp, -- we have to do this in two steps to stop simp changing bot to zero simp_rw [mem_support_iff] at hp, exact hp, end lemma is_homogeneous_C (r : R) : is_homogeneous (C r : mv_polynomial σ R) 0 := begin apply is_homogeneous_monomial, simp only [finsupp.zero_apply, finset.sum_const_zero], end variables (σ R) lemma is_homogeneous_zero (n : ℕ) : is_homogeneous (0 : mv_polynomial σ R) n := (homogeneous_submodule σ R n).zero_mem lemma is_homogeneous_one : is_homogeneous (1 : mv_polynomial σ R) 0 := is_homogeneous_C _ _ variables {σ} (R) lemma is_homogeneous_X (i : σ) : is_homogeneous (X i : mv_polynomial σ R) 1 := begin apply is_homogeneous_monomial, simp only [finsupp.support_single_ne_zero _ one_ne_zero, finset.sum_singleton], exact finsupp.single_eq_same end end namespace is_homogeneous variables [comm_semiring R] {φ ψ : mv_polynomial σ R} {m n : ℕ} lemma coeff_eq_zero (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : ∑ i in d.support, d i ≠ n) : coeff d φ = 0 := by { have aux := mt (@hφ d) hd, classical, rwa not_not at aux } lemma inj_right (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := begin obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero hφ, rw [← hm hd, ← hn hd] end lemma add (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := (homogeneous_submodule σ R n).add_mem hφ hψ lemma sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) n) : is_homogeneous (∑ i in s, φ i) n := (homogeneous_submodule σ R n).sum_mem h lemma mul (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := homogeneous_submodule_mul m n $ submodule.mul_mem_mul hφ hψ lemma prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) (n i)) : is_homogeneous (∏ i in s, φ i) (∑ i in s, n i) := begin classical, revert h, apply finset.induction_on s, { intro, simp only [is_homogeneous_one, finset.sum_empty, finset.prod_empty] }, { intros i s his IH h, simp only [his, finset.prod_insert, finset.sum_insert, not_false_iff], apply (h i (finset.mem_insert_self _ _)).mul (IH _), intros j hjs, exact h j (finset.mem_insert_of_mem hjs) } end lemma total_degree (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := begin rw total_degree, apply le_antisymm, { apply finset.sup_le, intros d hd, rw mem_support_iff at hd, rw [finsupp.sum, hφ hd], }, { obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero h, simp only [← hφ hd, finsupp.sum], replace hd := finsupp.mem_support_iff.mpr hd, exact finset.le_sup hd, } end /-- The homogeneous submodules form a graded ring. This instance is used by `direct_sum.comm_semiring` and `direct_sum.algebra`. -/ instance homogeneous_submodule.gcomm_semiring : set_like.graded_monoid (homogeneous_submodule σ R) := { one_mem := is_homogeneous_one σ R, mul_mem := λ i j xi xj, is_homogeneous.mul} open_locale direct_sum noncomputable example : comm_semiring (⨁ i, homogeneous_submodule σ R i) := infer_instance noncomputable example : algebra R (⨁ i, homogeneous_submodule σ R i) := infer_instance end is_homogeneous section noncomputable theory open finset /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component [comm_semiring R] (n : ℕ) : mv_polynomial σ R →ₗ[R] mv_polynomial σ R := (submodule.subtype _).comp $ finsupp.restrict_dom _ _ {d | ∑ i in d.support, d i = n} section homogeneous_component open finset variables [comm_semiring R] (n : ℕ) (φ ψ : mv_polynomial σ R) lemma coeff_homogeneous_component (d : σ →₀ ℕ) : coeff d (homogeneous_component n φ) = if ∑ i in d.support, d i = n then coeff d φ else 0 := by convert finsupp.filter_apply (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ d lemma homogeneous_component_apply : homogeneous_component n φ = ∑ d in φ.support.filter (λ d, ∑ i in d.support, d i = n), monomial d (coeff d φ) := by convert finsupp.filter_eq_sum (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ lemma homogeneous_component_is_homogeneous : (homogeneous_component n φ).is_homogeneous n := begin intros d hd, contrapose! hd, rw [coeff_homogeneous_component, if_neg hd] end @[simp] lemma homogeneous_component_zero : homogeneous_component 0 φ = C (coeff 0 φ) := begin ext1 d, rcases em (d = 0) with (rfl|hd), { classical, simp only [coeff_homogeneous_component, sum_eq_zero_iff, finsupp.zero_apply, if_true, coeff_C, eq_self_iff_true, forall_true_iff] }, { rw [coeff_homogeneous_component, if_neg, coeff_C, if_neg (ne.symm hd)], simp only [finsupp.ext_iff, finsupp.zero_apply] at hd, simp [hd] } end @[simp] lemma homogeneous_component_C_mul (n : ℕ) (r : R) : homogeneous_component n (C r * φ) = C r * homogeneous_component n φ := by simp only [C_mul', linear_map.map_smul] lemma homogeneous_component_eq_zero' (h : ∀ d : σ →₀ ℕ, d ∈ φ.support → ∑ i in d.support, d i ≠ n) : homogeneous_component n φ = 0 := begin rw [homogeneous_component_apply, sum_eq_zero], intros d hd, rw mem_filter at hd, exfalso, exact h _ hd.1 hd.2 end lemma homogeneous_component_eq_zero (h : φ.total_degree < n) : homogeneous_component n φ = 0 := begin apply homogeneous_component_eq_zero', rw [total_degree, finset.sup_lt_iff] at h, { intros d hd, exact ne_of_lt (h d hd), }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma sum_homogeneous_component : ∑ i in range (φ.total_degree + 1), homogeneous_component i φ = φ := begin ext1 d, suffices : φ.total_degree < d.support.sum d → 0 = coeff d φ, by simpa [coeff_sum, coeff_homogeneous_component], exact λ h, (coeff_eq_zero_of_total_degree_lt h).symm end lemma homogeneous_component_homogeneous_polynomial (m n : ℕ) (p : mv_polynomial σ R) (h : p ∈ homogeneous_submodule σ R n) : homogeneous_component m p = if m = n then p else 0 := begin simp only [mem_homogeneous_submodule] at h, ext x, rw coeff_homogeneous_component, by_cases zero_coeff : coeff x p = 0, { split_ifs, all_goals { simp only [zero_coeff, coeff_zero], }, }, { rw h zero_coeff, simp only [show n = m ↔ m = n, from eq_comm], split_ifs with h1, { refl }, { simp only [coeff_zero] } } end end homogeneous_component end end mv_polynomial
56918d2f5a5d0fca4b16ff0f7118070977d69cec
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/vcd_examples.lean
74f421816f55e1cd9f9e44f0c171b3377a25317f
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
13,971
lean
import formal_ml.vcd namespace list variable {α:Type*} lemma nth_lt_of_sorted_of_lt [L:linear_order α] {a b:ℕ} {l:list α} (ha:a < l.length) (hb:b < l.length):list.sorted (<) l → (a < b) → (l.nth_le a ha) < (l.nth_le b hb) := begin intros A1 A2, simp [list.sorted] at A1, rw list.pairwise_iff_nth_le at A1, apply A1, apply A2, end end list namespace finset variable {α:Type*} lemma card_three [L:linear_order α] {T:finset α}:T.card = 3 → (∃ (a b c:α), a < b ∧ b < c ∧ T = {a,b,c}) := begin intros h, have A1:(T.sort L.le).length = 3, { rw finset.length_sort, apply h }, rw ← finset.sort_to_finset L.le T, have A2:(T.sort L.le).sorted (<) := sort_sorted_lt T, cases (T.sort L.le) with a0 S, { apply absurd A1, dec_trivial, }, cases S with a1 S, { apply absurd A1, dec_trivial, }, cases S with a2 S, { apply absurd A1, dec_trivial, }, cases S with a3 S, existsi [a0, a1, a2], split, apply @list.nth_lt_of_sorted_of_lt α L 0 1 [a0, a1, a2], dec_trivial, dec_trivial, apply A2, dec_trivial, split, apply @list.nth_lt_of_sorted_of_lt α L 1 2 [a0, a1, a2], dec_trivial, dec_trivial, apply A2, dec_trivial, simp, apply absurd A1, dec_trivial, end lemma powerset_two {a b:α} [decidable_eq α] {a≠ b}:({a,b}:finset α).powerset = {∅, {a},{b},{a,b}} := begin rw finset.powerset_insert, rw finset.powerset_singleton, simp, ext x, split; intros A1; { simp at A1, simp [A1], cases A1, simp [A1], cases A1, simp [A1], cases A1, simp [A1], simp [A1], }, end lemma forall_subset_card_1 {a:α} {P:finset α → Prop}: P ∅ → P {a} → (∀ S:finset α, S⊆ {a} → P S) := begin intros A1 A2, intros S, intros A3, cases (finset.eq_empty_or_nonempty S) with h_empty h_nonempty, subst S, apply A1, simp [finset.nonempty] at h_nonempty, cases h_nonempty with x x_in_S, have A4:S = {a}, { apply finset.subset.antisymm, apply A3, rw finset.subset_iff, intros y A5, simp at A5, subst y, have A6 := A3 x_in_S, simp at A6, subst x, apply x_in_S, }, subst S, apply A2, end lemma forall_subset_card_2 {a a':α} [decidable_eq α] {P:finset α → Prop}: P ∅ → P {a} → P {a'} → P ({a,a'}:finset α) → (∀ S:finset α, S⊆ {a,a'} → P S) := begin intros A1 A2 A3 A4, intros S A5, cases (decidable.em (a∈ S)) with B1 B1; cases (decidable.em (a'∈S)) with B2 B2, { have A6:S = {a,a'}, { ext x, split;intros A6_1, apply A5, apply A6_1, simp at A6_1, cases A6_1, subst x, apply B1, subst x, apply B2 }, subst S, apply A4 }, { have A6:S = {a}, { ext x, split;intros A6_1, have A6_2 := A5 A6_1, simp at A6_2, cases A6_2, { subst x, simp }, subst x, apply absurd A6_1, apply B2, simp at A6_1, subst x, apply B1 }, subst S, apply A2 }, { have A6:S = {a'}, { ext x, split;intros A6_1, have A6_2 := A5 A6_1, simp at A6_2, cases A6_2, { subst x, apply absurd A6_1, apply B1 }, subst x, simp, simp at A6_1, subst x, apply B2 }, subst S, apply A3 }, { have A6:S = ∅, { ext x, split;intros A6_1, have A6_2 := A5 A6_1, simp at A6_2, cases A6_2, { subst x, apply absurd A6_1, apply B1 }, { subst x, apply absurd A6_1, apply B2 }, simp at A6_1, apply false.elim A6_1 }, subst S, apply A1 }, end end finset namespace set variable {α:Type*} lemma inter_singleton_eq_singleton_iff {a:α} {c:set α}:c ∩ {a} = {a} ↔ a ∈ c := begin have A0:a ∈ {a}, { apply set.mem_singleton, }, split;intros A1, { have A2:c ∩ {a} ⊆ c, { apply set.inter_subset_left }, apply A2, rw A1, apply A0 }, { ext x, split, intros A1, simp at A1, simp, apply A1.right, intros A2, simp at A2, subst x, simp [A1] }, end lemma two_of_three {a b c:α} {h_a_ne_b:a ≠ b} {h_b_ne_c:b≠ c} {T:set α}:T ∩ {a,b,c} = {a,c} ↔ ((a ∈ T) ∧ (b∉ T) ∧ (c∈ T)):= begin have B0:a∈ ({a,b,c}:set α), { simp }, have B1:a∈ ({a,c}:set α), { simp }, have B2:c ∈ ({a,c}:set α), { simp, }, split; intros A1, split, { rw set.subset.antisymm_iff at A1, have C1 := A1.right B1, simp at C1, apply C1 }, split, { intros contra, rw set.subset.antisymm_iff at A1, have C1:b∈ T ∩ {a,b,c}, { simp, apply contra }, have C2 := A1.left C1, simp at C2, cases C2, apply h_a_ne_b, rw C2, apply h_b_ne_c, rw C2 }, { rw set.subset.antisymm_iff at A1, have C1 := A1.right B2, simp at C1, apply C1 }, ext x;split;intros D1, { simp at D1, cases D1 with D1 D2, cases D2 with D2 D3, subst x, simp, cases D3, subst x, apply absurd D1, apply A1.right.left, subst x, simp, }, { simp, simp at D1, cases D1; subst x; simp [A1], }, end end set namespace VC_PAC_problem variable {α:Type*} /- The class of bounded intervals. -/ def intervals (α) [linear_order α]:set (set α) := {C|∃ (a b:α), C = set.Ioo a b ∨ C = set.Ioc a b ∨ C = set.Ico a b ∨ C = set.Icc a b} /- The class of thresholds. -/ def thresholds (α) [linear_order α]:set (set α) := {C|∃ (a:α), C = set.Iio a ∨ C = set.Iic a ∨ C = set.Ioi a ∨ C = set.Ici a} lemma non_singleton_two [L:linear_order α]: (∃ a b:α, a ≠ b) → (∃ c d:α, c < d) := begin intros h, cases h with a h, cases h with b h, cases (lt_trichotomy a b) with h_a_lt_b h_a_eq_b_or_b_lt_a, { existsi [a,b], apply h_a_lt_b }, cases h_a_eq_b_or_b_lt_a with h_a_eq_b h_b_lt_a, { exfalso, apply h, apply h_a_eq_b }, { existsi [b,a], apply h_b_lt_a, }, end lemma one_le_VCD {a:α} {C:set (set α)}:(∃ c∈ C, a∈ c) → (∃ c∈ C, a∉ c) → 1 ≤ VCD C := begin intros h1 h2, let T:finset α := {a}, begin have A1:(T.card:enat) = (1:enat), { simp, }, rw ← A1, apply shatters_card_le_VCD, rw shatters_iff, apply finset.forall_subset_card_1, { cases h2 with c h2, cases h2 with h2 h3, apply exists.intro c, apply exists.intro h2, simp [h3], }, { cases h1 with c h1, cases h1 with h1 h3, apply exists.intro c, apply exists.intro h1, simp, rw set.inter_singleton_eq_singleton_iff, apply h3 }, end end /- Though long and drawn out, this should be straightforward to automate, which will be useful for when there are 16 or more cases. -/ lemma two_le_VCD {a a':α} [decidable_eq α] {C:set (set α)}: (∃ c∈ C, a∈ c ∧ a'∈ c) → (∃ c∈ C, a∉ c∧ a' ∈ c) → (∃ c∈ C, a∈ c∧ a' ∉ c) → (∃ c∈ C, a∉ c∧ a' ∉ c) → 2 ≤ VCD C := begin intros h1 h2 h3 h4, have A1:a ≠ a', { cases h2 with c h2, cases h2 with h2 h3, intros contra, subst a', apply h3.left, apply h3.right }, begin have A2:(({a,a'}:finset α).card:enat) = (2:enat), { simp [A1], refl }, rw ← A2, apply shatters_card_le_VCD, rw shatters_iff, apply finset.forall_subset_card_2, { cases h4 with c h4, cases h4 with h4 h5, existsi [c, h4], simp, ext x,split;intros B1, simp at B1, cases B1 with B1 B2, cases B2; subst x; exfalso, apply h5.left, apply B1, apply h5.right, apply B1, simp at B1, apply false.elim B1 }, { cases h3 with c h3, cases h3 with h3 h5, existsi [c, h3], simp, ext x,split;intros B1, simp at B1, cases B1 with B1 B2, cases B2; subst x, simp, exfalso, apply h5.right, apply B1, simp at B1, subst x, simp, apply h5.left }, { cases h2 with c h2, cases h2 with h2 h5, existsi [c, h2], simp, ext x,split;intros B1, simp at B1, cases B1 with B1 B2, cases B2; subst x,exfalso, apply h5.left, apply B1, simp, simp at B1, subst x, simp, apply h5.right }, { cases h1 with c h1, cases h1 with h1 h5, existsi [c, h1], simp, ext x,split;intros B1, simp at B1, cases B1 with B1 B2, cases B2; subst x; simp, simp at B1, cases B1; subst x; simp [h5], }, end end @[simp] lemma set_Icc_mem_intervals {a b:α}[L:linear_order α]:set.Icc a b ∈ intervals α := begin simp [intervals], existsi [a, b], simp, end @[simp] lemma set_Ioc_mem_intervals {a b:α}[L:linear_order α]:set.Ioc a b ∈ intervals α := begin simp [intervals], existsi [a, b], simp, end @[simp] lemma set_Ico_mem_intervals {a b:α}[L:linear_order α]:set.Ico a b ∈ intervals α := begin simp [intervals], existsi [a, b], simp, end @[simp] lemma set_Ioo_mem_intervals {a b:α}[L:linear_order α]:set.Ioo a b ∈ intervals α := begin simp [intervals], existsi [a, b], simp, end @[simp] lemma set_Iio_mem_thresholds {a:α}[L:linear_order α]:set.Iio a ∈ thresholds α := begin simp [thresholds], existsi a, simp, end @[simp] lemma set_Iic_mem_thresholds {a:α}[L:linear_order α]:set.Iic a ∈ thresholds α := begin simp [thresholds], existsi [a], simp, end @[simp] lemma set_Ioi_mem_thresholds {a:α}[L:linear_order α]:set.Ioi a ∈ thresholds α := begin simp [thresholds], existsi a, simp, end @[simp] lemma set_Ici_mem_thresholds {a:α}[L:linear_order α]:set.Ici a ∈ thresholds α := begin simp [thresholds], existsi [a], simp, end lemma intervals_convex {a b c : α} [linear_order α] (T:set α): (T∈ intervals α) → (a ≤ b) → (b ≤ c) → (a∈ T) → (c ∈ T) → (b∈ T) := begin intros A1 A2 A3 A4 A5, simp [intervals] at A1, cases A1 with d A1, cases A1 with e A1, cases A1, { subst T, simp at A4, simp at A5, simp, split, apply lt_of_lt_of_le A4.left A2, apply lt_of_le_of_lt A3 A5.right }, cases A1, { subst T, simp at A4, simp at A5, simp, split, apply lt_of_lt_of_le A4.left A2, apply le_trans A3 A5.right }, cases A1, { subst T, simp at A4, simp at A5, simp, split, apply le_trans A4.left A2, apply lt_of_le_of_lt A3 A5.right }, { subst T, simp at A4, simp at A5, simp, split, apply le_trans A4.left A2, apply le_trans A3 A5.right }, end lemma thresholds_convex {a b c : α} [linear_order α] (T:set α): (T∈ thresholds α) → (a ≤ b) → (b ≤ c) → (a∈ T) → (c ∈ T) → (b∈ T) := begin intros A1 A2 A3 A4 A5, simp [thresholds] at A1, cases A1 with d A1, --cases A1 with e A1, cases A1, { subst T, simp at A4, simp at A5, simp, apply lt_of_le_of_lt A3 A5 }, cases A1, { subst T, simp at A4, simp at A5, simp, apply le_trans A3 A5 }, cases A1, { subst T, simp at A4, simp at A5, simp, apply lt_of_lt_of_le A4 A2 }, { subst T, simp at A4, simp at A5, simp, apply le_trans A4 A2 }, end lemma enat.coe_two:((2:nat):enat)=2 := begin have A1:(1:enat) + (1:enat) = (2:enat), { refl }, have A2:(1:nat) + (1:nat) = (2:nat), { refl }, rw ← A2, rw ← A1, rw enat.coe_add, rw enat.coe_one, end lemma convex_VCD_le_2 [L:linear_order α] (C:set (set α)):(∀ (a b c:α) (d∈ C), (a ≤ b) → (b ≤ c) → (a ∈ d) → (c∈ d) → (b ∈ d)) → VCD C ≤ 2 := begin intros h_convex, have A1:(2:enat) = (2:nat), { rw enat.coe_two, }, rw A1, apply VCD_le', intros S, intros h_S, have h_shatters := finset.card_three h_S, clear h_S, cases h_shatters with a h_shatters, cases h_shatters with b h_shatters, cases h_shatters with c h_shatters, cases h_shatters with h_a_lt_b h_shatters, cases h_shatters with h_b_lt_c h_shatters, subst S, have h_a_ne_b:a ≠ b, { intros contra, subst b, apply lt_irrefl a h_a_lt_b }, have h_b_ne_c:b ≠ c, { intros contra, subst b, apply lt_irrefl c h_b_lt_c }, intros contra, rw shatters_iff at contra, --cases contra with S' h_subset, have contra2 := contra {a,c} _, cases contra2 with d contra2, cases contra2 with contra2 contra3, simp at contra3, rw set.two_of_three at contra3, apply contra3.right.left, apply h_convex a b c d contra2 (le_of_lt h_a_lt_b) (le_of_lt h_b_lt_c) contra3.left contra3.right.right, apply h_a_ne_b, apply h_b_ne_c, simp [finset.insert_subset], end lemma intervals_VCD_2 [L:linear_order α] [decidable_eq α]: (∃ a b:α, a ≠ b) → VCD (intervals α) = 2 := begin intros h, apply le_antisymm, { /- In one dimension, a hypothesis space with convex hypotheses has a VCD less than or equal to 2. -/ apply convex_VCD_le_2, intros a b c d h_d_mem h_a_le_b h_b_le_c h_a_mem h_b_mem, apply intervals_convex _ h_d_mem h_a_le_b h_b_le_c, apply h_a_mem, apply h_b_mem, }, { have h2 := non_singleton_two h, cases h2 with a h2, cases h2 with b h2, apply @two_le_VCD _ a b, { existsi [set.Icc a b], simp [le_of_lt h2] }, { existsi [set.Ioc a b], simp [le_of_lt h2, h2] }, { existsi [set.Ico a b], simp [le_of_lt h2, h2] }, { existsi [set.Ioo a b], simp [le_of_lt h2, h2] } }, end lemma thresholds_VCD_2 [L:linear_order α] [decidable_eq α]: (∃ a b:α, a ≠ b) → VCD (thresholds α) = 2 := begin intros h, apply le_antisymm, { /- In one dimension, a hypothesis space with convex hypotheses has a VCD less than or equal to 2. -/ apply convex_VCD_le_2, intros a b c d h_d_mem h_a_le_b h_b_le_c h_a_mem h_b_mem, apply thresholds_convex _ h_d_mem h_a_le_b h_b_le_c, apply h_a_mem, apply h_b_mem, }, { have h2 := non_singleton_two h, cases h2 with a h2, cases h2 with b h2, apply @two_le_VCD _ a b, { existsi [set.Iic b], simp [le_of_lt h2] }, { existsi [set.Ioi a], simp [le_of_lt h2, h2] }, { existsi [set.Iic a], simp [le_of_lt h2, h2], }, { existsi [set.Iio a], simp [le_of_lt h2, h2] } }, end def set_of_sets.prod {β:Type*} (Cα:set (set α)) (Cβ:set (set β)):set (set (α × β)) := {p|∃ (A:set α) (B:set β), (A∈ Cα) ∧ (B∈ Cβ) ∧ p = A.prod B} --noncomputable def get_max_of_three_real (a b c:real):real := get_max_of_three real a b c --α end VC_PAC_problem
d005c24d64f3f937c93520cc03ef002866465157
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/direct_limit.lean
9c55402b38d1b1f0f7deb8a6cc6a0d9e6d855828
[ "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
25,563
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.finset.order import algebra.direct_sum.module import ring_theory.free_comm_ring import ring_theory.ideal.operations /-! # Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". ## Main definitions * `directed_system f` * `module.direct_limit G f` * `add_comm_group.direct_limit G f` * `ring.direct_limit G f` -/ universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ι : Type v} variables [dec_ι : decidable_eq ι] [preorder ι] variables (G : ι → Type w) /-- A directed system is a functor from a category (directed poset) to another category. -/ class directed_system (f : Π i j, i ≤ j → G i → G j) : Prop := (map_self [] : ∀ i x h, f i i h x = x) (map_map [] : ∀ {i j k} hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Π i, add_comm_group (G i)] [Π i, module R (G i)] variables {G} (f : Π i j, i ≤ j → G i →ₗ[R] G j) /-- A copy of `directed_system.map_self` specialized to linear maps, as otherwise the `λ i j h, f i j h` can confuse the simplifier. -/ lemma directed_system.map_self [directed_system G (λ i j h, f i j h)] (i x h) : f i i h x = x := directed_system.map_self (λ i j h, f i j h) i x h /-- A copy of `directed_system.map_map` specialized to linear maps, as otherwise the `λ i j h, f i j h` can confuse the simplifier. -/ lemma directed_system.map_map [directed_system G (λ i j h, f i j h)] {i j k} (hij hjk x) : f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x := directed_system.map_map (λ i j h, f i j h) hij hjk x variables (G) include dec_ι /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := direct_sum ι G ⧸ (span R $ { a | ∃ (i j) (H : i ≤ j) x, direct_sum.lof R ι G i x - direct_sum.lof R ι G j (f i j H x) = a }) namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : module R (direct_limit G f) := quotient.module _ instance : inhabited (direct_limit G f) := ⟨0⟩ variables (R ι) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ι G i variables {R ι G f} @[simp] lemma of_f {i j hij x} : (of R ι G f j (f i j hij x)) = of R ι G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] [is_directed ι (≤)] (z : direct_limit G f) : ∃ i x, of R ι G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (λ i x, ⟨i, x, rfl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := exists_ge_ge i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on [nonempty ι] [is_directed ι (≤)] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of R ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Π i, G i →ₗ[R] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[R] P := liftq _ (direct_sum.to_module R ι P g) (span_le.2 $ λ a ⟨i, j, hij, x, hx⟩, by rw [← hx, set_like.mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ι G f} omit Hg lemma lift_of {i} (x) : lift R ι G f g Hg (of R ι G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique [nonempty ι] [is_directed ι (≤)] (F : direct_limit G f →ₗ[R] P) (x) : F x = lift R ι G f (λ i, F.comp $ of R ι G f i) (λ i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl section totalize open_locale classical variables (G f) omit dec_ι /-- `totalize G f i j` is a linear map from `G i` to `G j`, for *every* `i` and `j`. If `i ≤ j`, then it is the map `f i j` that comes with the directed system `G`, and otherwise it is the zero map. -/ noncomputable def totalize (i j) : G i →ₗ[R] G j := if h : i ≤ j then f i j h else 0 variables {G f} lemma totalize_of_le {i j} (h : i ≤ j) : totalize G f i j = f i j h := dif_pos h lemma totalize_of_not_le {i j} (h : ¬(i ≤ j)) : totalize G f i j = 0 := dif_neg h end totalize variables [directed_system G (λ i j h, f i j h)] open_locale classical lemma to_module_totalize_of_le {x : direct_sum ι G} {i j : ι} (hij : i ≤ j) (hx : ∀ k ∈ x.support, k ≤ i) : direct_sum.to_module R ι (G j) (λ k, totalize G f k j) x = f i j hij (direct_sum.to_module R ι (G i) (λ k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ι G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (λ k hk, _), rw [direct_sum.single_eq_lof R k (x k), direct_sum.to_module_lof, direct_sum.to_module_lof, totalize_of_le (hx k hk), totalize_of_le (le_trans (hx k hk) hij), directed_system.map_map], end lemma of.zero_exact_aux [nonempty ι] [is_directed ι (≤)] {x : direct_sum ι G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : ∃ j, (∀ k ∈ x.support, k ≤ j) ∧ direct_sum.to_module R ι (G j) (λ i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ι, span_induction ((quotient.mk_eq_zero _).1 H) (λ x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := exists_ge_ge i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, direct_sum.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_of_le, hik, hjk, directed_system.map_map, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, λ _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (λ x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := exists_ge_ge i j in ⟨k, λ l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (λ hl, le_trans (hi _ hl) hik) (λ hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (λ a x ⟨i, hi, hxi⟩, ⟨i, λ k hk, hi k (direct_sum.support_smul _ _ hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact [is_directed ι (≤)] {i x} (H : of R ι G f i x = 0) : ∃ j hij, f i j hij x = (0 : G j) := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_rfl, by simp [hx0]⟩ else have hij : i ≤ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_of_le hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Π i, add_comm_group (G i)] include dec_ι /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Π i j, i ≤ j → G i →+ G j) : Type* := @module.direct_limit ℤ _ ι _ _ G _ _ (λ i j hij, (f i j hij).to_int_linear_map) namespace direct_limit variables (f : Π i j, i ≤ j → G i →+ G j) omit dec_ι protected lemma directed_system [h : directed_system G (λ i j h, f i j h)] : directed_system G (λ i j hij, (f i j hij).to_int_linear_map) := h include dec_ι local attribute [instance] direct_limit.directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (λ i j hij, (f i j hij).to_int_linear_map) instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →ₗ[ℤ] direct_limit G f := module.direct_limit.of ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) i variables {G f} @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[elab_as_eliminator] protected theorem induction_on [nonempty ι] [is_directed ι (≤)] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact [is_directed ι (≤)] [directed_system G (λ i j h, f i j h)] (i x) (h : of G f i x = 0) : ∃ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Π i, G i →+ P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →ₗ[ℤ] P := module.direct_limit.lift ℤ ι G (λ i j hij, (f i j hij).to_int_linear_map) (λ i, (g i).to_int_linear_map) Hg variables {G f} @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ lemma lift_unique [nonempty ι] [is_directed ι (≤)] (F : direct_limit G f →+ P) (x) : F x = lift G f P (λ i, F.comp (of G f i).to_add_monoid_hom) (λ i j hij x, by simp) x := direct_limit.induction_on x $ λ i x, by simp end direct_limit end add_comm_group namespace ring variables [Π i, comm_ring (G i)] section variables (f : Π i j, i ≤ j → G i → G j) open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := free_comm_ring (Σ i, G i) ⧸ (ideal.span { a | (∃ i j H x, of (⟨j, f i j H x⟩ : Σ i, G i) - of ⟨i, x⟩ = a) ∨ (∃ i, of (⟨i, 1⟩ : Σ i, G i) - 1 = a) ∨ (∃ i x y, of (⟨i, x + y⟩ : Σ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (∃ i x y, of (⟨i, x * y⟩ : Σ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }) namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ instance : inhabited (direct_limit G f) := ⟨0⟩ /-- The canonical map from a component to the direct limit. -/ def of (i) : G i →+* direct_limit G f := ring_hom.mk' { to_fun := λ x, ideal.quotient.mk _ (of (⟨i, x⟩ : Σ i, G i)), map_one' := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul' := λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, } (λ x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩) variables {G f} @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of [nonempty ι] [is_directed ι (≤)] (z : direct_limit G f) : ∃ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ι, quotient.induction_on' z $ λ x, free_abelian_group.induction_on x ⟨ind, 0, (of _ _ ind).map_zero⟩ (λ s, multiset.induction_on s ⟨ind, 1, (of _ _ ind).map_one⟩ (λ a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := exists_ge_ge i j in ⟨k, f i k hik x * f j k hjk y, by rw [(of _ _ _).map_mul, of_f, of_f, hs]; refl⟩)) (λ s ⟨i, x, ih⟩, ⟨i, -x, by rw [(of _ _ _).map_neg, ih]; refl⟩) (λ p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := exists_ge_ge i j in ⟨k, f i k hik x + f j k hjk y, by rw [(of _ _ _).map_add, of_f, of_f, ihx, ihy]; refl⟩) section open_locale classical open polynomial variables {f' : Π i j, i ≤ j → G i →+* G j} theorem polynomial.exists_of [nonempty ι] [is_directed ι (≤)] (q : polynomial (direct_limit G (λ i j h, f' i j h))) : ∃ i p, polynomial.map (of G (λ i j h, f' i j h) i) p = q := polynomial.induction_on q (λ z, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x, by rw [map_C, h]⟩) (λ q₁ q₂ ⟨i₁, p₁, ih₁⟩ ⟨i₂, p₂, ih₂⟩, let ⟨i, h1, h2⟩ := exists_ge_ge i₁ i₂ in ⟨i, p₁.map (f' i₁ i h1) + p₂.map (f' i₂ i h2), by { rw [polynomial.map_add, map_map, map_map, ← ih₁, ← ih₂], congr' 2; ext x; simp_rw [ring_hom.comp_apply, of_f] }⟩) (λ n z ih, let ⟨i, x, h⟩ := exists_of z in ⟨i, C x * X ^ (n + 1), by rw [polynomial.map_mul, map_C, h, polynomial.map_pow, map_X]⟩) end @[elab_as_eliminator] theorem induction_on [nonempty ι] [is_directed ι (≤)] {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx ▸ ih i x section of_zero_exact open_locale classical variables (f' : Π i j, i ≤ j → G i →+* G j) variables [directed_system G (λ i j h, f' i j h)] variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Σ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : ∀ z : Σ i, G i, z ∈ s → z.1 ≤ j) (hk : ∀ z : Σ i, G i, z ∈ t → z.1 ≤ k) (hjk : j ≤ k) (hst : s ⊆ t) : f' j k hjk (lift (λ ix : s, f' ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (λ ix : t, f' ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine subring.in_closure.rec_on hxs _ _ _ _, { rw [(restriction _).map_one, (free_comm_ring.lift _).map_one, (f' j k hjk).map_one, (restriction _).map_one, (free_comm_ring.lift _).map_one] }, { rw [(restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one, (f' j k hjk).map_neg, (f' j k hjk).map_one, (restriction _).map_neg, (restriction _).map_one, (free_comm_ring.lift _).map_neg, (free_comm_ring.lift _).map_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, (f' j k hjk).map_mul, ih, (restriction _).map_mul, (free_comm_ring.lift _).map_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, have := directed_system.map_map (λ i j h, f' i j h), dsimp only at this, rw this, refl }, { rintros x y ihx ihy, rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, (f' j k hjk).map_add, ihx, ihy, (restriction _).map_add, (free_comm_ring.lift _).map_add] } end variables {G f f'} lemma of.zero_exact_aux [nonempty ι] [is_directed ι (≤)] {x : free_comm_ring Σ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G (λ i j h, f' i j h))) : ∃ j s, ∃ H : (∀ k : Σ i, G i, k ∈ s → k.1 ≤ j), is_supported x s ∧ lift (λ ix : s, f' ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f' i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, have := directed_system.map_map (λ i j h, f' i j h), dsimp only at this, rw this, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [(restriction _).map_sub, (free_comm_ring.lift _).map_sub, restriction_of, dif_pos, (restriction _).map_one, lift_of, (free_comm_ring.lift _).map_one], dsimp only, rw [(f' i i _).map_one, sub_self], { exact set.mem_singleton _ } } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_add, lift_of, lift_of, lift_of], dsimp only, rw (f' i i _).map_add, exact sub_self _, exacts [or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [(restriction _).map_sub, (restriction _).map_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, (free_comm_ring.lift _).map_sub, (free_comm_ring.lift _).map_mul, lift_of, lift_of, lift_of], dsimp only, rw (f' i i _).map_mul, exacts [sub_self _, or.inl rfl, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ι, _), refine ⟨ind, ∅, λ _, false.elim, is_supported_zero, _⟩, rw [(restriction _).map_zero, (free_comm_ring.lift _).map_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, obtain ⟨k, hik, hjk⟩ := exists_ge_ge i j, have : ∀ z : Σ i, G i, z ∈ s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s ∪ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [(restriction _).map_add, (free_comm_ring.lift _).map_add, ← of.zero_exact_aux2 G f' hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right s t), ihs, (f' i k hik).map_zero, iht, (f' j k hjk).map_zero, zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, obtain ⟨k, hik, hjk⟩ := exists_ge_ge i j, have : ∀ z : Σ i, G i, z ∈ ↑s ∪ t → z.1 ≤ k, { rintros z (hz | hz), exacts [(hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩).trans hik, (hj z hz).trans hjk] }, refine ⟨k, ↑s ∪ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [(restriction _).map_mul, (free_comm_ring.lift _).map_mul, ← of.zero_exact_aux2 G f' hyt hj this hjk (set.subset_union_right ↑s t), iht, (f' j k hjk).map_zero, mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact [is_directed ι (≤)] {i x} (hix : of G (λ i j h, f' i j h) i x = 0) : ∃ j (hij : i ≤ j), f' i j hij x = 0 := by haveI : nonempty ι := ⟨i⟩; exact let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Σ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact variables (f' : Π i j, i ≤ j → G i →+* G j) /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_injective [is_directed ι (≤)] [directed_system G (λ i j h, f' i j h)] (hf : ∀ i j hij, function.injective (f' i j hij)) (i) : function.injective (of G (λ i j h, f' i j h) i) := begin suffices : ∀ x, of G (λ i j h, f' i j h) i x = 0 → x = 0, { intros x y hxy, rw ← sub_eq_zero, apply this, rw [(of G _ i).map_sub, hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, (f' i j hij).map_zero] end variables (P : Type u₁) [comm_ring P] variables (g : Π i, G i →+* P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f →+* P := ideal.quotient.lift _ (free_comm_ring.lift $ λ (x : Σ i, G i), g x.1 x.2) begin suffices : ideal.span _ ≤ ideal.comap (free_comm_ring.lift (λ (x : Σ (i : ι), G i), g (x.fst) (x.snd))) ⊥, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [set_like.mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [ring_hom.map_sub, lift_of, Hg, ring_hom.map_one, ring_hom.map_add, ring_hom.map_mul, (g i).map_one, (g i).map_add, (g i).map_mul, sub_self] end variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ theorem lift_unique [nonempty ι] [is_directed ι (≤)] (F : direct_limit G f →+* P) (x) : F x = lift G f P (λ i, F.comp $ of G f i) (λ i j hij x, by simp) x := direct_limit.induction_on x $ λ i x, by simp end direct_limit end end ring namespace field variables [nonempty ι] [is_directed ι (≤)] [Π i, field (G i)] variables (f : Π i j, i ≤ j → G i → G j) variables (f' : Π i j, i ≤ j → G i →+* G j) namespace direct_limit instance nontrivial [directed_system G (λ i j h, f' i j h)] : nontrivial (ring.direct_limit G (λ i j h, f' i j h)) := ⟨⟨0, 1, nonempty.elim (by apply_instance) $ assume i : ι, begin change (0 : ring.direct_limit G (λ i j h, f' i j h)) ≠ 1, rw ← (ring.direct_limit.of _ _ _).map_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw (f' i j hij).map_one at hf, exact one_ne_zero hf end ⟩⟩ theorem exists_inv {p : ring.direct_limit G f} : p ≠ 0 → ∃ y, p * y = 1 := ring.direct_limit.induction_on p $ λ i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← (ring.direct_limit.of _ _ _).map_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, (ring.direct_limit.of _ _ _).map_zero]), (ring.direct_limit.of _ _ _).map_one]⟩ section open_locale classical /-- Noncomputable multiplicative inverse in a direct limit of fields. -/ noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p ≠ 0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] /-- Noncomputable field structure on the direct limit of fields. See note [reducible non-instances]. -/ @[reducible] protected noncomputable def field [directed_system G (λ i j h, f' i j h)] : field (ring.direct_limit G (λ i j h, f' i j h)) := { inv := inv G (λ i j h, f' i j h), mul_inv_cancel := λ p, direct_limit.mul_inv_cancel G (λ i j h, f' i j h), inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G (λ i j h, f' i j h), .. direct_limit.nontrivial G (λ i j h, f' i j h) } end end direct_limit end field
f38844b8f5edff783e249412d3118b475f67d61c
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Std/Data/RBTree.lean
292bdae34f4683362812ebcb4a784ba87ddb5d90
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
3,356
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.RBMap namespace Std universes u v w def RBTree (α : Type u) (cmp : α → α → Ordering) : Type u := RBMap α Unit cmp instance : Inhabited (RBTree α p) where default := RBMap.empty @[inline] def mkRBTree (α : Type u) (cmp : α → α → Ordering) : RBTree α cmp := mkRBMap α Unit cmp instance (α : Type u) (cmp : α → α → Ordering) : EmptyCollection (RBTree α cmp) := ⟨mkRBTree α cmp⟩ namespace RBTree variable {α : Type u} {β : Type v} {cmp : α → α → Ordering} @[inline] def empty : RBTree α cmp := RBMap.empty @[inline] def depth (f : Nat → Nat → Nat) (t : RBTree α cmp) : Nat := RBMap.depth f t @[inline] def fold (f : β → α → β) (init : β) (t : RBTree α cmp) : β := RBMap.fold (fun r a _ => f r a) init t @[inline] def revFold (f : β → α → β) (init : β) (t : RBTree α cmp) : β := RBMap.revFold (fun r a _ => f r a) init t @[inline] def foldM {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (t : RBTree α cmp) : m β := RBMap.foldM (fun r a _ => f r a) init t @[inline] def forM {m : Type v → Type w} [Monad m] (f : α → m PUnit) (t : RBTree α cmp) : m PUnit := t.foldM (fun _ a => f a) ⟨⟩ @[inline] protected def forIn [Monad m] (t : RBTree α cmp) (init : σ) (f : α → σ → m (ForInStep σ)) : m σ := t.val.forIn init (fun a _ acc => f a acc) instance : ForIn m (RBTree α cmp) α where forIn := RBTree.forIn @[inline] def isEmpty (t : RBTree α cmp) : Bool := RBMap.isEmpty t @[specialize] def toList (t : RBTree α cmp) : List α := t.revFold (fun as a => a::as) [] @[inline] protected def min (t : RBTree α cmp) : Option α := match RBMap.min t with | some ⟨a, _⟩ => some a | none => none @[inline] protected def max (t : RBTree α cmp) : Option α := match RBMap.max t with | some ⟨a, _⟩ => some a | none => none instance [Repr α] : Repr (RBTree α cmp) where reprPrec t prec := Repr.addAppParen ("Std.rbtreeOf " ++ repr t.toList) prec @[inline] def insert (t : RBTree α cmp) (a : α) : RBTree α cmp := RBMap.insert t a () @[inline] def erase (t : RBTree α cmp) (a : α) : RBTree α cmp := RBMap.erase t a @[specialize] def ofList : List α → RBTree α cmp | [] => mkRBTree .. | x::xs => (ofList xs).insert x @[inline] def find? (t : RBTree α cmp) (a : α) : Option α := match RBMap.findCore? t a with | some ⟨a, _⟩ => some a | none => none @[inline] def contains (t : RBTree α cmp) (a : α) : Bool := (t.find? a).isSome def fromList (l : List α) (cmp : α → α → Ordering) : RBTree α cmp := l.foldl insert (mkRBTree α cmp) @[inline] def all (t : RBTree α cmp) (p : α → Bool) : Bool := RBMap.all t (fun a _ => p a) @[inline] def any (t : RBTree α cmp) (p : α → Bool) : Bool := RBMap.any t (fun a _ => p a) def subset (t₁ t₂ : RBTree α cmp) : Bool := t₁.all fun a => (t₂.find? a).toBool def seteq (t₁ t₂ : RBTree α cmp) : Bool := subset t₁ t₂ && subset t₂ t₁ end RBTree def rbtreeOf {α : Type u} (l : List α) (cmp : α → α → Ordering) : RBTree α cmp := RBTree.fromList l cmp end Std
24473f6f672794d12738503547e63417b9a44a2a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/hom/aut.lean
d0e2bfe47879ff0a2729a6cea4401f20288624a3
[ "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
7,430
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import group_theory.perm.basic /-! # Multiplicative and additive group automorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the automorphism group structure on `add_aut R := add_equiv R R` and `mul_aut R := mul_equiv R R`. ## Implementation notes The definition of multiplication in the automorphism groups agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, but not with `category_theory.comp`. This file is kept separate from `data/equiv/mul_add` so that `group_theory.perm` is free to use equivalences (and other files that use them) before the group structure is defined. ## Tags mul_aut, add_aut -/ variables {A : Type*} {M : Type*} {G : Type*} /-- The group of multiplicative automorphisms. -/ @[reducible, to_additive "The group of additive automorphisms."] def mul_aut (M : Type*) [has_mul M] := M ≃* M namespace mul_aut variables (M) [has_mul M] /-- The group operation on multiplicative automorphisms is defined by `λ g h, mul_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (mul_aut M) := by refine_struct { mul := λ g h, mul_equiv.trans h g, one := mul_equiv.refl M, inv := mul_equiv.symm, div := _, npow := @npow_rec _ ⟨mul_equiv.refl M⟩ ⟨λ g h, mul_equiv.trans h g⟩, zpow := @zpow_rec _ ⟨mul_equiv.refl M⟩ ⟨λ g h, mul_equiv.trans h g⟩ ⟨mul_equiv.symm⟩ }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (mul_aut M) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : mul_aut M) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : mul_aut M) = id := rfl lemma mul_def (e₁ e₂ : mul_aut M) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : mul_aut M) = mul_equiv.refl _ := rfl lemma inv_def (e₁ : mul_aut M) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : mul_aut M) (m : M) : (e₁ * e₂) m = e₁ (e₂ m) := rfl @[simp] lemma one_apply (m : M) : (1 : mul_aut M) m = m := rfl @[simp] lemma apply_inv_self (e : mul_aut M) (m : M) : e (e⁻¹ m) = m := mul_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : mul_aut M) (m : M) : e⁻¹ (e m) = m := mul_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : mul_aut M →* equiv.perm M := by refine_struct { to_fun := mul_equiv.to_equiv }; intros; refl /-- The tautological action by `mul_aut M` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_mul_distrib_mul_action {M} [monoid M] : mul_distrib_mul_action (mul_aut M) M := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl, smul_one := mul_equiv.map_one, smul_mul := mul_equiv.map_mul } @[simp] protected lemma smul_def {M} [monoid M] (f : mul_aut M) (a : M) : f • a = f a := rfl /-- `mul_aut.apply_mul_action` is faithful. -/ instance apply_has_faithful_smul {M} [monoid M] : has_faithful_smul (mul_aut M) M := ⟨λ _ _, mul_equiv.ext⟩ /-- Group conjugation, `mul_aut.conj g h = g * h * g⁻¹`, as a monoid homomorphism mapping multiplication in `G` into multiplication in the automorphism group `mul_aut G`. See also the type `conj_act G` for any group `G`, which has a `mul_action (conj_act G) G` instance where `conj G` acts on `G` by conjugation. -/ def conj [group G] : G →* mul_aut G := { to_fun := λ g, { to_fun := λ h, g * h * g⁻¹, inv_fun := λ h, g⁻¹ * h * g, left_inv := λ _, by simp [mul_assoc], right_inv := λ _, by simp [mul_assoc], map_mul' := by simp [mul_assoc] }, map_mul' := λ _ _, by ext; simp [mul_assoc], map_one' := by ext; simp [mul_assoc] } @[simp] lemma conj_apply [group G] (g h : G) : conj g h = g * h * g⁻¹ := rfl @[simp] lemma conj_symm_apply [group G] (g h : G) : (conj g).symm h = g⁻¹ * h * g := rfl @[simp] lemma conj_inv_apply [group G] (g h : G) : (conj g)⁻¹ h = g⁻¹ * h * g := rfl end mul_aut namespace add_aut variables (A) [has_add A] /-- The group operation on additive automorphisms is defined by `λ g h, add_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance group : group (add_aut A) := by refine_struct { mul := λ g h, add_equiv.trans h g, one := add_equiv.refl A, inv := add_equiv.symm, div := _, npow := @npow_rec _ ⟨add_equiv.refl A⟩ ⟨λ g h, add_equiv.trans h g⟩, zpow := @zpow_rec _ ⟨add_equiv.refl A⟩ ⟨λ g h, add_equiv.trans h g⟩ ⟨add_equiv.symm⟩ }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (add_aut A) := ⟨1⟩ @[simp] lemma coe_mul (e₁ e₂ : add_aut A) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl @[simp] lemma coe_one : ⇑(1 : add_aut A) = id := rfl lemma mul_def (e₁ e₂ : add_aut A) : e₁ * e₂ = e₂.trans e₁ := rfl lemma one_def : (1 : add_aut A) = add_equiv.refl _ := rfl lemma inv_def (e₁ : add_aut A) : e₁⁻¹ = e₁.symm := rfl @[simp] lemma mul_apply (e₁ e₂ : add_aut A) (a : A) : (e₁ * e₂) a = e₁ (e₂ a) := rfl @[simp] lemma one_apply (a : A) : (1 : add_aut A) a = a := rfl @[simp] lemma apply_inv_self (e : add_aut A) (a : A) : e⁻¹ (e a) = a := add_equiv.apply_symm_apply _ _ @[simp] lemma inv_apply_self (e : add_aut A) (a : A) : e (e⁻¹ a) = a := add_equiv.apply_symm_apply _ _ /-- Monoid hom from the group of multiplicative automorphisms to the group of permutations. -/ def to_perm : add_aut A →* equiv.perm A := by refine_struct { to_fun := add_equiv.to_equiv }; intros; refl /-- The tautological action by `add_aut A` on `A`. This generalizes `function.End.apply_mul_action`. -/ instance apply_distrib_mul_action {A} [add_monoid A] : distrib_mul_action (add_aut A) A := { smul := ($), smul_zero := add_equiv.map_zero, smul_add := add_equiv.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def {A} [add_monoid A] (f : add_aut A) (a : A) : f • a = f a := rfl /-- `add_aut.apply_distrib_mul_action` is faithful. -/ instance apply_has_faithful_smul {A} [add_monoid A] : has_faithful_smul (add_aut A) A := ⟨λ _ _, add_equiv.ext⟩ /-- Additive group conjugation, `add_aut.conj g h = g + h - g`, as an additive monoid homomorphism mapping addition in `G` into multiplication in the automorphism group `add_aut G` (written additively in order to define the map). -/ def conj [add_group G] : G →+ additive (add_aut G) := { to_fun := λ g, @additive.of_mul (add_aut G) { to_fun := λ h, g + h + -g, -- this definition is chosen to match `mul_aut.conj` inv_fun := λ h, -g + h + g, left_inv := λ _, by simp [add_assoc], right_inv := λ _, by simp [add_assoc], map_add' := by simp [add_assoc] }, map_add' := λ _ _, by apply additive.to_mul.injective; ext; simp [add_assoc], map_zero' := by ext; simpa } @[simp] lemma conj_apply [add_group G] (g h : G) : conj g h = g + h + -g := rfl @[simp] lemma conj_symm_apply [add_group G] (g h : G) : (conj g).symm h = -g + h + g := rfl @[simp] lemma conj_inv_apply [add_group G] (g h : G) : (-(conj g)) h = -g + h + g := rfl end add_aut
949008c20d9d9b9a3a16a1d80de4107b342f1723
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Data/Hashable.lean
3f81ec033e83277d76ff79182551fdd4bf9d37b5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,213
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.UInt import Init.Data.String universe u instance : Hashable Nat where hash n := UInt64.ofNat n instance [Hashable α] [Hashable β] : Hashable (α × β) where hash | (a, b) => mixHash (hash a) (hash b) instance : Hashable Bool where hash | true => 11 | false => 13 instance [Hashable α] : Hashable (Option α) where hash | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (List α) where hash as := as.foldl (fun r a => mixHash r (hash a)) 7 instance : Hashable UInt8 where hash n := n.toUInt64 instance : Hashable UInt16 where hash n := n.toUInt64 instance : Hashable UInt32 where hash n := n.toUInt64 instance : Hashable UInt64 where hash n := n instance : Hashable USize where hash n := n.toUInt64 instance : Hashable (Fin n) where hash v := v.val.toUInt64 instance : Hashable Int where hash | Int.ofNat n => UInt64.ofNat (2 * n) | Int.negSucc n => UInt64.ofNat (2 * n + 1) instance (P : Prop) : Hashable P where hash p := 0
aebdaa8fa02a3c6a3eb28d31c9ea53a9b5193e8a
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/nat/unique_factorization.lean
8a479c274eb2ca52c103eee7c78d7e483451078c
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,856
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.nat.associated import ring_theory.unique_factorization_domain /-# # Unique factorization in `ℕ` This file defines the `unique_factorization_monoid` structure on the natural numbers. ## Main results * `nat.irreducible_iff_prime`: a non-unit natural number is only divisible by `1` iff it is prime * `nat.unique_factorization_monoid`: the natural numbers have unique factorization into irreducibles * `nat.factors_eq`: the multiset of elements of `nat.factors` is equal to the factors given by the `unique_factorization_monoid` instance ## Tags prime factorization, prime factors, unique factorization, unique factors -/ namespace nat instance : wf_dvd_monoid ℕ := ⟨begin apply rel_hom.well_founded _ (with_top.well_founded_lt nat.lt_wf), refine ⟨λ x, if x = 0 then ⊤ else x, _⟩, intros a b h, cases a, { exfalso, revert h, simp [dvd_not_unit] }, cases b, {simp [succ_ne_zero, with_top.coe_lt_top]}, cases dvd_and_not_dvd_iff.2 h with h1 h2, simp only [succ_ne_zero, with_top.coe_lt_coe, if_false], apply lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h1) (λ con, h2 _), rw con, end⟩ instance : unique_factorization_monoid ℕ := ⟨λ _, nat.irreducible_iff_prime⟩ end nat open unique_factorization_monoid theorem nat.factors_eq {n : ℕ} : factors n = n.factors := begin cases n, {refl}, rw [← multiset.rel_eq, ← associated_eq_eq], apply factors_unique (irreducible_of_factor) _, { rw [multiset.coe_prod, nat.prod_factors (nat.succ_pos _)], apply factors_prod (nat.succ_ne_zero _) }, { apply_instance }, { intros x hx, rw [nat.irreducible_iff_prime, ← nat.prime_iff], apply nat.mem_factors hx, } end
ec5df4cc7e8f369d4c985161aa1b402a68ad5431
137c667471a40116a7afd7261f030b30180468c2
/src/measure_theory/interval_integral.lean
dd17dfc3f06589e54579d5450b78690063804e3e
[ "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
104,231
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import measure_theory.set_integral import measure_theory.lebesgue_measure import analysis.calculus.fderiv_measurable import analysis.calculus.extend_deriv /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and many versions of the first part of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that it states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ### FTC-2 and corollaries We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming scheme as for the versions of FTC-1. They include: * `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` - most general version, for functions with a right derivative * `interval_integral.integral_eq_sub_of_has_deriv_at'` - version for functions with a derivative on an open set * `interval_integral.integral_deriv_eq_sub'` - version that is easiest to use when computing the integral of a specific function We then derive additional integration techniques from FTC-2: * `interval_integral.integral_mul_deriv_eq_deriv_mul` - integration by parts * `interval_integral.integral_comp_mul_deriv'` - integration by substitution Many applications of these theorems can be found in the file `analysis.special_functions.integrals`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Ioo` and `Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ## Tags integral, fundamental theorem of calculus -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter open_locale classical topological_space filter ennreal big_operators variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α] [measurable_space E] [normed_group E] open_locale interval /-! ### Almost everywhere on an interval -/ section variables {μ : measure α} {a b : α} {P : α → Prop} lemma ae_interval_oc_iff : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂μ, x ∈ Ioc a b → P x) ∧ (∀ᵐ x ∂μ, x ∈ Ioc b a → P x) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } lemma ae_measurable_interval_oc_iff {μ : measure α} {β : Type*} [measurable_space β] {f : α → β} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } variables [topological_space α] [opens_measurable_space α] [order_closed_topology α] lemma ae_interval_oc_iff' : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂ (μ.restrict $ Ioc a b), P x) ∧ (∀ᵐ x ∂ (μ.restrict $ Ioc b a), P x) := begin simp_rw ae_interval_oc_iff, rw [ae_restrict_eq, eventually_inf_principal, ae_restrict_eq, eventually_inf_principal] ; exact measurable_set_Ioc end end /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : α → E) (μ : measure α) (a b : α) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ /-- A function is interval integrable with respect to a given measure `μ` on `interval a b` if and only if it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. This is an equivalent defintion of `interval_integrable`. -/ lemma interval_integrable_iff {f : α → E} {a b : α} {μ : measure α} : interval_integrable f μ a b ↔ integrable_on f (Ioc (min a b) (max a b)) μ := by cases le_total a b; simp [h, interval_integrable] /-- If a function is interval integrable with respect to a given measure `μ` on `interval a b` then it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. -/ lemma interval_integrable.def {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) : integrable_on f (Ioc (min a b) (max a b)) μ := interval_integrable_iff.mp h /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `interval a b`. -/ lemma measure_theory.integrable.interval_integrable {f : α → E} {a b : α} {μ : measure α} (hf : integrable f μ) : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ namespace interval_integrable section variables {f : α → E} {a b c d : α} {μ ν : measure α} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma trans_iterate {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a 0) (a n) := begin induction n with n hn, { simp }, { exact (hn (λ k hk, hint k (hk.trans n.lt_succ_self))).trans (hint n n.lt_succ_self) } end lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ lemma norm [opens_measurable_space E] (h : interval_integrable f μ a b) : interval_integrable (λ x, ∥f x∥) μ a b := ⟨h.1.norm, h.2.norm⟩ lemma abs {f : α → ℝ} (h : interval_integrable f μ a b) : interval_integrable (λ x, abs (f x)) μ a b := h.norm lemma mono (hf : interval_integrable f ν a b) (h1 : interval c d ⊆ interval a b) (h2 : μ ≤ ν) : interval_integrable f μ c d := let ⟨h1₁, h1₂⟩ := interval_subset_interval_iff_le.mp h1 in interval_integrable_iff.mpr $ hf.def.mono (Ioc_subset_Ioc h1₁ h1₂) h2 lemma mono_set (hf : interval_integrable f μ a b) (h : interval c d ⊆ interval a b) : interval_integrable f μ c d := hf.mono h rfl.le lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) : interval_integrable f μ a b := hf.mono rfl.subset h lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ioc (min c d) (max c d) ≤ᵐ[μ] Ioc (min a b) (max a b)) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono_set_ae h protected lemma ae_measurable (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc a b)):= h.1.ae_measurable protected lemma ae_measurable' (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc b a)):= h.2.ae_measurable end variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ @[simp] lemma add [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ end interval_integrable section variables {μ : measure ℝ} [locally_finite_measure μ] lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := begin split, all_goals { refine measure_theory.integrable_on.mono_set _ Ioc_subset_Icc_self, refine continuous_on.integrable_on_compact is_compact_Icc (hu.mono _) }, exacts [Icc_subset_interval, Icc_subset_interval'] end lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : α → E) (a b : α) (μ : measure α) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section basic variables {a b : α} {f g : α → E} {μ : measure α} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma integral_cases (f : α → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ioc (min a b) (max a b), f x ∂μ, -∫ x in Ioc (min a b) (max a b), f x ∂μ} : set E) := (le_total a b).imp (λ h, by simp [h, integral_of_le]) (λ h, by simp [h, integral_of_ge]) lemma integral_undef (h : ¬ interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b with hab hab; simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero]; refine integral_undef (not_imp_not.mpr integrable.integrable_on' _); simpa [hab] using not_and_distrib.mp h lemma integral_non_ae_measurable (hf : ¬ ae_measurable f (μ.restrict (Ioc (min a b) (max a b)))) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b; simpa [integral_of_le, integral_of_ge, h] using integral_non_ae_measurable hf lemma integral_non_ae_measurable_of_le (h : a ≤ b) (hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_ae_measurable $ by simpa [h] using hf lemma norm_integral_eq_norm_integral_Ioc : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ := (integral_cases f a b).elim (congr_arg _) (λ h, (congr_arg _ h).trans (norm_neg _)) lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc ... ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ abs (∫ x in a..b, ∥f x∥ ∂μ) := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ioc (min a b) (max a b) → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ioc (min a b) (max a b), ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h @[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by { simp only [interval_integral, integral_add hf.1 hg.1, integral_add hf.2 hg.2], abel } @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } @[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) @[simp] lemma integral_smul (r : ℝ) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] @[simp] lemma integral_const {a b : ℝ} (c : E) : ∫ x in a..b, c = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ℝ≥0∞) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] end basic section comp variables {a b c d : ℝ} (f : ℝ → E) @[simp] lemma integral_comp_mul_right (hc : c ≠ 0) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : closed_embedding (λ x, x * c) := (homeomorph.mul_right' c hc).closed_embedding, conv_rhs { rw [← real.smul_map_volume_mul_right hc] }, simp_rw [integral_smul_measure, interval_integral, set_integral_map_of_closed_embedding measurable_set_Ioc A, ennreal.to_real_of_real (abs_nonneg c)], cases lt_or_gt_of_ne hc, { simp [h, mul_div_cancel, hc, abs_of_neg, restrict_congr_set Ico_ae_eq_Ioc] }, { simp [(show 0 < c, from h), mul_div_cancel, hc, abs_of_pos] } end @[simp] lemma smul_integral_comp_mul_right (c) : c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_left (hc : c ≠ 0) : ∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] lemma smul_integral_comp_mul_left (c) : c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div (hc : c ≠ 0) : ∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x := by simpa only [inv_inv'] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] lemma inv_smul_integral_comp_div (c) : c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_right (d) : ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x := have A : closed_embedding (λ x, x + d) := (homeomorph.add_right d).closed_embedding, calc ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume) : by simp [interval_integral, set_integral_map_of_closed_embedding _ A] ... = ∫ x in a+d..b+d, f x : by rw [real.map_volume_add_right] @[simp] lemma integral_comp_add_left (d) : ∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x := by simpa only [add_comm] using integral_comp_add_right f d @[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_mul_add (c d) : c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_add_mul (c d) : c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_add (c d) : c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_add_div (c d) : c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] lemma smul_integral_comp_mul_sub (c d) : c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x := begin simp only [sub_eq_add_neg, neg_mul_eq_neg_mul], rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm], simp only [inv_neg, smul_neg, neg_neg, neg_smul], end @[simp] lemma smul_integral_comp_sub_mul (c d) : c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_sub (c d) : c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_sub_div (c d) : c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_right (d) : ∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] lemma integral_comp_sub_left (d) : ∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end comp /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ section order_closed_topology variables [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b c d : α} {f g : α → E} {μ : measure α} lemma integral_Icc_eq_integral_Ioc {f : α → E} {a b : α} (ha : μ {a} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := begin cases le_or_lt a b with hab hab, { have : μ.restrict (Icc a b) = μ.restrict (Ioc a b), { rw [← Ioc_union_left hab, measure_theory.measure.restrict_union _ measurable_set_Ioc (measurable_set_singleton a)], { simp [measure_theory.measure.restrict_zero_set ha] }, { simp } }, rw this }, { simp [hab, hab.le] } end /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : α} (h : eq_on f g (interval a b)) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge] using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self) lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, ← add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma sum_integral_adjacent_intervals {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := begin induction n with n hn, { simp }, { rw [finset.sum_range_succ, hn (λ k hk, hint k (hk.trans n.lt_succ_self))], exact integral_add_adjacent_intervals (interval_integrable.trans_iterate $ λ k hk, hint k (hk.trans n.lt_succ_self)) (hint n n.lt_succ_self) } end lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc (le_refl _)), Iic_union_Ioc_eq_Iic hab], exacts [measurable_set_Iic, measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : function.support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, function.support_eq_empty_iff] at h, simp [h] } end lemma integral_congr_ae' {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h, set_integral_congr_ae (measurable_set_Ioc) h'] lemma integral_congr_ae {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := integral_congr_ae' (ae_interval_oc_iff.mp h).1 (ae_interval_oc_iff.mp h).2 lemma integral_zero_ae {f : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ (x : α) in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h ... = 0 : integral_zero lemma integral_indicator {a₁ a₂ a₃ : α} (h : a₂ ∈ Icc a₁ a₃) {f : α → E} : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ := begin have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2, rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, measure.restrict_restrict, this], exact measurable_set_Iic, all_goals { apply measurable_set_Iic }, end end order_closed_topology section continuity_wrt_parameter open topological_space variables {X : Type*} [topological_space X] [first_countable_topology X] variables {μ : measure α} /-- Continuity of interval integral with respect to a parameter, at a point within a set. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)` is continuous at `x₀` within `s` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_within_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} {s : set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (hF_meas₀ : ae_measurable (F x₀) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_within_at (λ x, F x t) s x₀) : continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ := begin have gcs := is_countably_generated_nhds_within x₀ s, cases bound_integrable, cases le_or_lt a b with hab hab; [{ rw interval_oc_of_le hab at *, simp_rw interval_integral.integral_of_le hab }, { rw interval_oc_of_lt hab at *, simp_rw interval_integral.integral_of_ge hab.le, refine tendsto.neg _ }]; apply tendsto_integral_filter_of_dominated_convergence bound gcs hF_meas hF_meas₀ h_bound, exacts [bound_integrable_left, h_cont, bound_integrable_right, h_cont] end /-- Continuity of interval integral with respect to a parameter at a point. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)` is continuous at `x₀` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_at (λ x, F x t) x₀) : continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ := begin rw ← continuous_within_at_univ, apply continuous_within_at_of_dominated_interval ; try { rw nhds_within_univ}, exacts [hF_meas, (mem_of_mem_nhds hF_meas : _), h_bound, bound_integrable, h_cont.mono (λ a, (continuous_within_at_univ (λ x, F x a) x₀).mpr)] end /-- Continuity of interval integral with respect to a parameter. Given `F : X → α → E`, assume each `F x` is ae-measurable on `[a, b]`, and assume it is bounded by a function integrable on `[a, b]` independent of `x`. If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_of_dominated_interval {F : X → α → E} {bound : α → ℝ} {a b : α} (hF_meas : ∀ x, ae_measurable (F x) $ μ.restrict $ Ι a b) (h_bound : ∀ x, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous (λ x, F x t)) : continuous (λ x, ∫ t in a..b, F x t ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval (eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $ λ _, continuous.continuous_at) end continuity_wrt_parameter section continuous_primitive open topological_space variables [topological_space α] [order_topology α] [opens_measurable_space α] [first_countable_topology α] {a b : α} {μ : measure α} lemma continuous_within_at_primitive {f : α → E} {a b₀ b₁ b₂ : α} (hb₀ : μ {b₀} = 0) (h_int : interval_integrable f μ (min a b₁) (max a b₂)) : continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ := begin by_cases h₀ : b₀ ∈ Icc b₁ b₂, { have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2, have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂, have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x, { rintros x ⟨h₁, h₂⟩, apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_right a b₁), h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ }, { exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁, le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } }, have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ, { rintros b ⟨h₁, h₂⟩, rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩), apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ }, { exact ⟨min_le_of_left_le (min_le_right _ _), le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } }, apply continuous_within_at.congr _ this (this _ h₀), clear this, refine continuous_within_at_const.add _, have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀] λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ, { apply eventually_eq_of_mem self_mem_nhds_within, exact λ b b_in, (integral_indicator b_in).symm }, apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm, have : interval_integrable (λ x, ∥f x∥) μ b₁ b₂, from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂), refine continuous_within_at_of_dominated_interval _ _ _ this _ ; clear this, { apply eventually.mono (self_mem_nhds_within), intros x hx, erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' hx).1.ae_measurable }, { exact le_max_of_le_right hx.2 }, exacts [measurable_set_Iic, measurable_set_Iic] }, { erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' h₀).1.ae_measurable }, { exact le_max_of_le_right h₀.2 }, exact measurable_set_Iic, exact measurable_set_Iic }, { refine eventually_of_forall (λ (x : α), eventually_of_forall (λ (t : α), _)), dsimp [indicator], split_ifs ; simp }, { have : ∀ᵐ t ∂μ.restrict (Ι b₁ b₂), t < b₀ ∨ b₀ < t, { apply ae_restrict_of_ae, apply eventually.mono (compl_mem_ae_iff.mpr hb₀), intros x hx, exact ne.lt_or_lt hx }, apply this.mono, rintros x₀ (hx₀ | hx₀), { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = f x₀, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Ioi_mem_nhds hx₀), intros x hx, simp [hx.le] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀.le] }, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = 0, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Iio_mem_nhds hx₀), intros x hx, simp [hx] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀] } } }, { apply continuous_within_at_of_not_mem_closure, rwa [closure_Icc] } end lemma continuous_on_primitive {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) := begin by_cases h : a ≤ b, { have : ∀ x ∈ Icc a b, ∫ (t : α) in Ioc a x, f t ∂μ = ∫ (t : α) in a..x, f t ∂μ, { intros x x_in, simp_rw [← interval_oc_of_le h, integral_of_le x_in.1] }, rw continuous_on_congr this, intros x₀ hx₀, refine continuous_within_at_primitive (measure_singleton x₀) _, rw interval_integrable_iff, simp only [h, max_eq_right, min_eq_left], exact h_int.mono Ioc_subset_Icc_self le_rfl }, { rw Icc_eq_empty h, exact continuous_on_empty _ }, end lemma continuous_on_primitive' {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) := begin rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ, by { ext x, exact integral_Icc_eq_integral_Ioc (measure_singleton a) }, exact continuous_on_primitive h_int end lemma continuous_on_primitive'' {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (Icc a b) := (continuous_on_primitive h_int).congr (λ x₀ hx₀, integral_of_le hx₀.1) variables [no_bot_order α] [no_top_order α] [has_no_atoms μ] lemma continuous_primitive {f : α → E} (h_int : ∀ a b : α, interval_integrable f μ a b) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := begin rw continuous_iff_continuous_at, intro b₀, cases no_bot b₀ with b₁ hb₁, cases no_top b₀ with b₂ hb₂, apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂), exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _) end lemma _root_.measure_theory.integrable.continuous_primitive {f : α → E} (h_int : integrable f μ) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := continuous_primitive (λ _ _, h_int.interval_integrable) a end continuous_primitive section variables {f g : α → ℝ} {a b : α} {μ : measure α} lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] } end lemma integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (function.support f ∩ Ioc a b) := begin obtain hab | hab := le_total b a; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { rw [←not_iff_not, not_and_distrib, not_lt, not_lt, integral_of_ge hab, neg_nonpos], exact iff_of_true (integral_nonneg_of_ae hf) (or.intro_left _ hab) }, rw [integral_of_le hab, set_integral_pos_iff_support_of_nonneg_ae hf hfi.1, iff.comm, and_iff_right_iff_imp], contrapose!, intro h, rw [Ioc_eq_empty h.not_lt, inter_empty, measure_empty], exact le_refl 0, end lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (function.support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi variable (hab : a ≤ b) include hab lemma integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H lemma integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf lemma integral_nonneg_of_forall (hf : ∀ u, 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae hab $ eventually_of_forall hf lemma integral_nonneg [topological_space α] [opens_measurable_space α] [order_closed_topology α] (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf lemma norm_integral_le_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in a..b, ∥f x∥ ∂μ := norm_integral_le_abs_integral_norm.trans_eq $ abs_of_nonneg $ integral_nonneg_of_forall hab $ λ x, norm_nonneg _ lemma abs_integral_le_integral_abs : abs (∫ x in a..b, f x ∂μ) ≤ ∫ x in a..b, abs (f x) ∂μ := norm_integral_le_integral_norm hab section mono variables (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) include hf hg lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H lemma integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h lemma integral_mono_on [topological_space α] [opens_measurable_space α] [order_closed_topology α] (h : ∀ x ∈ Icc a b, f x ≤ g x) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := λ x hx, h x $ Ioc_subset_Icc_self hx in by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H lemma integral_mono (h : f ≤ g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg $ ae_of_all _ h end mono end /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. There are four instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a], 𝓝[Ioi a])`, `(a, 𝓝[Iic a], 𝓝[Iic a])`, and `(a, 𝓝 a, 𝓝 a)`. -/ class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β] (a : out_param β) (outer : filter β) (inner : out_param $ filter β) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter variables [linear_order β] [measurable_space β] [topological_space β] instance pure (a : β) : FTC_filter a (pure a) ⊥ := { pure_le := le_refl _, le_nhds := bot_le } instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l'] {μ : measure β} [locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds variables [opens_measurable_space β] [order_topology β] instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_refl _ } instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : β) : FTC_filter a (𝓝[Iic a] a) (𝓝[Iic a] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : β) : FTC_filter a (𝓝[Ici a] a) (𝓝[Ioi a] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } end FTC_filter open asymptotics section variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β} {μ : measure α} {u v ua va ub vb : β → α} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] variables [topological_space α] section variables [locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end variables [order_topology α] [borel_space α] local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ eventually_eq.rfl, have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'], intros t ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β} {a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- **First Fundamental Theorem of Calculus**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s.prod t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s.prod t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s.prod t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s.prod t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals. -/ variable {f' : ℝ → E} /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.measurable.ae_measurable.measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-- The integral of a continuous function is continuous on a real set `s`. This is true even without the assumption of continuity, but a proof of that fact does not yet exist in mathlib. -/ theorem continuous_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : continuous_on (λ u, ∫ x in a..u, f x) s := (differentiable_on_integral_of_continuous hintg hcont).continuous_on /-- **Second Fundamental Theorem of Calculus**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (Icc a b)) : ∫ y in a..b, f' y = f b - f a := begin have hmeas' : ae_measurable f' (volume.restrict (Icc a b)), from hcont'.ae_measurable measurable_set_Icc, refine eq_sub_of_add_eq (eq_of_has_deriv_right_eq (λ y hy, _) hderiv (λ y hy, _) hcont (by simp) _ (right_mem_Icc.2 hab)), { refine (integral_has_deriv_within_at_right _ _ _).add_const _, { refine (hcont'.mono _).interval_integrable, simp only [hy.left, Icc_subset_Icc_right hy.right.le, interval_of_le] }, { exact ⟨_, Icc_mem_nhds_within_Ioi hy, hmeas'⟩, }, { exact (hcont' _ (mem_Icc_of_Ico hy)).mono_of_mem (Icc_mem_nhds_within_Ioi hy) } }, { -- TODO: prove that the integral of any integrable function is continuous and use here letI : tendsto_Ixx_class Ioc (𝓟 (Icc a b)) (𝓟 (Ioc a b)) := tendsto_Ixx_class_principal.2 (λ x hx y hy, Ioc_subset_Ioc hx.1 hy.2), haveI : is_measurably_generated (𝓝[Ioc a b] y) := measurable_set_Ioc.nhds_within_is_measurably_generated y, letI : FTC_filter y (𝓝[Icc a b] y) (𝓝[Ioc a b] y) := ⟨pure_le_nhds_within hy, inf_le_left⟩, refine (integral_has_deriv_within_at_right _ _ _).continuous_within_at.add continuous_within_at_const, { exact (hcont'.mono $ Icc_subset_Icc_right hy.2).interval_integrable_of_Icc hy.1 }, { exact ⟨_, mem_sets_of_superset self_mem_nhds_within Ioc_subset_Icc_self, hmeas'⟩ }, { exact (hcont' y hy).mono Ioc_subset_Icc_self } } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ico (min a b) (max a b), has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hcont' hderiv, exact integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont' }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hcont' hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont', neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at' (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin refine integral_eq_sub_of_has_deriv_right hcont _ hcont', intros y hy', obtain (hy | hy) : y ∈ Ioo (min a b) (max a b) ∨ min a b = y ∧ y < max a b, { simpa only [le_iff_lt_or_eq, or_and_distrib_right, mem_Ioo, mem_Ico] using hy' }, { exact (hderiv y hy).has_deriv_within_at }, { refine has_deriv_at_interval_left_endpoint_of_tendsto_deriv (λ x hx, (hderiv x hx).has_deriv_within_at.differentiable_within_at) _ _ _, { exact (hcont y (Ico_subset_Icc_self hy')).mono Ioo_subset_Icc_self }, { exact Ioo_mem_nhds_within_Ioi hy' }, { have : tendsto f' (𝓝[Ioi y] y) (𝓝 (f' y)), { refine tendsto.mono_left _ (nhds_within_mono y Ioi_subset_Ici_self), have h := hcont'.continuous_within_at (left_mem_Icc.mpr min_le_max), simpa only [← nhds_within_Icc_eq_nhds_within_Ici hy.2, interval, hy.1] using h }, have h := eventually_of_mem (Ioo_mem_nhds_within_Ioi hy') (λ x hx, (hderiv x hx).deriv), rwa tendsto_congr' h } }, end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at'_of_le (hab : a ≤ b) (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_at' hcont (by rwa [min_eq_left hab, max_eq_right hab]) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_at' (has_deriv_at.continuous_on hderiv) (λ x hx, hderiv _ (mem_Icc_of_Ioo hx)) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is continuous on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont' : continuous_on (deriv f) (interval a b)) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hcont' theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f') (hdiff : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := by rw [← hderiv, integral_deriv_eq_sub hdiff]; cc /-! ### Integration by parts -/ theorem integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hcu' : continuous_on u' (interval a b)) (hcv' : continuous_on v' (interval a b)) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_eq_sub_of_has_deriv_at (λ x hx, (hu x hx).mul (hv x hx)) $ (hcu'.mul (has_deriv_at.continuous_on hv)).add ((has_deriv_at.continuous_on hu).mul hcv') theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hcu' : continuous_on u' (interval a b)) (hcv' : continuous_on v' (interval a b)) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x := begin have hcv := has_deriv_at.continuous_on hv, rw [← integral_deriv_mul_eq_sub hu hv hcu' hcv', ← integral_sub], { exact integral_congr (λ x hx, by simp only [mul_comm, add_sub_cancel']) }, { exact ((hcu'.mul hcv).add ((has_deriv_at.continuous_on hu).mul hcv')).interval_integrable }, { exact (hcv.mul hcu').interval_integrable }, end /-! ### Integration by substitution / Change of variables -/ theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hf' : continuous_on f' (interval a b)) (hg : ∀ x ∈ f '' (interval a b), continuous_at g x) (hgm : ∀ x ∈ f '' (interval a b), measurable_at_filter g (𝓝 x)) : -- TODO: prove that the integral of any integrable function is continuous and use here to remove -- assumption `hgm` ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := let hg' := continuous_at.continuous_on hg in have h : ∀ x ∈ interval a b, has_deriv_at (λ u, ∫ t in f a..f u, g t) ((g ∘ f) x * f' x) x, { intros x hx, have hs := interval_subset_interval_left hx, exact (integral_has_deriv_at_right (hg'.mono $ trans (intermediate_value_interval $ has_deriv_at.continuous_on $ λ y hy, hf y $ hs hy) $ image_subset f hs).interval_integrable (hgm (f x) ⟨x, hx, rfl⟩) $ hg (f x) ⟨x, hx, rfl⟩).comp _ (hf x hx) }, by simp_rw [integral_eq_sub_of_has_deriv_at h $ (hg'.comp (has_deriv_at.continuous_on hf) $ subset_preimage_image f _).mul hf', integral_same, sub_zero] theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := integral_comp_mul_deriv' h h' (λ x h, hg.continuous_at) (λ x h, hg.measurable.measurable_at_filter) theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval (f a) (f b), has_deriv_at g (g' x) x) (hf' : continuous_on f' (interval a b)) (hg1 : continuous_on g' (interval (f a) (f b))) (hg2 : ∀ x ∈ f '' (interval a b), continuous_at g' x) (hgm : ∀ x ∈ f '' (interval a b), measurable_at_filter g' (𝓝 x)) : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by rw [integral_comp_mul_deriv' hf hf' hg2 hgm, integral_eq_sub_of_has_deriv_at hg hg1] theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := integral_eq_sub_of_has_deriv_at (λ x hx, (hg x hx).comp x $ hf x hx) $ (hg'.comp_continuous_on $ has_deriv_at.continuous_on hf).mul hf' end interval_integral
f25ffb51a36d3b3da5a0a99fcd3cc503c5b5ff9e
29fc903502a2f31a2009389392484557342601fe
/src/graph.lean
77d474be4caa81a9ee92b1e041b699f610bdb392
[]
no_license
NicolasRouquette/digraphs
9a7ed10ce54ce3d60983db153624d33e47391f8f
c6a88abc2565b0b25a0b3a93665d4b285c79e51b
refs/heads/master
1,673,439,036,710
1,604,799,582,000
1,604,799,582,000
310,965,050
0
0
null
null
null
null
UTF-8
Lean
false
false
50,137
lean
-- A basic framework for graph theory on multidigraphs in Lean -- and a proof that no_watershed_condition is sufficient to -- establish that a graph has a unique sink for each vertex -- -- I hope to give some introduction to the syntax of how Lean works here, -- but I assume some familiarity with functions, pattern matching, -- type theory, and proofs. -- -- The most important thing to note is that `begin` and `end` delineate -- sections of code in "tactic/interactive proof mode" (as opposed to -- "term mode"). The Lean compiler shows the proof goal and the available -- assumptions and context, and then shows how it changes after tactics -- are executed. The best way to see this happen is to download Lean from -- the following links and open it in VSCode (or emacs) and walk through -- the steps of a proof to see the changes. -- -- VSCode: "Typing ctrl-shift-enter opens up a message window which shows you -- error messages, warnings, output, and goal information when in tactic mode." -- Emacs: "C-c C-g show goal in tactic proof (lean-show-goal-at-pos)" -- (https://leanprover.github.io/reference/using_lean.html) -- -- Make sure to create a project folder and install mathlib as explained here: -- https://leanprover.github.io/reference/using_lean.html#using-the-package-manager -- -- http://leanprover.github.io/ -- https://github.com/leanprover/lean -- Quick primer on Lean: -- -- Propositions are types. This means that the mathematical language of Lean is -- the language of types, which can encode any sensical sentence about math. -- Types are, of course, also used in the design of computable programming -- languages, which Lean also is. But "mere" propositions don't contain data -- to compute on: only the type of a proof matters, really, not its exact details. -- -- The term language and the type language are the same, which means that values -- can be mentioned in types, and vice-versa. This is a result of dependent type -- theory, and it allows encoding interesting propositions, such as about the value -- of functions: given some (f : ℝ → ℝ), (∀ x : ℝ, x > 0 → f x = 0) is the -- proposition that, for positive values of `x`, `f x` evaluates to zero. Note that -- `f` is a fixed value, and `x` is a variable value, both mentioned at the type level. -- -- ∀ is actually the same thing as Π – they are notation for dependently-typed -- functions. (f : Π (a : α), β a) is a function that takes an element `a` of type `α` -- and returns a result that `β a`, with a type that can depend on the value of `a`. -- Putting this together, if we have `f` as above, and some `v : α`, then `f v : β v` -- (meaning, the value of `f` applied to `v` has type `β v`). -- If `β a` does _not_ depend on `a` (that is, if `β` is a constant function, say, -- β = λ _, γ), then the type of `f` can be written as `α → γ`, the type of a -- non-dependent function, also familiar as implication from logic. -- The cool bit about dependent functions, though, is that they are also used to -- introduce polymorphism, if `α` is chosen to be `Type` (or `Prop`, or `Sort u` -- most generally). So `(λ _ a, a) : ∀ {α : Type}, α → α` is the polymorphic -- identity function. Note that function terms are introduced with lambdas: -- def f : Π (a : α), β a := -- λ (a : α), <some value of type `β a` using `a : α` in scope> -- -- But more typically, top-level definitions will have this alternate syntax: -- def f (a : α) : β a := <some value of type `β a` using `a : α` in scope> -- There are subtle differences, but they are basically the same, just note -- that in this latter form, (a : α) is already in scope without the lambda binder! -- -- I mention this below, but for completeness, there is existential quantification: -- (∃ (a : α), p a) : Prop, and dependent products: (Σ' (a : α), p a) : Type. -- Dependent products give access to the value and the proof, whereas existentials -- only assert that there is such a value, without giving it explicitly. -- This is the difference between (non-computable) classical logic and (computable) -- intuitionistic logic. See https://homotopytypetheory.org/book/ for more. -- -- Definitional versus propositional equality: there are two varieties of equality: -- `:=` is the syntax used to declare equalities, most of the time, and -- `=` is the proposition that two things are equal. The Lean compiler will solve -- definitional equalities, and this can be turned into a propositional equality -- using `refl a : a = a` (standing for the reflexivity of equality). -- For example, `refl 1 : 1 = 1` is the proof that 1 equals itself. Duh! -- `eq.trans (e1 : a = b) (e2 : b = c) : a = c` is an example where, even though -- `a`, `b`, and `c` are not known in advance (and thus are not definitionally -- equal), their propositional equalities can still be combined. -- Import libraries that this file depends on import data.fintype.basic data.equiv.basic -- Just a universe variable (used to avoid Girard's/Russel's paradox). -- Not so important; see the following for more: -- https://leanprover.github.io/reference/other_commands.html -- https://en.wikipedia.org/wiki/Intuitionistic_type_theory#Universe_Types universe u -- A few helpful lemmata, explanations skipped theorem psigma_elim_exists {α : Type} {β : α → Prop} {r : Prop} : Exists β → (psigma β → r) → r := λ e f, exists.elim e (λ a b, f (psigma.mk a b)) theorem subtype_elim_exists {α : Type} {β : α → Prop} {r : Prop} : Exists β → (subtype β → r) → r := λ e f, exists.elim e (λ a b, f (subtype.mk a b)) lemma list.nodup_tail_of_nodup {α : Type} {l : list α} : list.nodup l → list.nodup (list.tail l) := begin intro nd, cases l, exact list.nodup_nil, rw list.tail_cons, apply list.nodup_of_nodup_cons, exact nd, end -- end lemmata -- First we will need to define the types that characterize a (multi)digraph. -- An arc connects a starting and ending vertex; this defines the Type for that. -- in particular, this states that, given a Type (call it V), arcT V is a Type -- defined as `V × V`, which is an ordered pair consisting of two elements of type V. def arcT (V : Type) : Type := V × V def arcT.mk {V : Type} (v1 v2 : V) : arcT V := prod.mk v1 v2 -- Each digraph has a particular type of vertices, type of arcs, and consists of -- the mapping φ from specific arcs to their starting and ending vertices. structure digraph (V E : Type) : Type := mk :: (φ : E → arcT V) -- `arc G v1 v2` is an arc that goes from v1 to v2 in graph G. -- V and E are implicit arguments (since they use {}): they can be filled in -- once we know what the type of G is, since (G : digraph V E) mentions V and E. def arc {V E : Type} (G : digraph V E) (v1 v2 : V) := -- this is an edge paired with a proof that the edge connects -- the vertices mentioned in the type of the arc Σ'(e : E), G.φ e = arcT.mk v1 v2 -- The proposition that an arc exists, without specifying the arc itself. def has_arc {V E : Type} (G : digraph V E) (v1 v2 : V) : Prop := ∃ (e : E), G.φ e = arcT.mk v1 v2 -- Eliminate the existential has_arc with a non-dependent proof function taking an arc. def has_arc.elim {V E : Type} {G : digraph V E} {v1 v2 : V} {r : Prop} : has_arc G v1 v2 → (arc G v1 v2 → r) → r := psigma_elim_exists namespace digraph -- Get the source of an edge E in a graph G def source {V E : Type} (G : digraph V E) (e : E) : V := (G.φ e).1 -- Target of an arc def target {V E : Type} (G : digraph V E) (e : E) : V := (G.φ e).2 -- An initial vertex has no edges leading to it in G def is_initial {V E : Type} (G : digraph V E) (v : V) : Prop := ¬∃ (e : E), target G e = v -- A final vertex has no edges leading from it in G def is_final {V E : Type} (G : digraph V E) (v : V) : Prop := ¬∃ (e : E), source G e = v -- Subtype generated by is_initial -- (that is, a vertex with a proof that it is initial) def initial {V E : Type} (G : digraph V E) := { v : V // is_initial G v } -- Subtype generated by is_final def final {V E : Type} (G : digraph V E) := { v : V // is_final G v } -- A walk, as an inductive type, consists of arcs where each next arc leads -- from the previous arc. This is encoded by matching the vertices at the type -- level: only an arc from v1 to v2 and a walk from v2 to v3 can produce a walk -- from v1 to v3. -- Again, V and E can be figured out from an explicit G. inductive walk {V E : Type} (G : digraph V E) : V → V → Type | empty {v : V} : walk v v | step {v1 v2 v3 : V} : arc G v1 v2 → walk v2 v3 → walk v1 v3 -- This begins a namespace; everything declared in this namespace will be accessed -- with the prefix `walk.` outside of the namespace, like `walk.length` namespace walk -- The edges underlying a walk. -- This is a function defined by taking some arguments (most notably a walk) -- and returning a list of elements of type E. -- Note that G is implicit: it's inferrable from the type of the walk given to edges def edges {V E : Type} {G : digraph V E} {v1 v2 : V} : walk G v1 v2 → list E := -- this is tactic mode begin -- `intro` introduces the argument `w : walk G v1 v2` intro w, -- `induction` takes apart the two cases of `w` (`empty` and `step`) -- and adds an induction hypothesis for the nested walk in the `step` case induction w, -- for the first case, we want to produce an empty list -- `exact` just means that we are finishing the goal with a suitable term exact list.nil, -- for the second case, we `cons`truct a new list by adding the edge -- of the arc on the front to the front on the rest of the edges -- (note that w_ᾰ and w_ih are names automatically generated by `induction w`) exact list.cons w_ᾰ.1 w_ih, end -- The vertices visited in a walk, including the start and end vertices -- (which are already mentioned in the type). def vertices {V E : Type} {G : digraph V E} {v1 v2 : V} : walk G v1 v2 → list V := begin -- similar story, but we start with v2 in the empty case intro w, induction w, exact list.cons v2 list.nil, -- and add v1 at each step exact list.cons w_v1 w_ih, end -- The length of a walk, i.e. the number of arcs used in it, as a natural number. def length {V E : Type} {G : digraph V E} {v1 v2 : V} : walk G v1 v2 → ℕ := begin intro w, induction w, exact 0, -- Note: nat.succ n = n+1, get used to it ;) exact nat.succ w_ih, end -- This is our first lemma; it's like a definition but usually it contains a proof, -- (in this case: a proof that the length of an empty walk is 0). Conceptually, -- in type theory, there is no real difference: this is just another -- dependently-typed function, taking variables V E G and v and returning a result. @[simp] -- this attribute lets it get picked up by the `simp` tactic lemma length_empty {V E : Type} {G : digraph V E} {v : V} : -- (empty G : walk G v v) is just a type annotation specifying v -- This could be written (empty _ : walk G v v), since G is -- inferrable by unification length (empty: walk G v v) = 0 := by refl -- definitional equality holds here @[simp] lemma length_step {V E : Type} {G : digraph V E} {v1 v2 v3 : V} (a : arc G v1 v2) (w : walk G v2 v3) : length (step a w) = length w + 1 := by refl -- A walk from v1 to v2 can be concatenated with a walk from v2 to v3 by first -- taking the arcs from the first walk, then taking the arcs from the second. -- This is a binary function with two arguments, nothing else is new. def concat {V E : Type} {G : digraph V E} {v1 v2 v3 : V} : walk G v1 v2 → walk G v2 v3 → walk G v1 v3 := begin intros w1 w2, induction w1, exact w2, exact step w1_ᾰ (w1_ih w2), end -- A proof of a fact that's obvious enough for the equation compiler to solve @[simp] lemma concat_empty_left {V E : Type} {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : concat (empty) w = w := by refl -- Again, pretty obvious lemma concat_step_left {V E : Type} {G : digraph V E} {v1 v2 v3 v4 : V} (a : arc G v1 v2) (w1 : walk G v2 v3) (w2 : walk G v3 v4) : concat (step a w1) w2 = step a (concat w1 w2) := by refl -- But this one needs to be solved by induction, since there's no special case -- for an empty walk on the right (one must walk through all of the first walk). @[simp] lemma concat_empty_right {V E : Type} {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : concat w (empty) = w := begin -- luckily it is simple using induction induction w, refl, -- `rw` (or `rewrite`) is a tactic that changes the type of the goal -- given particular equalities; in this case, it finishes the goal too. rw [concat_step_left, w_ih], end -- Concatenating walks adds their length. lemma concat_length {V E : Type} {G : digraph V E} {v1 v2 v3 : V} (w1 : walk G v1 v2) (w2 : walk G v2 v3) : length (concat w1 w2) = length w1 + length w2 := begin induction w1, -- this is easy enough for the tactic to solve by simplification, -- by using these facts (available with the [simp] attribute): -- 1. concat (empty G) w2 = w2 -- 2. length (empty G) = 0 simp, -- provide two additional theorems to help `simp` close the goal: simp [concat_step_left, w1_ih], rw add_assoc, rw add_assoc, rw add_comm 1 w2.length, end -- Useful lemmata regarding walk.vertices -- (still inside the walk namespace!) namespace vertices -- Takes an assumption that the walk is empty, making it easier to use -- when the proof is not obviously `refl`. When it is obvious, use: -- rw [walk.vertices.empty _ rfl], @[simp] def empty {V E : Type} {G : digraph V E} {v : V} (w : walk G v v) : (w = walk.empty) → walk.vertices w = [v] := λ h, eq.substr h rfl -- Takes an assumption that the walk is nonempty, making it easier to use -- when the proof is not obviously `refl`. When it is obvious, use: -- rw [walk.vertices.step _ _ _ rfl], @[simp] def step {V E : Type} {G : digraph V E} {v1 v2 v3 : V} (a : arc G v1 v2) (w : walk G v2 v3) (w' : walk G v1 v3) : (w' = walk.step a w) → walk.vertices w' = v1 :: walk.vertices w := λ h, eq.substr h rfl -- The list of vertices of a walk starts with the starting vertex of the walk. def starts_with {V E : Type} {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : walk.vertices w = v1 :: list.tail (walk.vertices w) := begin cases w, refl, refl, end -- The list of vertices follow concatenation ... except for the first vertex of -- the second walk, which would be duplicated by just joining the verticces, -- since it is the last entry in `walk.vertices w1` already. def concat {V E : Type} {G : digraph V E} {v1 v2 v3 : V} (w1 : walk G v1 v2) (w2 : walk G v2 v3) (w3 : walk G v1 v3) : (w3 = walk.concat w1 w2) → walk.vertices w3 = walk.vertices w1 ++ list.tail (walk.vertices w2) := begin intro h, rw h, induction w1, { simp, exact starts_with w2 }, rw [concat_step_left w1_ᾰ w1_ᾰ_1 w2], -- simplify right side rw [step w1_ᾰ w1_ᾰ_1 _ rfl], -- simplify left side rw [step w1_ᾰ (concat w1_ᾰ_1 w2) _ rfl], -- pass through the cons, and apply induction hypothesis congr, apply w1_ih _ _ rfl, end end vertices end walk -- close out the namespaces; back to the default namespace of this file -- Back to types, a similar story regarding paths as walks: -- A path is a walk with a proof that vertices are not repeated. def path {V E : Type} (G : digraph V E) : V → V → Type := λ v1 v2, { w : walk G v1 v2 // list.nodup (walk.vertices w) } -- The proposition that a path between two vertices merely exists. def has_path {V E : Type} (G : digraph V E) : V → V → Prop := λ v1 v2, ∃ (w : walk G v1 v2), list.nodup (walk.vertices w) -- Eliminate the existential has_path via a real path def has_path.elim {V E : Type} {G : digraph V E} {v1 v2 : V} {r : Prop} : has_path G v1 v2 → (path G v1 v2 → r) → r := subtype_elim_exists namespace path -- An empty path is simple to generate; its list of 1 vertex obviously has no -- duplicates. def empty {V E : Type} (G : digraph V E) {v : V} : path G v v := begin -- `apply` is sort of like `exact`, but it expects a function that requires more -- arguments to reach the proof goal. -- In particular, this starts to create a subtype with the value `empty` apply subtype.mk (walk.empty), -- but it requires a proof that there are no duplicates in its vertex list: simp [walk.vertices.empty, list.nodup_singleton], end -- An arc between distinct vertices gives a path def from_arc {V E : Type} (G : digraph V E) {v1 v2 : V} : (v1 ≠ v2) → arc G v1 v2 → path G v1 v2 := begin intro h, intro a, -- `let` binds a local constant in a way that it can be referred to -- in other proof terms let w := walk.step a (walk.empty), apply subtype.mk w, -- `have` just provides a usuable constant whose definition can't be referred to have : walk.vertices w = [v1, v2], refl, rw this, -- `simp` helps make progress on the goal simp [list.nodup_singleton], -- the only thing missing is a proof that the vertices are distinct, -- which is true by assumption exact h -- or we could even use the `assumption` tactic end @[reducible] -- [reducible] makes this definition more transparent def length {V E : Type} {G : digraph V E} {v1 v2 : V} : path G v1 v2 → ℕ := λ p, walk.length p.1 -- This is a big topic: creating a path from a walk -- Note that my proofs in this section are ugly, so feel free to skip them -- (the high-level idea is easy enough to grasp; just know that it's -- machine-verified ;D) namespace from_walk -- A helpful invariant: a walk with just a vertex removed preserves the property -- of having no duplicates. def preserves_nodup {V E : Type} {G : digraph V E} {v v1 v2 : V} (w : walk G v1 v2) (w' : walk G v v2) := list.nodup (list.tail (walk.vertices w)) → list.nodup (list.tail (walk.vertices w')) -- But it turns out that the desired walk being a subwalk is sufficient def split_at {V E : Type} {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) (v : V) := Σ' (w1 : walk G v1 v) (w2 : walk G v v2), w = walk.concat w1 w2 -- This includes the other invariant we want to guarantee (that v does not -- appear except as the first vertex of w2). def split_at_without {V E : Type} {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) (v : V) := Σ' (w1 : walk G v1 v) (w2 : walk G v v2), (v ∉ list.tail (walk.vertices w2)) ∧ w = walk.concat w1 w2 -- Weaken the latter to the former ... -- Note: `a_of_b` is convention to indicate a function/lemma with a type like `b → a` def split_at_of_split_at_without {V E : Type} {G : digraph V E} {v1 v2 : V} {w : walk G v1 v2} {v : V} : split_at_without w v → split_at w v := begin intro s, constructor, constructor, exact s.2.2.2 end -- And recover the invariant from it lemma split_at.preserves_nodup {V E : Type} {G : digraph V E} {v1 v2 : V} {w : walk G v1 v2} {v : V} (s : split_at w v) : preserves_nodup w s.2.1 := begin cases s with w1 s, cases s with w2 p, intro nd, simp, rw [walk.vertices.concat _ _ _ p] at nd, rw [walk.vertices.starts_with _] at nd, simp at nd, rw list.nodup_append at nd, exact nd.2.1, end def discard_vertex.split_at {V E : Type} [decidable_eq V] {G : digraph V E} (v : V) {v1 v2 : V} (w : walk G v1 v2) : psum (split_at_without w v) (v ∉ list.tail (walk.vertices w)) := begin induction w with v0 v1 v2 v3 a w ih, right, simp [walk.vertices.empty _ rfl], simp [walk.vertices.step _ _ _ rfl], cases ih, left, apply psigma.mk (walk.step a ih.1), apply psigma.mk ih.2.1, apply and.intro ih.2.2.1, rw [walk.concat_step_left _ _ _], congr, exact ih.2.2.2, by_cases h : v = v2, left, rw h, rw h at ih, have : walk.concat (walk.step a (walk.empty)) w = walk.step a w, { simp [walk.concat_step_left _ _ _], }, exact psigma.mk (walk.step a (walk.empty)) (psigma.mk w (and.intro ih this)), right, have : walk.vertices w = v2 :: list.tail (walk.vertices w), cases w, refl, refl, rw this, intro vin, cases vin, exact h vin, exact ih vin, end -- Remove any occurrence of a vertex from a walk, by either returning a new walk -- formed as a subset of the previous walk but starting from the vertex to be -- removed (along with proofs that the vertex was removed, and that the new walk -- contains no dupicates if the original did), OR a proof that the vertex -- does not occur in the original walk. -- -- This is obviously ugly, but encodes enough information to make from_walk work. def discard_vertex {V E : Type} [decidable_eq V] {G : digraph V E} (v : V) {v1 v2 : V} (w : walk G v1 v2) : psum -- either a new walk (Σ' (w' : walk G v v2), -- from v to v2 -- where v does not occur (v ∉ list.tail (walk.vertices w')) ∧ -- and preserving the no duplicates property preserves_nodup w w') -- or a proof that the vertex does not occur in the original walk (v ∉ list.tail (walk.vertices w)) := begin induction w with v0 v1 v2 v3 a w ih, right, simp [walk.vertices.empty _ rfl], simp [walk.vertices.step _ _ _ rfl], cases ih, left, apply psigma.mk ih.1, apply and.intro ih.2.1, intro ndaw, simp [walk.vertices.step _ _ _ rfl] at ndaw, apply ih.2.2, apply list.nodup_tail_of_nodup, exact ndaw, by_cases h : v = v2, left, rw h, rw h at ih, have : preserves_nodup (walk.step a w) w, { intro ndaw, simp [walk.vertices.step _ _ _ rfl] at ndaw, apply list.nodup_tail_of_nodup, exact ndaw, }, exact psigma.mk w (and.intro ih this), right, have : walk.vertices w = v2 :: list.tail (walk.vertices w), cases w, refl, refl, rw this, intro vin, cases vin, exact h vin, exact ih vin, end -- This can obviously be used to discard repeats of the first vertex of a walk. -- But this is actually unused ... def discard_vertex.beginning {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : Σ' (w' : walk G v1 v2), (v1 ∉ list.tail (walk.vertices w')) ∧ preserves_nodup w w' := begin have := discard_vertex v1 w, cases this, exact this, exact psigma.mk w (and.intro this id), end -- Using induction on the walk, discard all the vertex repeats to generate a -- path. This has the effect of removing all cycles in the walk. def discard_vertex.all.explicit {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : path G v1 v2 := begin -- Induction on a walk considers the base case (empty) and the step case induction w with v v1 v2 v3 a w ih, -- If the walk is empty, we already know how to generate an empty path; done. exact path.empty _, -- But if v1 = v2, we discard the arc, and just return the induction -- hypothesis (that is, the path generated from the tail), once we have -- rewritten v1 as v2. by_cases v1_v2 : (v1 = v2), rw v1_v2, exact ih, -- Just splits up the induction hypothesis into the walk and the proof. cases ih with ih_w ih_nodup, -- Now we discard the starting vertex from the induction hypothesis' walk have ih_w' := discard_vertex v1 ih_w, -- Consider the cases: a new walk, or the same walk cases ih_w', cases ih_w' with w' p, -- If we obtained a new walk, it is the walk we want to return apply subtype.mk w', -- Construct a proof that the walk has no duplicates rw [walk.vertices.starts_with, list.nodup_cons], constructor, -- from the fact that v does not occur in the rest of the vertices exact p.1, -- and the fact that the ih had no duplicates, so the tail of this has none exact (p.2 (list.nodup_tail_of_nodup ih_nodup)), -- Otherwise, we should return the walk consisting of this arc and the ih walk apply subtype.mk (walk.step a ih_w), -- Do some rewrites of the goal ... rw [walk.vertices.step _ _ _ rfl, list.nodup_cons], constructor, rw [walk.vertices.starts_with, list.mem_cons_iff], -- We know that v1 is not the second vertex v2, nor is it in ih_w apply not_or v1_v2 ih_w', -- And the rest of the ih already had no duplicates, by induction exact ih_nodup, end -- This contains the above algorithm but also produces the proof that either -- the result is the same, or the walk/graph contained a cycle. -- -- This can be used to prove the equivalence of walks and paths in acyclic -- digraphs. def discard_vertex.all.acyc_prf {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : Σ' (p : path G v1 v2), p.1 = w ∨ ∃(v : V) (c : walk G v v), c ≠ walk.empty := begin induction w with v v1 v2 v3 a w ih, exact psigma.mk (path.empty _) (or.inl rfl), by_cases v1_v2 : (v1 = v2), apply psigma.mk, right, tactic.swap, rw v1_v2, exact ih.1, apply exists.intro v2, rw v1_v2 at a, apply exists.intro (walk.step a (walk.empty)), exact λ h, walk.no_confusion h, cases ih with ih prf, cases ih with ih_w ih_nodup, have ih_w' := discard_vertex.split_at v1 ih_w, cases ih_w', have := split_at.preserves_nodup (split_at_of_split_at_without ih_w'), cases ih_w' with w1 ih_w', cases ih_w' with w2 p, apply psigma.mk (subtype.mk w2 begin rw [walk.vertices.starts_with, list.nodup_cons], constructor, exact p.1, exact (this (list.nodup_tail_of_nodup ih_nodup)), end : path G v1 v3), right, apply exists.intro v1, apply exists.intro (walk.step a w1), exact λ h, walk.no_confusion h, apply psigma.mk (subtype.mk (walk.step a ih_w) begin rw [walk.vertices.step _ _ _ rfl], rw [list.nodup_cons], constructor, rw [walk.vertices.starts_with], rw list.mem_cons_iff, apply not_or v1_v2 ih_w', exact ih_nodup, end : path G v1 v3), cases prf, left, simp at prf, simp [prf], right, exact prf, end -- This defeq will be important @[reducible] def discard_vertex.all {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} (w : walk G v1 v2) : path G v1 v2 := (discard_vertex.all.acyc_prf w).1 end from_walk -- This just references the version inside the from_walk namespace @[reducible] def from_walk {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} : walk G v1 v2 → path G v1 v2 := from_walk.discard_vertex.all -- This concatenates the underlying paths then removes cycles to generate -- the new path. def concat {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 v3 : V} (p1 : path G v1 v2) (p2 : path G v2 v3) : path G v1 v3 := from_walk (walk.concat p1.1 p2.1) -- A maximal path is a path going to a final vertex. def maximal {V E : Type} (G : digraph V E) (v1 v2 : V) := pprod (path G v1 v2) (is_final G v2) -- (pprod stores a piece of data and a separate proof) -- Proposition that one exists. def has_maximal {V E : Type} (G : digraph V E) (v1 v2 : V) := (has_path G v1 v2) ∧ (is_final G v2) -- regular conjunction -- Eliminate it following the usual pattern def has_maximal.elim {V E : Type} {G : digraph V E} {v1 v2 : V} {r : Prop} : has_maximal G v1 v2 → (maximal G v1 v2 → r) → r := λ h f, has_path.elim h.1 (λ p, f (pprod.mk p h.2)) -- Hopefully this makes sense now by just looking at the types! def maximal.concat {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 v3 : V} (p1 : path G v1 v2) (p2 : path.maximal G v2 v3) : path.maximal G v1 v3 := begin constructor, exact path.concat p1 p2.1, exact p2.2, end def has_maximal.concat {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 v3 : V} (p1 : path G v1 v2) (p2 : path.has_maximal G v2 v3) : path.has_maximal G v1 v3 := flip and.intro p2.2 begin apply exists.elim p2.1, intro w, intro nodup, exact subtype.exists_of_subtype (path.concat p1 (subtype.mk w nodup)), end -- If the walk underlying a path is nonempty, produce the path corresponding -- to its tail. def vertices.step_back {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 v3 : V} (a : arc G v1 v2) (w : walk G v2 v3) (p : path G v1 v3) : (p.1 = walk.step a w) → path G v2 v3 := begin intro h, cases p, simp at h, apply subtype.mk w, rw [walk.vertices.step _ _ _ h] at p_property, exact list.nodup_of_nodup_cons p_property, end end path -- One encoding (fairly direct and easy to use) of the property of an acyclic -- graph: all walks from a vertex to itself are empty. def is_acyclic {V E : Type} (G : digraph V E) := ∀ (v : V) (w : walk G v v), w = walk.empty -- Subtype generated from that (unused). def acyclic {V E : Type} := { G : digraph V E // is_acyclic G } -- It turns out that in acyclic graphs, from_walk just elaborates the same walk -- with a proof term. lemma is_acyclic.from_walk {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} (acyc : is_acyclic G) (w : walk G v1 v2) : (path.from_walk w).val = w := begin let fw := path.from_walk.discard_vertex.all.acyc_prf w, have : path.from_walk w = fw.1, refl, rw this, cases h : fw with p prf, simp, cases prf, exact prf, exfalso, apply exists.elim prf, intro v, intro prf', apply exists.elim prf', intro c, intro prf'', exact prf'' (acyc v c) end -- Thus paths and walks are equivalent in acyclic digraphs. def path.equiv_walk {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 : V} : is_acyclic G → walk G v1 v2 ≃ path G v1 v2 := λ acyc, -- this is an equivalence a ≃ b: a pair of functions a → b and b → a, -- with proofs that they are inverses of each other equiv.mk path.from_walk subtype.val (is_acyclic.from_walk acyc) (λ p, subtype.eq (is_acyclic.from_walk acyc p.val)) -- Since the cycle elimination algorithm does nothing in an acyclic graph, -- lengths are preserved through concatenation lemma path.acyclic_concat_length {V E : Type} [decidable_eq V] {G : digraph V E} {v1 v2 v3 : V} (p1 : path G v1 v2) (p2 : path G v2 v3) : is_acyclic G → path.length (path.concat p1 p2) = path.length p1 + path.length p2 := begin intro acyc, show walk.length (path.concat p1 p2).1 = walk.length p1.1 + walk.length p2.1, show walk.length (path.from_walk (walk.concat p1.1 p2.1)).1 = walk.length p1.1 + walk.length p2.1, rw [is_acyclic.from_walk acyc _], exact walk.concat_length _ _, end -- Okay, done with types! On to the main course: -- The so-called “no-watershed condition”: for any two vertices with arcs -- from(!) a common vertex, there is another vertex that has paths from -- both of those. (Obviously true if {u,v,w} are not distinct.) -- See section 0.2 in http://www-users.math.umn.edu/~dgrinber/comb2/mt3.pdf def no_watershed_condition {V E : Type} (G : digraph V E) : Prop := Π (u v w : V), arc G u v → arc G u w → ∃ (t : V), has_path G v t ∧ has_path G w t -- Having the no-watershed condition in an acyclic graph produces the result -- that each vertex has a unique sink; that is, a vertex with a maximal path -- from the other vertex. namespace unique_sink -- Inside a namespace/section, we can use the following commands to declare variables -- used in the definitions/lemmata for this section: -- implicit and explicit arguments variables {V E : Type} (G : digraph V E) variables acyc : is_acyclic G -- and typeclass arguments! these are variables of a special type that have a -- canonical value -- In particular: -- decidable_eq V gives a function Π(v1 v2 : V), (v1 = v2) ∨ (v1 ≠ v2) -- that decides whether two vertices are equal, giving a proof either way -- fintype V asserts that V has finitely many inhabitants, by giving a list -- of them all (actually a finite set `finset`), and a proof that every -- element occurs in it: ∀ v : V, v ∈ univ V variables [decidable_eq V] [decidable_eq E] [fintype V] [fintype E] -- Now that we have G as a fixed local variable, we can use it in notation! -- who doesn't love syntactic sugar?!?!? :D local infix `⟶`:50 := arc G local infix `~⟶`:50 := walk G -- unused local infix `*⟶`:50 := path G local infix `×⟶`:50 := path.maximal G -- and their propositional equivalents local infix `⟼`:50 := has_arc G local infix `*⟼`:50 := has_path G local infix `×⟼`:50 := path.has_maximal G -- In finite acyclic graphs, each vertex will have a longest path; -- if `bounded_by p n` is provided, then the longest path from p is at most n steps. def bounded_by (p : V) (n : ℕ) := ∀ (q : V) (w : p *⟶ q), path.length w ≤ n -- This is the proposition used for induction. It limits the results to -- only pertain to vertices p whose paths away from them have length at most n. def P (n : ℕ) := ∀ (p : V), bounded_by G p n → ∃! (q : V), p ×⟼ q -- Helper: These are logically equivalent via two existing lemmate... lemma eq_zero_iff_le_zero {n : nat} : n ≤ 0 ↔ n = 0 := iff.intro nat.eq_zero_of_le_zero nat.le_of_eq -- A walk of length 0 obviously connects the same two vertices. lemma length0 {v1 v2 : V} (w : v1 ~⟶ v2) : walk.length w = 0 → v1 = v2 := begin intro h, -- obviously the `empty` case is trivial: cases w, refl, -- but the `step` case is absurd! rw [walk.length_step] at h, exact absurd h (nat.succ_ne_zero (walk.length w_ᾰ_1)), end -- Two maximal paths from the same vertex cannot have one be empty and the other -- be nonempty. lemma not_diff_emptiness {p q1 q2 : V} (w1 : p ×⟶ q1) (w2 : p ×⟶ q2) : ¬(path.length w1.1 = 0 ∧ path.length w2.1 > 0) := begin intro h, have pq1 := length0 G w1.1.1 h.1, have q1_final := w1.2, rw [← pq1] at q1_final, apply q1_final, let w := w2.1.1, cases hw : w, apply flip absurd (ne_of_gt h.2), show walk.length w = 0, rw hw, exact walk.length_empty, apply exists.intro ᾰ.1, have x : (arcT.mk p v2).1 = p, refl, rw [← ᾰ.2] at x, exact x, end -- ... basically the same as above, but more explicit. lemma same_emptiness {p q1 q2 : V} (w1 : p ×⟶ q1) (w2 : p ×⟶ q2) : (path.length w1.1 = 0 ∧ path.length w2.1 = 0) ∨ (path.length w1.1 > 0 ∧ path.length w2.1 > 0) := begin cases h1 : path.length w1.1, left, constructor, refl, cases h2 : path.length w2.1, refl, apply flip absurd (not_diff_emptiness G w1 w2), constructor, exact h1, have := nat.zero_lt_succ n, rw [← h2] at this, exact this, right, constructor, exact nat.zero_lt_succ n, cases h2 : path.length w2.1, apply flip absurd (not_diff_emptiness G w2 w1), constructor, exact h2, have := nat.zero_lt_succ n, rw [← h1] at this, exact this, exact nat.zero_lt_succ n_1, end -- A proof that each path has finite length, bounded above by the number of vertices lemma finite {p q : V} (w : p *⟶ q) : path.length w + 1 ≤ fintype.card V := begin cases w with w nodup, -- this should really be a separate lemma, but it's easy enough to prove inline... have : walk.length w + 1 = list.length (walk.vertices w), { induction w, refl, simp [walk.vertices.step _ _ _ rfl], apply w_ih, rw [walk.vertices.step _ _ _ rfl] at nodup, exact list.nodup_of_nodup_cons nodup, }, rw this, -- now we don't need the fact that it is a list of vertices anymore -- so replace it with a generic `l : list V` in the hypothesis and goal: generalize_hyp h : walk.vertices w = l at nodup, rw h, -- make a finite set from the list let fs : finset V := finset.mk (quotient.mk l) nodup, -- with the same size have : list.length l = finset.card fs := by symmetry; apply quot.lift_beta list.length multiset.card._proof_1, rw this, -- it must be smaller or the same size, since it is a subset exact finset.card_le_of_subset (finset.subset_univ _), end -- A vertex is either final or it has an arc leading from it to some other vertex. -- Relies on [fintype E] def any_arc_from (p : V) : (∃ (v : V), p ⟼ v) ∨ is_final G p := begin let elems : finset E := finset.univ, -- Prove that these are equivalent -- instead of proving each direction separately, we use bijections at each step have : (p ∈ multiset.map (source G) elems.val) ↔ (∃(e : E), source G e = p), symmetry, rw multiset.mem_map, apply exists_congr, intro e, symmetry, apply and_iff_right, exact finset.mem_univ e, -- this is a decidable proposition, so we can determine whether it is true or false by_cases h : p ∈ multiset.map (source G) elems.val, { rw this at h, left, apply exists.elim h, intro e, intro he, apply exists.intro (target G e), apply exists.intro e, apply prod.eq_iff_fst_eq_snd_eq.2, constructor, show (G.φ e).1 = p, exact he, show (G.φ e).2 = target G e, refl, }, { rw this at h, right, exact h, }, end -- tactic mode doesn't know to include this variable -- we will use it in the remaining proofs include acyc -- If all paths leading out of a vertex have length 0, it must be a sink def is_final_of_bounded_by_zero (v : V) : bounded_by G v 0 → is_final G v := begin intros len, have := any_arc_from G v, cases this, { exfalso, apply exists.elim this, intros v1 ha, apply has_arc.elim ha, intro a, let p : v *⟶ v1 := path.from_walk (walk.step a (walk.empty)), have len0 := len _ p, rw [eq_zero_iff_le_zero] at len0, suffices : path.length p = 1, cc, have : p.1 = walk.step a (walk.empty), from is_acyclic.from_walk acyc _, unfold path.length, rw this, refl }, exact this, end -- Helper for induction: giving a path from v1 to v2 with length no less -- than m and the fact that all paths from v1 are at most length n+m, means -- that a path from v2 to v3 must have length at most n. lemma reduce_length {v1 v2 v3 : V} {n m : ℕ} (w : v1 *⟶ v2) (p : v2 *⟶ v3) (lw : path.length w ≥ m) (mh : bounded_by G v1 (n+m)) : path.length p ≤ n := begin let wp : v1 *⟶ v3 := path.concat w p, have lwp : path.length wp = path.length w + path.length p, from path.acyclic_concat_length w p acyc, -- rewrite lw at lwp, apply @nat.le_of_add_le_add_left (path.length w) _ _, rw [← lwp, add_comm], transitivity, apply mh v3, exact nat.add_le_add_left lw _, end -- All vertices have a sink. -- This is a smaller proof following the style of the larger proof. -- We prove it by induction for all vertices that are bounded by n, -- then we pick a sufficiently large n to cover all vertices. lemma find_sink.bounded (n : ℕ) (v1 : V) : bounded_by G v1 n → ∃ (s : V), v1 ×⟼ s := begin intros len, induction n with n ih generalizing v1, { apply exists.intro v1, apply and.intro (subtype.exists_of_subtype (path.empty G)), apply is_final_of_bounded_by_zero, assumption, assumption, }, have := any_arc_from G v1, cases this, { apply exists.elim this, intros v2 ha, apply has_arc.elim ha, intro a, let p : v1 *⟶ v2 := path.from_walk (walk.step a (walk.empty)), have := ih v2 begin have : path.length p = 1, have : p.1 = walk.step a (walk.empty), from is_acyclic.from_walk acyc _, unfold path.length, rw this, refl, intros v' p', apply reduce_length G acyc p, exact ge_of_eq this, exact len, end, apply exists.elim this, intros s hm, apply exists.intro s, exact path.has_maximal.concat p hm }, { apply exists.intro v1, apply and.intro (subtype.exists_of_subtype (path.empty G)), assumption, }, end -- Using `finite`, we pick a sufficient n to bound all vertices lemma find_sink (v1 : V) : ∃ (s : V), v1 ×⟼ s := find_sink.bounded G acyc _ v1 begin unfold bounded_by, intros, rw ← nat.pred_succ (path.length w), apply nat.pred_le_pred, apply unique_sink.finite G end -- Final vertices are their own sink lemma P_final (p : V) : is_final G p → ∃!(q : V), p ×⟼ q := begin intro final, apply exists_unique.intro p, constructor, exact subtype.exists_of_subtype (path.empty G), exact final, intro sink, intro has_max, apply subtype_elim_exists has_max.1, intro p, cases p, cases p_val, refl, exfalso, apply final, apply exists.intro p_val_ᾰ.1, show (G.φ p_val_ᾰ.1).1 = p, rw p_val_ᾰ.2, refl end -- The base case, basically applies only to sinks, which are their own -- sink, obviously. lemma P0 : P G 0 := λ p len, P_final _ acyc p (is_final_of_bounded_by_zero _ acyc p len) -- The whole proof together. -- -- Big picture idea: -- For any vertex p with bounded_by G p n, try to find an arc leading out of it, call -- its target v (≠ p). The unique sink can be obtained by applying induction to v. -- But to establish that it is also unique for p, we take any otherSink -- with a maximal path from p, take the first new vertex visited by that path v2 -- and we can apply the watershed condition to an arc p v and an arc p v2 to get t with -- a path v t and a path v2 t. But by using this, the sinks from v, t, and v2 must -- all be the same since we can extend the maximal path from t to be from v or v2. -- This is essentially the statement that connected vertices share the same sink... -- (Obviously the computer requires more details to formalize this and accept -- it as rigorous, but they are explained below.) theorem Pn : no_watershed_condition G → ∀ (n : ℕ), P G n := begin -- introduce the watershed condition as a variable in scope intro watershed, -- this is the variable for induction, named n' since n will be in scope intro n, -- regular induction on natural numbers (just a special case of induction in DTT) induction n with n ih, -- base case, already proved as P0 above exact P0 G acyc, -- this is the vertex of interest intro p, -- and the proof that maximal paths from p have length at most n+1 intro len, -- try to obtain an arc from p have aa := any_arc_from G p, -- this splits it up into the two cases, replacing aa with the result of each case -- (what follows is mostly the proof of the first case, the second takes one line) cases aa, apply exists.elim aa, -- obtain the vertex it goes to, and the proof that there is an arc intro v, assume ha : p ⟼ v, -- obtain some actual arc from p to v apply has_arc.elim ha, assume a : p ⟶ v, -- a funny proof by contradiction that p ≠ v since it is in an acyclic graph -- TODO: factor this out by_cases (p = v), { let a' : p ⟶ v := a, rw h at a', have := acyc _ (walk.step a' (walk.empty)), exfalso, exact walk.no_confusion this, }, -- using that we can make a path from the arc ... let start : p *⟶ v := path.from_arc G h a, -- ... of length 1 (duh!) have len1 : path.length start = 1, refl, -- Now we can apply the induction hypothesis onto v, since `start` -- guarantees that the length will go down by 1. have exu := ih v begin intro v', intro p', apply reduce_length G acyc start p' (ge_of_eq len1) len, end, -- Now we unpack the existentials ... apply exists_unique.elim exu, simp, -- ... to obtain the sink, the existence of a maximal path from v to that -- sink, and the proof that that sink is unique intro sink, intro has_maxPathToSink, intro uniq, -- so we know that this is the sink we want, just need to prove it has a -- maximal path ... apply exists_unique.intro sink, apply subtype_elim_exists has_maxPathToSink.1, assume pathToSink : v *⟶ sink, constructor, apply subtype.exists_of_subtype, apply path.concat start pathToSink, exact has_maxPathToSink.2, -- ... and that it is unique. Oh boy. -- Given otherSink and a max path from p to otherSink, prove that they are -- the same sink. intro otherSink, intro has_maxPathToOtherSink, show otherSink = sink, apply path.has_maximal.elim has_maxPathToOtherSink, assume maxPathToOtherSink : p ×⟶ otherSink, -- Argue that the maximal path is nonempty. cases hp : maxPathToOtherSink.1.1, { exfalso, apply maxPathToOtherSink.2, apply exists.intro a.1, show (G.φ a.1).1 = p, exact (prod.eq_iff_fst_eq_snd_eq.1 (a.2)).1, }, -- Now we have hp : (maxPathToOtherSink.fst).val = walk.step a_1 a_2 -- so ᾰ is an arc from p to some v2 -- Apply the watershed condition with a : arc G p v, ᾰ : arc G p v2 have water1 := watershed p v v2 a ᾰ, -- so there is some t with paths from v to t and from v2 to t apply exists.elim water1, intro t, simp, intro has_vt, intro has_v2t, apply subtype_elim_exists has_vt, intro vt, apply subtype_elim_exists has_v2t, intro v2t, -- now we have another path like starting, but from p to t, via v. let startt : p *⟶ t := path.concat start vt, -- Induction again! have exu2 := ih t begin intro v', intro p', -- startt has length at least 1, since start has length 1, and -- vt may have length greater than 1, and since it is acyclic. have len_ge1 : path.length startt ≥ 1, have : path.length startt = path.length start + path.length vt, from path.acyclic_concat_length start vt acyc, rw len1 at this, transitivity, exact le_of_eq (eq.symm this), rw [add_comm], exact nat.succ_le_succ (nat.zero_le (path.length vt)), apply reduce_length G acyc startt p' len_ge1 len, end, apply exists_unique.elim exu2, simp, -- Oh here is anotherSink! the unique sink from t intro anotherSink, intro has_maxPathToAnotherSink, intro uniq2, -- but anotherSink = sink, since any maxpath can be extended along vt have := uniq _ (path.has_maximal.concat vt has_maxPathToAnotherSink), -- again argue that an arc connects distinct vertices by_cases (p = v2), { let a' : p ⟶ v2 := ᾰ, rw h at a', have := acyc _ (walk.step a' (walk.empty)), exfalso, exact walk.no_confusion this, }, -- So there's a path from p to v2 just using the arc ᾰ. let startv2 : p *⟶ v2 := path.from_arc G h ᾰ, -- Induction yet again! last time I promise have exuv2 := ih v2 begin intro v', intro p', apply reduce_length G acyc startv2 p', exact ge_of_eq (rfl : path.length startv2 = 1), exact len, end, apply exists_unique.elim exuv2, simp, -- finalSink is the unique sink from v2 intro finalSink, intro has_maxPathToFinalSink, intro uniqv2, -- but finalSink = otherSink, due to the maxpath a_2 from v2 to otherSink have := uniqv2 otherSink begin -- construct the maxpath constructor, -- we can demonstrate the exact path, but we just need its existence, apply subtype.exists_of_subtype, -- hp : (maxPathToOtherSink.fst).val = walk.step a_1 a_2 -- means that just the walk a_2 creates a path too exact path.vertices.step_back _ _ maxPathToOtherSink.1 hp, -- and is maximal since otherSink is still final exact maxPathToOtherSink.2, end, -- and finalSink = anotherSink, by extending maxpaths along v2t have := uniqv2 anotherSink (path.has_maximal.concat v2t has_maxPathToAnotherSink), -- so the congruence closure calculates that otherSink = sink via -- the equalities in scope cc, -- Oh yeah, and if aa had no arcs, then its a final vertex and we're done. exact P_final G acyc p aa, end end unique_sink -- It turns out that we can pick a sufficient n such that Pn holds for all p theorem unique_sink {V E : Type} {G : digraph V E} [decidable_eq V] [decidable_eq E] [fintype V] [fintype E] : is_acyclic G → no_watershed_condition G → ∀ (p : V), ∃! (q : V), path.has_maximal G p q := λ acyc watershed p, unique_sink.Pn G acyc watershed _ p begin unfold unique_sink.bounded_by, intros, rw ← nat.pred_succ (path.length w), apply nat.pred_le_pred, apply unique_sink.finite G end end digraph
3a6226bb2230086b2310333b321152246bebbb0f
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world7/level9.lean
5844c7dbb6c7037abbb202767368fba3b5670d57
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
2,041
lean
import game.world7.level8 -- hide import game.world6.level8 -- hide import tactic.tauto -- useful high-powered tactic local attribute [instance, priority 10] classical.prop_decidable -- hide /- # Advanced proposition world. You already know enough to embark on advanced addition world. But here are just a couple more things. ## Level 9: `exfalso` and proof by contradiction. It's certainly true that $P\land(\lnot P)\implies Q$ for any propositions $P$ and $Q$, because the left hand side of the implication is false. But how do we prove that `false` implies any proposition $Q$? A cheap way of doing it in Lean is using the `exfalso` tactic, which changes any goal at all to `false`. You might think this is a step backwards, but if you have a hypothesis `h : ¬ P` then after `rw not_iff_imp_false at h,` you can `apply h,` to make progress. Try solving this level without using `cc` or `tauto`, but using `exfalso` instead. -/ /- Lemma : no-side-bar If $P$ and $Q$ are true/false statements, then $$(P\land(\lnot P))\implies Q.$$ -/ lemma contra (P Q : Prop) : (P ∧ ¬ P) → Q := begin intro h, cases h with p np, rw not_iff_imp_false at np, exfalso, apply np, exact p, end /- ## Pro tip. `¬ P` is actually `P → false` *by definition*. Try commenting out `rw not_iff_imp_false at ...` by putting two minus signs `--` before the `rw`. Does it still compile? -/ /- Tactic : exfalso ## Summary `exfalso` changes your goal to `false`. ## Details We know that `false` implies `P` for any proposition `P`, and so if your goal is `P` then you should be able to `apply` `false → P` and reduce your goal to `false`. This is what the `exfalso` tactic does. The theorem that `false → P` is called `false.elim` so one can achieve the same effect with `apply false.elim`. This tactic can be used in a proof by contradiction, where the hypotheses are enough to deduce a contradiction and the goal happens to be some random statement (possibly a false one) which you just want to simplify to `false`. -/
24c984dae0599d71767183fca9a33428fd47ebe4
a623837965543f72645ad3de4797a693f5c64274
/test/terminal_goal.lean
778c8e14f2279ea278f3f4b4011643eaed6ecdd6
[]
no_license
khoek/lean-tidy
9e1c8ffebc6a3e4739128e6cf7b7e84cba3a0625
995fbf6efa56f6c01cdb3754fc4a84b648a6dd91
refs/heads/master
1,619,535,208,982
1,549,094,268,000
1,549,094,268,000
122,460,123
0
0
null
1,534,214,616,000
1,519,293,337,000
Lean
UTF-8
Lean
false
false
1,441
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 tidy.recover structure C := ( w : Type ) ( x : list w ) ( y : Type ) ( z : prod w y ) def test_terminal_goal : C := begin fsplit, success_if_fail { terminal_goal }, exact ℕ, terminal_goal, exact [], success_if_fail { terminal_goal }, exact bool, terminal_goal, exact (0, tt) end -- verifying that terminal_goal correctly considers all propositional goals as terminal? structure foo := (x : ℕ) (p : x = 0) open tactic lemma bar : ∃ F : foo, F = ⟨ 0, by refl ⟩ := begin split, swap, split, terminal_goal, swap, success_if_fail { terminal_goal }, exact 0, refl, refl, end structure D := ( w : ℕ → Type ) ( x : list (w 0) ) def test_terminal_goal' : D := begin split, swap, success_if_fail { terminal_goal }, intros, success_if_fail { terminal_goal }, exact ℕ, exact [] end def f : unit → Type := λ _, ℕ def test_terminal_goal'' : Σ x : unit, f x := begin split, terminal_goal, swap, terminal_goal, exact (), dsimp [f], exact 0 end def test_subsingleton_goal : 0 = 0 := begin subsingleton_goal, refl end def test_subsingleton_goal' : list ℕ := begin success_if_fail { subsingleton_goal }, exact [] end
f02ad93930d84ddd249866e5ae09704280c8c479
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/playground/zipper.lean
27a828ec57ec5de38ee0e2491d29ffb0fd78358f
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
1,448
lean
structure ListZipper (α : Type) := (xs : List α) (bs : List α) -- set_option trace.compiler.ir.rc true variables {α : Type} namespace ListZipper def goForward : ListZipper α → ListZipper α | ⟨[], bs⟩ := ⟨[], bs⟩ | ⟨x::xs, bs⟩ := ⟨xs, x::bs⟩ def goBackward : ListZipper α → ListZipper α | ⟨xs, []⟩ := ⟨xs, []⟩ | ⟨xs, b::bs⟩ := ⟨b::xs, bs⟩ def insert : ListZipper α → α → ListZipper α | ⟨xs, bs⟩ x := ⟨xs, x::bs⟩ def erase : ListZipper α → ListZipper α | ⟨[], bs⟩ := ⟨[], bs⟩ | ⟨x::xs, bs⟩ := ⟨xs, bs⟩ def curr [Inhabited α] : ListZipper α → α | ⟨[], bs⟩ := default _ | ⟨x::xs, bs⟩ := x def currOpt : ListZipper α → Option α | ⟨[], bs⟩ := none | ⟨x::xs, bs⟩ := some x def toList : ListZipper α → List α | ⟨xs, bs⟩ := bs.reverse ++ xs def atEnd (z : ListZipper α) : Bool := z.xs.isEmpty end ListZipper def List.toListZipper (xs : List α) : ListZipper α := ⟨xs, []⟩ partial def testAux : ListZipper Nat → ListZipper Nat | z := if z.atEnd then z else if z.curr % 2 == 0 then testAux (z.goForward.insert 0) else if z.curr > 20 then testAux z.erase else testAux z.goForward def test (xs : List Nat) : List Nat := (testAux xs.toListZipper).toList def main (xs : List String) : IO Unit := do IO.println $ test [10, 11, 13, 20, 22, 40, 41, 11], IO.println $ test (xs.map String.toNat)
95c516cb45431aa8fe06c061b6f49c72e4869680
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/ring_theory/matrix_algebra.lean
4b6776fe96fb42479b0abe441379bf9cf77afe93
[ "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
6,758
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 tactic.tidy import ring_theory.tensor_product import data.matrix.basic /-! We provide the `R`-algebra structure on `matrix n n A` when `A` is an `R`-algebra, and show `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)`. -/ universes u v w open_locale tensor_product open_locale big_operators open tensor_product open algebra.tensor_product open matrix variables {R : Type u} [comm_ring R] variables {A : Type v} [ring A] [algebra R A] variables {n : Type w} [fintype n] section variables [decidable_eq n] instance : algebra R (matrix n n A) := { commutes' := λ r x, begin ext, simp [matrix.scalar, matrix.mul_val, matrix.one_val, algebra.commutes], end, smul_def' := λ r x, begin ext, simp [matrix.scalar, algebra.smul_def'' r], end, ..((matrix.scalar n).comp (algebra_map R A)) } lemma algebra_map_matrix_val {r : R} {i j : n} : algebra_map R (matrix n n A) r i j = if i = j then algebra_map R A r else 0 := begin dsimp [algebra_map, algebra.to_ring_hom, matrix.scalar], split_ifs with h; simp [h, matrix.one_val_ne], end end variables (R A n) namespace matrix_equiv_tensor /-- (Implementation detail). The bare function underlying `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, on pure tensors. -/ def to_fun (a : A) (m : matrix n n R) : matrix n n A := λ i j, a * algebra_map R A (m i j) /-- (Implementation detail). The function underlying `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an `R`-linear map in the second tensor factor. -/ def to_fun_right_linear (a : A) : matrix n n R →ₗ[R] matrix n n A := { to_fun := to_fun R A n a, map_add' := λ x y, by { dsimp only [to_fun], ext, simp [mul_add], }, map_smul' := λ r x, begin dsimp only [to_fun], ext, simp only [matrix.smul_val, pi.smul_apply, ring_hom.map_mul, algebra.id.smul_eq_mul, ring_hom.map_mul], rw [algebra.smul_def r, ←_root_.mul_assoc, ←_root_.mul_assoc, algebra.commutes], end, } /-- (Implementation detail). The function underlying `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an `R`-bilinear map. -/ def to_fun_bilinear : A →ₗ[R] matrix n n R →ₗ[R] matrix n n A := { to_fun := to_fun_right_linear R A n, map_add' := λ x y, by { ext, simp [to_fun_right_linear, to_fun, add_mul], }, map_smul' := λ r x, by { ext, simp [to_fun_right_linear, to_fun] }, } /-- (Implementation detail). The function underlying `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an `R`-linear map. -/ def to_fun_linear : A ⊗[R] matrix n n R →ₗ[R] matrix n n A := tensor_product.lift (to_fun_bilinear R A n) variables [decidable_eq n] /-- The function `(A ⊗[R] matrix n n R) →ₐ[R] matrix n n A`, as an algebra homomorphism. -/ def to_fun_alg_hom : (A ⊗[R] matrix n n R) →ₐ[R] matrix n n A := alg_hom_of_linear_map_tensor_product (to_fun_linear R A n) begin intros, ext, simp_rw [to_fun_linear, to_fun_bilinear, lift.tmul], dsimp, simp_rw [to_fun_right_linear], dsimp, simp_rw [to_fun, matrix.mul_mul_left, matrix.smul_val, matrix.mul_val, ←_root_.mul_assoc _ a₂ _, algebra.commutes, _root_.mul_assoc a₂ _ _, ←finset.mul_sum, ring_hom.map_sum, ring_hom.map_mul, _root_.mul_assoc], end begin intros, ext, simp only [to_fun_linear, to_fun_bilinear, to_fun_right_linear, to_fun, matrix.one_val, algebra_map_matrix_val, lift.tmul, linear_map.coe_mk], split_ifs; simp, end @[simp] lemma to_fun_alg_hom_apply (a : A) (m : matrix n n R) : to_fun_alg_hom R A n (a ⊗ₜ m) = λ i j, a * algebra_map R A (m i j) := begin simp [to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear], refl, end /-- (Implementation detail.) The bare function `matrix n n A → A ⊗[R] matrix n n R`. (We don't need to show that it's an algebra map, thankfully --- just that it's an inverse.) -/ def inv_fun (M : matrix n n A) : A ⊗[R] matrix n n R := ∑ (p : n × n), M p.1 p.2 ⊗ₜ (std_basis_matrix p.1 p.2 1) @[simp] lemma inv_fun_zero : inv_fun R A n 0 = 0 := by simp [inv_fun] @[simp] lemma inv_fun_add (M N : matrix n n A) : inv_fun R A n (M + N) = inv_fun R A n M + inv_fun R A n N := by simp [inv_fun, add_tmul, finset.sum_add_distrib] @[simp] lemma inv_fun_smul (a : A) (M : matrix n n A) : inv_fun R A n (λ i j, a * M i j) = (a ⊗ₜ 1) * inv_fun R A n M := by simp [inv_fun,finset.mul_sum] @[simp] lemma inv_fun_algebra_map (M : matrix n n R) : inv_fun R A n (λ i j, algebra_map R A (M i j)) = 1 ⊗ₜ M := begin dsimp [inv_fun], simp only [algebra.algebra_map_eq_smul_one, smul_tmul, ←tmul_sum, mul_boole], congr, conv_rhs {rw matrix_eq_sum_std_basis M}, convert finset.sum_product, simp, end lemma right_inv (M : matrix n n A) : (to_fun_alg_hom R A n) (inv_fun R A n M) = M := begin simp only [inv_fun, alg_hom.map_sum, std_basis_matrix, apply_ite ⇑(algebra_map R A), mul_boole, to_fun_alg_hom_apply, ring_hom.map_zero, ring_hom.map_one], convert finset.sum_product, apply matrix_eq_sum_std_basis, end lemma left_inv (M : A ⊗[R] matrix n n R) : inv_fun R A n (to_fun_alg_hom R A n M) = M := begin apply tensor_product.induction_on _ _ M, { simp, }, { intros a m, simp, }, { intros x y hx hy, simp [alg_hom.map_sum, hx, hy], }, end /-- (Implementation detail) The equivalence, ignoring the algebra structure, `(A ⊗[R] matrix n n R) ≃ matrix n n A`. -/ def equiv : (A ⊗[R] matrix n n R) ≃ matrix n n A := { to_fun := to_fun_alg_hom R A n, inv_fun := inv_fun R A n, left_inv := left_inv R A n, right_inv := right_inv R A n, } end matrix_equiv_tensor variables [decidable_eq n] /-- The `R`-algebra isomorphism `matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R)`. -/ def matrix_equiv_tensor : matrix n n A ≃ₐ[R] (A ⊗[R] matrix n n R) := alg_equiv.symm { ..(matrix_equiv_tensor.to_fun_alg_hom R A n), ..(matrix_equiv_tensor.equiv R A n) } open matrix_equiv_tensor @[simp] lemma matrix_equiv_tensor_apply (M : matrix n n A) : matrix_equiv_tensor R A n M = ∑ (p : n × n), M p.1 p.2 ⊗ₜ (std_basis_matrix p.1 p.2 1) := rfl @[simp] lemma matrix_equiv_tensor_apply_std_basis (i j : n) (x : A): matrix_equiv_tensor R A n (std_basis_matrix i j x) = x ⊗ₜ (std_basis_matrix i j 1) := begin have t : ∀ (p : n × n), (p.1 = i ∧ p.2 = j) ↔ (p = (i, j)) := by tidy, simp [ite_tmul, t, std_basis_matrix], end @[simp] lemma matrix_equiv_tensor_apply_symm (a : A) (M : matrix n n R) : (matrix_equiv_tensor R A n).symm (a ⊗ₜ M) = λ i j, a * algebra_map R A (M i j) := begin simp [matrix_equiv_tensor, to_fun_alg_hom, alg_hom_of_linear_map_tensor_product, to_fun_linear], refl, end
70ca8aceacc3e767e53d1b88e8098c52186b8db0
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/algebra/ordered_field.lean
5ef266be28932f70c2777fcf8faac22891b4602b
[ "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
9,573
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.ordered_ring algebra.field section linear_ordered_field variables {α : Type*} [linear_ordered_field α] {a b c d : α} def div_pos := @div_pos_of_pos_of_pos lemma inv_pos {a : α} : 0 < a → 0 < a⁻¹ := by rw [inv_eq_one_div]; exact div_pos zero_lt_one lemma inv_lt_zero {a : α} : a < 0 → a⁻¹ < 0 := by rw [inv_eq_one_div]; exact div_neg_of_pos_of_neg zero_lt_one lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := ⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩ lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a := ⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩ lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb) lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b := lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb) lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := ⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩ lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩ lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg _ (ne_of_gt (neg_pos.2 hc)), le_neg, div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := ⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [inv_eq_one_div, div_le_iff ha, ← div_eq_inv_mul, one_le_div_iff_le hb] lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos ha), division_ring.inv_inv (ne_of_gt ha)] lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos hb) ha, division_ring.inv_inv (ne_of_gt hb)] lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div_eq_inv] using inv_le_inv ha hb lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha) def div_nonneg := @div_nonneg_of_nonneg_of_pos lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc), λ h, div_lt_div_of_lt_of_pos h hc⟩ lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc) lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := ⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc), λ h, div_lt_div_of_lt_of_neg h hc⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc) lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := (mul_lt_mul_left ha).trans (inv_lt_inv hb hc) lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0) lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one def half_lt_self := @div_two_lt_of_pos lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma ivl_translate : (λx, x + c) '' {r:α | a ≤ r ∧ r ≤ b } = {r:α | a + c ≤ r ∧ r ≤ b + c} := calc (λx, x + c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x - c) ⁻¹' {r | a ≤ r ∧ r ≤ b } : congr_fun (set.image_eq_preimage_of_inverse (assume a, add_sub_cancel a c) (assume b, sub_add_cancel b c)) _ ... = {r | a + c ≤ r ∧ r ≤ b + c} : set.ext $ by simp [-sub_eq_add_neg, le_sub_iff_add_le, sub_le_iff_le_add] lemma ivl_stretch (hc : 0 < c) : (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = {r | a * c ≤ r ∧ r ≤ b * c} := calc (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x / c) ⁻¹' {r | a ≤ r ∧ r ≤ b } : congr_fun (set.image_eq_preimage_of_inverse (assume a, mul_div_cancel _ $ ne_of_gt hc) (assume b, div_mul_cancel _ $ ne_of_gt hc)) _ ... = {r | a * c ≤ r ∧ r ≤ b * c} : set.ext $ by simp [le_div_iff, div_le_iff, hc] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos, calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos ... = a₂ : add_self_div_two a₂⟩ } instance linear_ordered_field.to_no_top_order : no_top_order α := { no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ } instance linear_ordered_field.to_no_bot_order : no_bot_order α := { no_bot := assume a, ⟨a + -1, add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ } lemma inv_lt_one {a : α} (ha : 1 < a) : a⁻¹ < 1 := by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *) lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂] lemma inv_le_one {a : α} (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *) lemma one_le_inv {x : α} (hx0 : 0 < x) (hx : x ≤ 1) : 1 ≤ x⁻¹ := le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt hx0))]) hx0 lemma mul_self_inj_of_nonneg {a b : α} (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := (mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $ λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero] lemma div_le_div_of_le_left {a b c : α} (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then by simp [ha0] else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) (lt_of_lt_of_le hc h) hc).2 h end linear_ordered_field namespace nat variables {α : Type*} [linear_ordered_field α] lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div_eq_inv, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end nat section variables {α : Type*} [discrete_linear_ordered_field α] (a b c : α) lemma inv_pos' {a : α} : 0 < a⁻¹ ↔ 0 < a := ⟨by rw [inv_eq_one_div]; exact pos_of_one_div_pos, inv_pos⟩ lemma inv_neg' {a : α} : a⁻¹ < 0 ↔ a < 0 := ⟨by rw [inv_eq_one_div]; exact neg_of_one_div_neg, inv_lt_zero⟩ lemma inv_nonneg {a : α} : 0 ≤ a⁻¹ ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 inv_neg' lemma inv_nonpos {a : α} : a⁻¹ ≤ 0 ↔ a ≤ 0 := le_iff_le_iff_lt_iff_lt.2 inv_pos' lemma abs_inv : abs a⁻¹ = (abs a)⁻¹ := have h : abs (1 / a) = 1 / abs a, begin rw [abs_div, abs_of_nonneg], exact zero_le_one end, by simp [*] at * lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := if h : a = 0 then by simp [h, inv_zero] else by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma inv_le_inv_of_le {a b : α} (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ := begin rw [inv_eq_one_div, inv_eq_one_div], exact one_div_le_one_div_of_le hb h end lemma div_nonneg' {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := (lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm]) end
49bfb7149404591f46001f3ffe4e98acd919d176
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/set_theory/game.lean
7eee7eadf242df6987a928e55fc622a585ca08fa
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
5,378
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import set_theory.pgame /-! # Combinatorial games. In this file we define the quotient of pre-games by the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`, and construct an instance `add_comm_group game`, as well as an instance `partial_order game` (although note carefully the warning that the `<` field in this instance is not the usual relation on combinatorial games). -/ universes u local infix ` ≈ ` := pgame.equiv instance pgame.setoid : setoid pgame := ⟨λ x y, x ≈ y, λ x, pgame.equiv_refl _, λ x y, pgame.equiv_symm, λ x y z, pgame.equiv_trans⟩ /-- The type of combinatorial games. In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a combinatorial pre-game is built inductively from two families of combinatorial games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. A combinatorial game is then constructed by quotienting by the equivalence `x ≈ y ↔ x ≤ y ∧ y ≤ x`. -/ def game := quotient pgame.setoid open pgame namespace game /-- The relation `x ≤ y` on games. -/ def le : game → game → Prop := quotient.lift₂ (λ x y, x ≤ y) (λ x₁ y₁ x₂ y₂ hx hy, propext (le_congr hx hy)) instance : has_le game := { le := le } @[refl] theorem le_refl : ∀ x : game, x ≤ x := by { rintro ⟨x⟩, apply pgame.le_refl } @[trans] theorem le_trans : ∀ x y z : game, x ≤ y → y ≤ z → x ≤ z := by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩, apply pgame.le_trans } theorem le_antisymm : ∀ x y : game, x ≤ y → y ≤ x → x = y := by { rintro ⟨x⟩ ⟨y⟩ h₁ h₂, apply quot.sound, exact ⟨h₁, h₂⟩ } /-- The relation `x < y` on games. -/ -- We don't yet make this into an instance, because it will conflict with the (incorrect) notion -- of `<` provided by `partial_order` later. def lt : game → game → Prop := quotient.lift₂ (λ x y, x < y) (λ x₁ y₁ x₂ y₂ hx hy, propext (lt_congr hx hy)) theorem not_le : ∀ {x y : game}, ¬ (x ≤ y) ↔ (lt y x) := by { rintro ⟨x⟩ ⟨y⟩, exact not_le } instance : has_zero game := ⟨⟦0⟧⟩ instance : inhabited game := ⟨0⟩ instance : has_one game := ⟨⟦1⟧⟩ /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : game → game := quot.lift (λ x, ⟦-x⟧) (λ x y h, quot.sound (@neg_congr x y h)) instance : has_neg game := { neg := neg } /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ def add : game → game → game := quotient.lift₂ (λ x y : pgame, ⟦x + y⟧) (λ x₁ y₁ x₂ y₂ hx hy, quot.sound (pgame.add_congr hx hy)) instance : has_add game := ⟨add⟩ theorem add_assoc : ∀ (x y z : game), (x + y) + z = x + (y + z) := begin rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, apply quot.sound, exact add_assoc_equiv end instance : add_semigroup game.{u} := { add_assoc := add_assoc, ..game.has_add } theorem add_zero : ∀ (x : game), x + 0 = x := begin rintro ⟨x⟩, apply quot.sound, apply add_zero_equiv end theorem zero_add : ∀ (x : game), 0 + x = x := begin rintro ⟨x⟩, apply quot.sound, apply zero_add_equiv end instance : add_monoid game := { add_zero := add_zero, zero_add := zero_add, ..game.has_zero, ..game.add_semigroup } theorem add_left_neg : ∀ (x : game), (-x) + x = 0 := begin rintro ⟨x⟩, apply quot.sound, apply add_left_neg_equiv end instance : add_group game := { add_left_neg := add_left_neg, ..game.has_neg, ..game.add_monoid } theorem add_comm : ∀ (x y : game), x + y = y + x := begin rintros ⟨x⟩ ⟨y⟩, apply quot.sound, exact add_comm_equiv end instance : add_comm_semigroup game := { add_comm := add_comm, ..game.add_semigroup } instance : add_comm_group game := { ..game.add_comm_semigroup, ..game.add_group } theorem add_le_add_left : ∀ (a b : game), a ≤ b → ∀ (c : game), c + a ≤ c + b := begin rintro ⟨a⟩ ⟨b⟩ h ⟨c⟩, apply pgame.add_le_add_left h, end -- While it is very tempting to define a `partial_order` on games, and prove -- that games form an `ordered_comm_group`, it is a bit dangerous. -- The relations `≤` and `<` on games do not satisfy -- `lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)` -- (Consider `a = 0`, `b = star`.) -- (`lt_iff_le_not_le` is satisfied by surreal numbers, however.) -- Thus we can not use `<` when defining a `partial_order`. -- Because of this issue, we define the `partial_order` and `ordered_comm_group` instances, -- but do not actually mark them as instances, for safety. /-- The `<` operation provided by this partial order is not the usual `<` on games! -/ def game_partial_order : partial_order game := { le_refl := le_refl, le_trans := le_trans, le_antisymm := le_antisymm, ..game.has_le } local attribute [instance] game_partial_order /-- The `<` operation provided by this `ordered_comm_group` is not the usual `<` on games! -/ def ordered_comm_group_game : ordered_comm_group game := ordered_comm_group.mk' add_le_add_left end game
d106221f2ec5647d2c5b54a69cfadb5b0a12e4e3
1136b4d61007050cc632ede270de45a662f8dba4
/library/init/data/nat/basic.lean
2bc927a867c37973127355369860c5cbfdff12a0
[ "Apache-2.0" ]
permissive
zk744750315/lean
7fe895f16cc0ef1869238a01cae903bbd623b4a9
c17e5b913b2db687ab38f53285326b9dbb2b1b6e
refs/heads/master
1,618,208,425,413
1,521,520,544,000
1,521,520,936,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,039
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.logic notation `ℕ` := nat namespace nat inductive less_than_or_equal (a : ℕ) : ℕ → Prop | refl : less_than_or_equal a | step : Π {b}, less_than_or_equal b → less_than_or_equal (succ b) instance : has_le ℕ := ⟨nat.less_than_or_equal⟩ @[reducible] protected def le (n m : ℕ) := nat.less_than_or_equal n m @[reducible] protected def lt (n m : ℕ) := nat.less_than_or_equal (succ n) m instance : has_lt ℕ := ⟨nat.lt⟩ def pred : ℕ → ℕ | 0 := 0 | (a+1) := a protected def sub : ℕ → ℕ → ℕ | a 0 := a | a (b+1) := pred (sub a b) protected def mul : nat → nat → nat | a 0 := 0 | a (b+1) := (mul a b) + a instance : has_sub ℕ := ⟨nat.sub⟩ instance : has_mul ℕ := ⟨nat.mul⟩ instance : decidable_eq ℕ | zero zero := is_true rfl | (succ x) zero := is_false (λ h, nat.no_confusion h) | zero (succ y) := is_false (λ h, nat.no_confusion h) | (succ x) (succ y) := match decidable_eq x y with | is_true xeqy := is_true (xeqy ▸ eq.refl (succ x)) | is_false xney := is_false (λ h, nat.no_confusion h (λ xeqy, absurd xeqy xney)) end def {u} repeat {α : Type u} (f : ℕ → α → α) : ℕ → α → α | 0 a := a | (succ n) a := f n (repeat n a) instance : inhabited ℕ := ⟨nat.zero⟩ @[simp] lemma nat_zero_eq_zero : nat.zero = 0 := rfl /- properties of inequality -/ @[refl] protected def le_refl : ∀ a : ℕ, a ≤ a := less_than_or_equal.refl lemma le_succ (n : ℕ) : n ≤ succ n := less_than_or_equal.step (nat.le_refl n) lemma succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m := λ h, less_than_or_equal.rec (nat.le_refl (succ n)) (λ a b, less_than_or_equal.step) h lemma zero_le : ∀ (n : ℕ), 0 ≤ n | 0 := nat.le_refl 0 | (n+1) := less_than_or_equal.step (zero_le n) lemma zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ (zero_le n) def succ_pos := zero_lt_succ lemma not_succ_le_zero : ∀ (n : ℕ), succ n ≤ 0 → false . lemma not_lt_zero (a : ℕ) : ¬ a < 0 := not_succ_le_zero a lemma pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m := λ h, less_than_or_equal.rec_on h (nat.le_refl (pred n)) (λ n, nat.rec (λ a b, b) (λ a b c, less_than_or_equal.step) n) lemma le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred instance decidable_le : ∀ a b : ℕ, decidable (a ≤ b) | 0 b := is_true (zero_le b) | (a+1) 0 := is_false (not_succ_le_zero a) | (a+1) (b+1) := match decidable_le a b with | is_true h := is_true (succ_le_succ h) | is_false h := is_false (λ a, h (le_of_succ_le_succ a)) end instance decidable_lt : ∀ a b : ℕ, decidable (a < b) := λ a b, nat.decidable_le (succ a) b protected lemma eq_or_lt_of_le {a b : ℕ} (h : a ≤ b) : a = b ∨ a < b := less_than_or_equal.cases_on h (or.inl rfl) (λ n h, or.inr (succ_le_succ h)) lemma lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ @[simp] lemma succ_sub_succ_eq_sub (a b : ℕ) : succ a - succ b = a - b := nat.rec_on b (show succ a - succ zero = a - zero, from (eq.refl (succ a - succ zero))) (λ b, congr_arg pred) lemma not_succ_le_self : ∀ n : ℕ, ¬succ n ≤ n := λ n, nat.rec (not_succ_le_zero 0) (λ a b c, b (le_of_succ_le_succ c)) n protected lemma lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self n protected lemma le_trans {n m k : ℕ} (h1 : n ≤ m) : m ≤ k → n ≤ k := less_than_or_equal.rec h1 (λ p h2, less_than_or_equal.step) lemma pred_le : ∀ (n : ℕ), pred n ≤ n | 0 := less_than_or_equal.refl 0 | (succ a) := less_than_or_equal.step (less_than_or_equal.refl a) lemma pred_lt : ∀ {n : ℕ}, n ≠ 0 → pred n < n | 0 h := absurd rfl h | (succ a) h := lt_succ_of_le (less_than_or_equal.refl _) lemma sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b (nat.le_refl (a - 0)) (λ b₁, nat.le_trans (pred_le (a - b₁))) lemma sub_lt : ∀ {a b : ℕ}, 0 < a → 0 < b → a - b < a | 0 b h1 h2 := absurd h1 (nat.lt_irrefl 0) | (a+1) 0 h1 h2 := absurd h2 (nat.lt_irrefl 0) | (a+1) (b+1) h1 h2 := eq.symm (succ_sub_succ_eq_sub a b) ▸ show a - b < succ a, from lt_succ_of_le (sub_le a b) protected lemma lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans /- Basic nat.add lemmas -/ protected lemma zero_add : ∀ n : ℕ, 0 + n = n | 0 := rfl | (n+1) := congr_arg succ (zero_add n) lemma succ_add : ∀ n m : ℕ, (succ n) + m = succ (n + m) | n 0 := rfl | n (m+1) := congr_arg succ (succ_add n m) lemma add_succ (n m : ℕ) : n + succ m = succ (n + m) := rfl protected lemma add_zero (n : ℕ) : n + 0 = n := rfl lemma add_one (n : ℕ) : n + 1 = succ n := rfl lemma succ_eq_add_one (n : ℕ) : succ n = n + 1 := rfl /- Basic lemmas for comparing numerals -/ protected lemma bit0_succ_eq (n : ℕ) : bit0 (succ n) = succ (succ (bit0 n)) := show succ (succ n + n) = succ (succ (n + n)), from congr_arg succ (succ_add n n) protected lemma zero_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 0 < bit0 n | 0 h := absurd rfl h | (succ n) h := calc 0 < succ (succ (bit0 n)) : zero_lt_succ _ ... = bit0 (succ n) : (nat.bit0_succ_eq n).symm protected lemma zero_lt_bit1 (n : nat) : 0 < bit1 n := zero_lt_succ _ protected lemma bit0_ne_zero : ∀ {n : ℕ}, n ≠ 0 → bit0 n ≠ 0 | 0 h := absurd rfl h | (n+1) h := suffices (n+1) + (n+1) ≠ 0, from this, suffices succ ((n+1) + n) ≠ 0, from this, λ h, nat.no_confusion h protected lemma bit1_ne_zero (n : ℕ) : bit1 n ≠ 0 := show succ (n + n) ≠ 0, from λ h, nat.no_confusion h /- Exponentiation -/ def pow (b : ℕ) : ℕ → ℕ | 0 := 1 | (succ n) := pow n * b infix `^` := pow lemma pow_succ (b n : ℕ) : b^(succ n) = b^n * b := rfl @[simp] lemma pow_zero (b : ℕ) : b^0 = 1 := rfl end nat
30e3ecb96f81510811a1a0430987066979cc5e86
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/to_semiring.lean
4f14ea46f3a112a4163092f5565831e2167be64e
[]
no_license
johoelzl/mason-stother
0c78bca183eb729d7f0f93e87ce073bc8cd8808d
573ecfaada288176462c03c87b80ad05bdab4644
refs/heads/master
1,631,751,973,492
1,528,923,934,000
1,528,923,934,000
109,133,224
0
1
null
null
null
null
UTF-8
Lean
false
false
1,380
lean
import data.finsupp import algebra.ring import .to_finset import .to_multiset local infix ^ := monoid.pow universe u variable {α : Type u} variable [semiring α] def associated (x y : α) : Prop:= ∃u : units α, x = u * y local notation a `~ᵤ` b : 50 := associated a b def is_unit (a : α) : Prop := ∃b : units α, a = b /- is used once in UFD, but I don't understand what it does -/ lemma is_unit_unit (u : units α) : @is_unit α _ u := ⟨u, rfl⟩ @[simp] lemma is_unit_one : is_unit (1 : α ) := ⟨1, rfl⟩ --Should I do all these lemmas using the zero_ne_one class? @[simp] lemma not_is_unit_zero (h : (0 : α) ≠ 1) : ¬ is_unit (0 : α) := --Do we need semiring? begin intro h, rcases h with ⟨u, hu⟩, have h2: u.val*u.inv = 1, from u.val_inv, simp [units.val_coe] at *, rw [←hu, _root_.zero_mul] at h2, contradiction, end lemma ne_zero_of_is_unit {a : α} (h : (0 : α) ≠ 1) : is_unit a → a ≠ 0 := begin intros h1 h2, subst h2, exact not_is_unit_zero h h1, end lemma is_unit_mul_of_is_unit_of_is_unit {a b : α} (h1 : is_unit a) (h2 : is_unit b) : is_unit (a * b) := let ⟨aᵤ, ha⟩ := h1 in let ⟨bᵤ, hb⟩ := h2 in ⟨aᵤ*bᵤ, by simp [units.mul_coe, *]⟩ lemma zero_associated_zero : (0 : α) ~ᵤ 0 := ⟨1, by simp⟩ lemma unit_associated_one {u : units α}: (u : α) ~ᵤ 1 := ⟨u, by simp⟩
9fec1420315b4928b6bd88f381f2b455d64834f4
4e3bf8e2b29061457a887ac8889e88fa5aa0e34c
/lean/love05_inductive_predicates_exercise_sheet.lean
adfdf1aadd72bc1bdd720d502625e54bd83d13dd
[]
no_license
mukeshtiwari/logical_verification_2019
9f964c067a71f65eb8884743273fbeef99e6503d
16f62717f55ed5b7b87e03ae0134791a9bef9b9a
refs/heads/master
1,619,158,844,208
1,585,139,500,000
1,585,139,500,000
249,906,380
0
0
null
1,585,118,728,000
1,585,118,727,000
null
UTF-8
Lean
false
false
1,804
lean
/- LoVe Exercise 5: Inductive Predicates -/ import .love05_inductive_predicates_demo namespace LoVe /- Question 1: Even and Odd -/ /- The `even` predicate is true for even numbers and false for odd numbers. -/ #check even /- 1.1. Prove that 0, 2, 4, and 6 are even. -/ -- enter your answer here /- We define `odd` as the negation of `even`: -/ def odd (n : ℕ) : Prop := ¬ even n /- 1.2. Prove that 1 is odd and register this fact as a `simp` rule. Hint: `cases` is useful to reason about hypotheses of the form `even …`. -/ @[simp] lemma odd_1 : odd 1 := sorry /- 1.3. Prove that 3, 5, and 7 are odd. -/ -- enter your answer here /- 1.4. Complete the following proof by structural induction. Hint: You can rely implicitly on computation for the induction step. -/ lemma even_two_times : ∀m : ℕ, even (2 * m) := sorry /- 1.5. Complete the following proof by rule induction. Hint: You can use the `cases` tactic (or `match … with`) to destruct an existential quantifier and extract the witness. -/ lemma even_imp_exists_two_times : ∀n : ℕ, even n → ∃m, n = 2 * m | _ even.zero := exists.intro 0 (by simp) | _ (even.add_two n hen) := sorry /- 1.6. Using `even_two_times` and `even_imp_exists_two_times`, prove the following equivalence. -/ lemma even_iff_exists_two_times (n : ℕ) : even n ↔ ∃m, n = 2 * m := sorry /- Question 2: Binary Trees -/ /- 2.1. Prove the converse of `is_full_mirror`. You may exploit already proved lemmas (e.g., `is_full_mirror`, `mirror_mirror`). -/ lemma mirror_is_full {α : Type} : ∀t : btree α, is_full (mirror t) → is_full t := sorry /- 2.2. Define a function that counts the number of constructors (`empty` or `node`) in a tree. -/ def count {α : Type} : btree α → ℕ := sorry end LoVe
b0248fc434b502c2bee51fa10dbe5c1d1e29e818
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/continued_fractions/computation/correctness_terminating.lean
b6ee4ce5c915225bbbfbd3078ca9fc50e187d089
[ "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
12,389
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.translations import algebra.continued_fractions.terminated_stable import algebra.continued_fractions.continuants_recurrence import order.filter.at_top_bot /-! # Correctness of Terminating Continued Fraction Computations (`generalized_continued_fraction.of`) ## Summary We show the correctness of the algorithm computing continued fractions (`generalized_continued_fraction.of`) in case of termination in the following sense: At every step `n : ℕ`, we can obtain the value `v` by adding a specific residual term to the last denominator of the fraction described by `(generalized_continued_fraction.of v).convergents' n`. The residual term will be zero exactly when the continued fraction terminated; otherwise, the residual term will be given by the fractional part stored in `generalized_continued_fraction.int_fract_pair.stream v n`. For an example, refer to `generalized_continued_fraction.comp_exact_value_correctness_of_stream_eq_some` and for more information about the computation process, refer to `algebra.continued_fraction.computation.basic`. ## Main definitions - `generalized_continued_fraction.comp_exact_value` can be used to compute the exact value approximated by the continued fraction `generalized_continued_fraction.of v` by adding a residual term as described in the summary. ## Main Theorems - `generalized_continued_fraction.comp_exact_value_correctness_of_stream_eq_some` shows that `generalized_continued_fraction.comp_exact_value` indeed returns the value `v` when given the convergent and fractional part as described in the summary. - `generalized_continued_fraction.of_correctness_of_terminated_at` shows the equality `v = (generalized_continued_fraction.of v).convergents n` if `generalized_continued_fraction.of v` terminated at position `n`. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {K : Type*} [linear_ordered_field K] {v : K} {n : ℕ} /-- Given two continuants `pconts` and `conts` and a value `fr`, this function returns - `conts.a / conts.b` if `fr = 0` - `exact_conts.a / exact_conts.b` where `exact_conts = next_continuants 1 fr⁻¹ pconts conts` otherwise. This function can be used to compute the exact value approxmated by a continued fraction `generalized_continued_fraction.of v` as described in lemma `comp_exact_value_correctness_of_stream_eq_some`. -/ protected def comp_exact_value (pconts conts : gcf.pair K) (fr : K) : K := -- if the fractional part is zero, we exactly approximated the value by the last continuants if fr = 0 then conts.a / conts.b -- otherwise, we have to include the fractional part in a final continuants step. else let exact_conts := next_continuants 1 fr⁻¹ pconts conts in exact_conts.a / exact_conts.b variable [floor_ring K] /-- Just a computational lemma we need for the next main proof. -/ protected lemma comp_exact_value_correctness_of_stream_eq_some_aux_comp {a : K} (b c : K) (fract_a_ne_zero : int.fract a ≠ 0) : ((⌊a⌋ : K) * b + c) / (int.fract a) + b = (b * a + c) / int.fract a := by { field_simp [fract_a_ne_zero], rw int.fract, ring } open generalized_continued_fraction as gcf /-- Shows the correctness of `comp_exact_value` in case the continued fraction `generalized_continued_fraction.of v` did not terminate at position `n`. That is, we obtain the value `v` if we pass the two successive (auxiliary) continuants at positions `n` and `n + 1` as well as the fractional part at `int_fract_pair.stream n` to `comp_exact_value`. The correctness might be seen more readily if one uses `convergents'` to evaluate the continued fraction. Here is an example to illustrate the idea: Let `(v : ℚ) := 3.4`. We have - `generalized_continued_fraction.int_fract_pair.stream v 0 = some ⟨3, 0.4⟩`, and - `generalized_continued_fraction.int_fract_pair.stream v 1 = some ⟨2, 0.5⟩`. Now `(generalized_continued_fraction.of v).convergents' 1 = 3 + 1/2`, and our fractional term at position `2` is `0.5`. We hence have `v = 3 + 1/(2 + 0.5) = 3 + 1/2.5 = 3.4`. This computation corresponds exactly to the one using the recurrence equation in `comp_exact_value`. -/ lemma comp_exact_value_correctness_of_stream_eq_some : ∀ {ifp_n : int_fract_pair K}, int_fract_pair.stream v n = some ifp_n → v = gcf.comp_exact_value ((gcf.of v).continuants_aux n) ((gcf.of v).continuants_aux $ n + 1) ifp_n.fr := begin let g := gcf.of v, induction n with n IH, { assume ifp_zero stream_zero_eq, -- nat.zero have : int_fract_pair.of v = ifp_zero, by { have : int_fract_pair.stream v 0 = some (int_fract_pair.of v), from rfl, simpa only [this] using stream_zero_eq }, cases this, cases decidable.em (int.fract v = 0) with fract_eq_zero fract_ne_zero, -- int.fract v = 0; we must then have `v = ⌊v⌋` { suffices : v = ⌊v⌋, by simpa [continuants_aux, fract_eq_zero, gcf.comp_exact_value], calc v = int.fract v + ⌊v⌋ : by rw int.fract_add_floor ... = ⌊v⌋ : by simp [fract_eq_zero] }, -- int.fract v ≠ 0; the claim then easily follows by unfolding a single computation step { field_simp [continuants_aux, next_continuants, next_numerator, next_denominator, gcf.of_h_eq_floor, gcf.comp_exact_value, fract_ne_zero] } }, { assume ifp_succ_n succ_nth_stream_eq, -- nat.succ obtain ⟨ifp_n, nth_stream_eq, nth_fract_ne_zero, -⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, -- introduce some notation let conts := g.continuants_aux (n + 2), set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, cases decidable.em (ifp_succ_n.fr = 0) with ifp_succ_n_fr_eq_zero ifp_succ_n_fr_ne_zero, -- ifp_succ_n.fr = 0 { suffices : v = conts.a / conts.b, by simpa [gcf.comp_exact_value, ifp_succ_n_fr_eq_zero], -- use the IH and the fact that ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ to prove this case obtain ⟨ifp_n', nth_stream_eq', ifp_n_fract_inv_eq_floor⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋, from int_fract_pair.exists_succ_nth_stream_of_fr_zero succ_nth_stream_eq ifp_succ_n_fr_eq_zero, have : ifp_n' = ifp_n, by injection (eq.trans (nth_stream_eq').symm nth_stream_eq), cases this, have s_nth_eq : g.s.nth n = some ⟨1, ⌊ifp_n.fr⁻¹⌋⟩, from gcf.nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero nth_stream_eq nth_fract_ne_zero, rw [←ifp_n_fract_inv_eq_floor] at s_nth_eq, suffices : v = gcf.comp_exact_value ppconts pconts ifp_n.fr, by simpa [conts, continuants_aux, s_nth_eq,gcf.comp_exact_value, nth_fract_ne_zero] using this, exact (IH nth_stream_eq) }, -- ifp_succ_n.fr ≠ 0 { -- use the IH to show that the following equality suffices suffices : gcf.comp_exact_value ppconts pconts ifp_n.fr = gcf.comp_exact_value pconts conts ifp_succ_n.fr, by { have : v = gcf.comp_exact_value ppconts pconts ifp_n.fr, from IH nth_stream_eq, conv_lhs { rw this }, assumption }, -- get the correspondence between ifp_n and ifp_succ_n obtain ⟨ifp_n', nth_stream_eq', ifp_n_fract_ne_zero, ⟨refl⟩⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, have : ifp_n' = ifp_n, by injection (eq.trans (nth_stream_eq').symm nth_stream_eq), cases this, -- get the correspondence between ifp_n and g.s.nth n have s_nth_eq : g.s.nth n = some ⟨1, (⌊ifp_n.fr⁻¹⌋ : K)⟩, from gcf.nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero nth_stream_eq ifp_n_fract_ne_zero, -- the claim now follows by unfolding the definitions and tedious calculations -- some shorthand notation let ppA := ppconts.a, let ppB := ppconts.b, let pA := pconts.a, let pB := pconts.b, have : gcf.comp_exact_value ppconts pconts ifp_n.fr = (ppA + ifp_n.fr⁻¹ * pA) / (ppB + ifp_n.fr⁻¹ * pB), by -- unfold comp_exact_value and the convergent computation once { field_simp [ifp_n_fract_ne_zero, gcf.comp_exact_value, next_continuants, next_numerator, next_denominator], ac_refl }, rw this, -- two calculations needed to show the claim have tmp_calc := gcf.comp_exact_value_correctness_of_stream_eq_some_aux_comp pA ppA ifp_succ_n_fr_ne_zero, have tmp_calc' := gcf.comp_exact_value_correctness_of_stream_eq_some_aux_comp pB ppB ifp_succ_n_fr_ne_zero, rw inv_eq_one_div at tmp_calc tmp_calc', have : int.fract (1 / ifp_n.fr) ≠ 0, by simpa using ifp_succ_n_fr_ne_zero, -- now unfold the recurrence one step and simplify both sides to arrive at the conclusion field_simp [conts, gcf.comp_exact_value, (gcf.continuants_aux_recurrence s_nth_eq ppconts_eq pconts_eq), next_continuants, next_numerator, next_denominator, this, tmp_calc, tmp_calc'], ac_refl } } end /-- The convergent of `generalized_continued_fraction.of v` at step `n - 1` is exactly `v` if the `int_fract_pair.stream` of the corresponding continued fraction terminated at step `n`. -/ lemma of_correctness_of_nth_stream_eq_none (nth_stream_eq_none : int_fract_pair.stream v n = none) : v = (gcf.of v).convergents (n - 1) := begin induction n with n IH, case nat.zero { contradiction }, -- int_fract_pair.stream v 0 ≠ none case nat.succ { rename nth_stream_eq_none succ_nth_stream_eq_none, let g := gcf.of v, change v = g.convergents n, have : int_fract_pair.stream v n = none ∨ ∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0, from int_fract_pair.succ_nth_stream_eq_none_iff.elim_left succ_nth_stream_eq_none, rcases this with ⟨nth_stream_eq_none⟩ | ⟨ifp_n, nth_stream_eq, nth_stream_fr_eq_zero⟩, { cases n with n', { contradiction }, -- int_fract_pair.stream v 0 ≠ none { have : g.terminated_at n', from gcf.of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right nth_stream_eq_none, have : g.convergents (n' + 1) = g.convergents n', from gcf.convergents_stable_of_terminated n'.le_succ this, rw this, exact (IH nth_stream_eq_none) } }, { simpa [nth_stream_fr_eq_zero, gcf.comp_exact_value] using (comp_exact_value_correctness_of_stream_eq_some nth_stream_eq) } } end /-- If `generalized_continued_fraction.of v` terminated at step `n`, then the `n`th convergent is exactly `v`. -/ theorem of_correctness_of_terminated_at (terminated_at_n : (gcf.of v).terminated_at n) : v = (gcf.of v).convergents n := have int_fract_pair.stream v (n + 1) = none, from gcf.of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_left terminated_at_n, of_correctness_of_nth_stream_eq_none this /-- If `generalized_continued_fraction.of v` terminates, then there is `n : ℕ` such that the `n`th convergent is exactly `v`. -/ lemma of_correctness_of_terminates (terminates : (gcf.of v).terminates) : ∃ (n : ℕ), v = (gcf.of v).convergents n := exists.elim terminates ( assume n terminated_at_n, exists.intro n (of_correctness_of_terminated_at terminated_at_n) ) open filter /-- If `generalized_continued_fraction.of v` terminates, then its convergents will eventually always be `v`. -/ lemma of_correctness_at_top_of_terminates (terminates : (gcf.of v).terminates) : ∀ᶠ n in at_top, v = (gcf.of v).convergents n := begin rw eventually_at_top, obtain ⟨n, terminated_at_n⟩ : ∃ n, (gcf.of v).terminated_at n, from terminates, use n, assume m m_geq_n, rw (gcf.convergents_stable_of_terminated m_geq_n terminated_at_n), exact of_correctness_of_terminated_at terminated_at_n end end generalized_continued_fraction
fbf6f2baed68a9de913e85b6da201c70e2a247f4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/convex/combination.lean
8aac405b7832b7b9716eb388f78bbc01a0181976
[ "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
22,181
lean
/- Copyright (c) 2019 Yury Kudriashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudriashov -/ import algebra.big_operators.order import analysis.convex.hull import linear_algebra.affine_space.basis /-! # Convex combinations This file defines convex combinations of points in a vector space. ## Main declarations * `finset.center_mass`: Center of mass of a finite family of points. ## Implementation notes We divide by the sum of the weights in the definition of `finset.center_mass` because of the way mathematical arguments go: one doesn't change weights, but merely adds some. This also makes a few lemmas unconditional on the sum of the weights being `1`. -/ open set function open_locale big_operators classical pointwise universes u u' variables {R E F ι ι' α : Type*} [linear_ordered_field R] [add_comm_group E] [add_comm_group F] [linear_ordered_add_comm_group α] [module R E] [module R F] [module R α] [ordered_smul R α] {s : set E} /-- Center of mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ def finset.center_mass (t : finset ι) (w : ι → R) (z : ι → E) : E := (∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i) variables (i j : ι) (c : R) (t : finset ι) (w : ι → R) (z : ι → E) open finset lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) : (insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i + ((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul], congr' 2, rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] end lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) : t.center_mass w z = ∑ i in t, w i • z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → R) (zs : ι → E) (wt : ι' → R) (zt : ι' → E) (hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : R) (hab : a + b = 1) : a • s.center_mass ws zs + b • t.center_mass wt zt = (s.disj_sum t).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → R) (z : ι → E) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : R) (hab : a + b = 1) : a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then (1 : R) else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity ∑ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' namespace finset lemma center_mass_le_sup {s : finset ι} {f : ι → α} {w : ι → R} (hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : 0 < ∑ i in s, w i) : s.center_mass w f ≤ s.sup' (nonempty_of_ne_empty $ by { rintro rfl, simpa using hw₁ }) f := begin rw [center_mass, inv_smul_le_iff hw₁, sum_smul], exact sum_le_sum (λ i hi, smul_le_smul_of_nonneg (le_sup' _ hi) $ hw₀ i hi), apply_instance, end lemma inf_le_center_mass {s : finset ι} {f : ι → α} {w : ι → R} (hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : 0 < ∑ i in s, w i) : s.inf' (nonempty_of_ne_empty $ by { rintro rfl, simpa using hw₁ }) f ≤ s.center_mass w f := @center_mass_le_sup R _ αᵒᵈ _ _ _ _ _ _ _ hw₀ hw₁ end finset variable {z} /-- The center of mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex R s) : (∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros h₀ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : ∑ j in t, w j = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex R s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) : ∑ i in t, w i • z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz /-- A version of `convex.sum_mem` for `finsum`s. If `s` is a convex set, `w : ι → R` is a family of nonnegative weights with sum one and `z : ι → E` is a family of elements of a module over `R` such that `z i ∈ s` whenever `w i ≠ 0``, then the sum `∑ᶠ i, w i • z i` belongs to `s`. See also `partition_of_unity.finsum_smul_mem_convex`. -/ lemma convex.finsum_mem {ι : Sort*} {w : ι → R} {z : ι → E} {s : set E} (hs : convex R s) (h₀ : ∀ i, 0 ≤ w i) (h₁ : ∑ᶠ i, w i = 1) (hz : ∀ i, w i ≠ 0 → z i ∈ s) : ∑ᶠ i, w i • z i ∈ s := begin have hfin_w : (support (w ∘ plift.down)).finite, { by_contra H, rw [finsum, dif_neg H] at h₁, exact zero_ne_one h₁ }, have hsub : support ((λ i, w i • z i) ∘ plift.down) ⊆ hfin_w.to_finset, from (support_smul_subset_left _ _).trans hfin_w.coe_to_finset.ge, rw [finsum_eq_sum_plift_of_support_subset hsub], refine hs.sum_mem (λ _ _, h₀ _) _ (λ i hi, hz _ _), { rwa [finsum, dif_pos hfin_w] at h₁ }, { rwa [hfin_w.mem_to_finset] at hi } end lemma convex_iff_sum_mem : convex R s ↔ (∀ (t : finset E) (w : E → R), (∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x hx y hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → R} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull R s := (convex_convex_hull R s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull R s $ hz i hi) /-- A refinement of `finset.center_mass_mem_convex_hull` when the indexed family is a `finset` of the space. -/ lemma finset.center_mass_id_mem_convex_hull (t : finset E) {w : E → R} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) : t.center_mass w id ∈ convex_hull R (t : set E) := t.center_mass_mem_convex_hull hw₀ hws (λ i, mem_coe.2) lemma affine_combination_eq_center_mass {ι : Type*} {t : finset ι} {p : ι → E} {w : ι → R} (hw₂ : ∑ i in t, w i = 1) : affine_combination t p w = center_mass t w p := begin rw [affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ w _ hw₂ (0 : E), finset.weighted_vsub_of_point_apply, vadd_eq_add, add_zero, t.center_mass_eq_of_sum_1 _ hw₂], simp_rw [vsub_eq_sub, sub_zero], end lemma affine_combination_mem_convex_hull {s : finset ι} {v : ι → E} {w : ι → R} (hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : s.sum w = 1) : s.affine_combination v w ∈ convex_hull R (range v) := begin rw affine_combination_eq_center_mass hw₁, apply s.center_mass_mem_convex_hull hw₀, { simp [hw₁], }, { simp, }, end /-- The centroid can be regarded as a center of mass. -/ @[simp] lemma finset.centroid_eq_center_mass (s : finset ι) (hs : s.nonempty) (p : ι → E) : s.centroid R p = s.center_mass (s.centroid_weights R) p := affine_combination_eq_center_mass (s.sum_centroid_weights_eq_one_of_nonempty R hs) lemma finset.centroid_mem_convex_hull (s : finset E) (hs : s.nonempty) : s.centroid R id ∈ convex_hull R (s : set E) := begin rw s.centroid_eq_center_mass hs, apply s.center_mass_id_mem_convex_hull, { simp only [inv_nonneg, implies_true_iff, nat.cast_nonneg, finset.centroid_weights_apply], }, { have hs_card : (s.card : R) ≠ 0, { simp [finset.nonempty_iff_ne_empty.mp hs] }, simp only [hs_card, finset.sum_const, nsmul_eq_mul, mul_inv_cancel, ne.def, not_false_iff, finset.centroid_weights_apply, zero_lt_one] } end lemma convex_hull_range_eq_exists_affine_combination (v : ι → E) : convex_hull R (range v) = { x | ∃ (s : finset ι) (w : ι → R) (hw₀ : ∀ i ∈ s, 0 ≤ w i) (hw₁ : s.sum w = 1), s.affine_combination v w = x } := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, obtain ⟨i, hi⟩ := set.mem_range.mp hx, refine ⟨{i}, function.const ι (1 : R), by simp, by simp, by simp [hi]⟩, }, { rintro x ⟨s, w, hw₀, hw₁, rfl⟩ y ⟨s', w', hw₀', hw₁', rfl⟩ a b ha hb hab, let W : ι → R := λ i, (if i ∈ s then a * w i else 0) + (if i ∈ s' then b * w' i else 0), have hW₁ : (s ∪ s').sum W = 1, { rw [sum_add_distrib, ← sum_subset (subset_union_left s s'), ← sum_subset (subset_union_right s s'), sum_ite_of_true _ _ (λ i hi, hi), sum_ite_of_true _ _ (λ i hi, hi), ← mul_sum, ← mul_sum, hw₁, hw₁', ← add_mul, hab, mul_one]; intros i hi hi'; simp [hi'], }, refine ⟨s ∪ s', W, _, hW₁, _⟩, { rintros i -, by_cases hi : i ∈ s; by_cases hi' : i ∈ s'; simp [hi, hi', add_nonneg, mul_nonneg ha (hw₀ i _), mul_nonneg hb (hw₀' i _)], }, { simp_rw [affine_combination_eq_linear_combination (s ∪ s') v _ hW₁, affine_combination_eq_linear_combination s v w hw₁, affine_combination_eq_linear_combination s' v w' hw₁', add_smul, sum_add_distrib], rw [← sum_subset (subset_union_left s s'), ← sum_subset (subset_union_right s s')], { simp only [ite_smul, sum_ite_of_true _ _ (λ i hi, hi), mul_smul, ← smul_sum], }, { intros i hi hi', simp [hi'], }, { intros i hi hi', simp [hi'], }, }, }, { rintros x ⟨s, w, hw₀, hw₁, rfl⟩, exact affine_combination_mem_convex_hull hw₀ hw₁, }, end /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull R s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → R) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s), t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ y ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_disj_sum] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *], }, { intros i hi, rw [finset.mem_disj_sum] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end lemma finset.convex_hull_eq (s : finset E) : convex_hull R ↑s = {x : E | ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintro x ⟨wx, hwx₀, hwx₁, rfl⟩ y ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, hx) } end lemma finset.mem_convex_hull {s : finset E} {x : E} : x ∈ convex_hull R (s : set E) ↔ ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x := by rw [finset.convex_hull_eq, set.mem_set_of_eq] lemma set.finite.convex_hull_eq {s : set E} (hs : s.finite) : convex_hull R s = {x : E | ∃ (w : E → R) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq /-- A weak version of Carathéodory's theorem. -/ lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull R s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull R ↑t := begin refine subset.antisymm _ _, { rw convex_hull_eq, rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [coe_image, set.image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hw₀, { simp only [hw₁, zero_lt_one] }, { exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (λ i, Union_subset convex_hull_mono), }, end lemma mk_mem_convex_hull_prod {t : set F} {x : E} {y : F} (hx : x ∈ convex_hull R s) (hy : y ∈ convex_hull R t) : (x, y) ∈ convex_hull R (s ×ˢ t) := begin rw convex_hull_eq at ⊢ hx hy, obtain ⟨ι, a, w, S, hw, hw', hS, hSp⟩ := hx, obtain ⟨κ, b, v, T, hv, hv', hT, hTp⟩ := hy, have h_sum : ∑ (i : ι × κ) in a ×ˢ b, w i.fst * v i.snd = 1, { rw [finset.sum_product, ← hw'], congr, ext i, have : ∑ (y : κ) in b, w i * v y = ∑ (y : κ) in b, v y * w i, { congr, ext, simp [mul_comm] }, rw [this, ← finset.sum_mul, hv'], simp }, refine ⟨ι × κ, a ×ˢ b, λ p, (w p.1) * (v p.2), λ p, (S p.1, T p.2), λ p hp, _, h_sum, λ p hp, _, _⟩, { rw mem_product at hp, exact mul_nonneg (hw p.1 hp.1) (hv p.2 hp.2) }, { rw mem_product at hp, exact ⟨hS p.1 hp.1, hT p.2 hp.2⟩ }, ext, { rw [←hSp, finset.center_mass_eq_of_sum_1 _ _ hw', finset.center_mass_eq_of_sum_1 _ _ h_sum], simp_rw [prod.fst_sum, prod.smul_mk], rw finset.sum_product, congr, ext i, have : ∑ (j : κ) in b, (w i * v j) • S i = ∑ (j : κ) in b, v j • w i • S i, { congr, ext, rw [mul_smul, smul_comm] }, rw [this, ←finset.sum_smul, hv', one_smul] }, { rw [←hTp, finset.center_mass_eq_of_sum_1 _ _ hv', finset.center_mass_eq_of_sum_1 _ _ h_sum], simp_rw [prod.snd_sum, prod.smul_mk], rw [finset.sum_product, finset.sum_comm], congr, ext j, simp_rw mul_smul, rw [←finset.sum_smul, hw', one_smul] } end @[simp] lemma convex_hull_prod (s : set E) (t : set F) : convex_hull R (s ×ˢ t) = convex_hull R s ×ˢ convex_hull R t := subset.antisymm (convex_hull_min (prod_mono (subset_convex_hull _ _) $ subset_convex_hull _ _) $ (convex_convex_hull _ _).prod $ convex_convex_hull _ _) $ prod_subset_iff.2 $ λ x hx y, mk_mem_convex_hull_prod hx lemma convex_hull_add (s t : set E) : convex_hull R (s + t) = convex_hull R s + convex_hull R t := by simp_rw [←image2_add, ←image_prod, is_linear_map.is_linear_map_add.convex_hull_image, convex_hull_prod] lemma convex_hull_sub (s t : set E) : convex_hull R (s - t) = convex_hull R s - convex_hull R t := by simp_rw [sub_eq_add_neg, convex_hull_add, convex_hull_neg] /-! ### `std_simplex` -/ variables (ι) [fintype ι] {f : ι → R} /-- `std_simplex 𝕜 ι` is the convex hull of the canonical basis in `ι → 𝕜`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull R (range $ λ(i j:ι), if i = j then (1:R) else 0) = std_simplex R ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex R ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex R i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : s.finite) : convex_hull R s = by haveI := hs.fintype; exact (⇑(∑ x : s, (@linear_map.proj R s _ (λ i, R) _ _ x).smul_right x.1)) '' (std_simplex R s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex 𝕜 ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex R ι) (x) : f x ∈ Icc (0 : R) 1 := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ /-- The convex hull of an affine basis is the intersection of the half-spaces defined by the corresponding barycentric coordinates. -/ lemma convex_hull_affine_basis_eq_nonneg_barycentric {ι : Type*} (b : affine_basis ι R E) : convex_hull R (range b.points) = { x | ∀ i, 0 ≤ b.coord i x } := begin rw convex_hull_range_eq_exists_affine_combination, ext x, split, { rintros ⟨s, w, hw₀, hw₁, rfl⟩ i, by_cases hi : i ∈ s, { rw b.coord_apply_combination_of_mem hi hw₁, exact hw₀ i hi, }, { rw b.coord_apply_combination_of_not_mem hi hw₁, }, }, { intros hx, have hx' : x ∈ affine_span R (range b.points), { rw b.tot, exact affine_subspace.mem_top R E x, }, obtain ⟨s, w, hw₁, rfl⟩ := (mem_affine_span_iff_eq_affine_combination R E).mp hx', refine ⟨s, w, _, hw₁, rfl⟩, intros i hi, specialize hx i, rw b.coord_apply_combination_of_mem hi hw₁ at hx, exact hx, }, end
ec2eb824364f42bff5823f28ea8b03450eb4d6f5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/dold_kan/degeneracies.lean
3a831d4e85ee4834262a30dc91d08ccfd4a49ff6
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,992
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.decomposition /-! # Behaviour of P_infty with respect to degeneracies For any `X : simplicial_object C` where `C` is an abelian category, the projector `P_infty : K[X] ⟶ K[X]` is supposed to be the projection on the normalized subcomplex, parallel to the degenerate subcomplex, i.e. the subcomplex generated by the images of all `X.σ i`. In this file, we obtain `degeneracy_comp_P_infty` which states that if `X : simplicial_object C` with `C` a preadditive category, `θ : [n] ⟶ Δ'` is a non injective map in `simplex_category`, then `X.map θ.op ≫ P_infty.f n = 0`. It follows from the more precise statement vanishing statement `σ_comp_P_eq_zero` for the `P q`. -/ open category_theory category_theory.category category_theory.limits category_theory.preadditive opposite open_locale simplicial dold_kan namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] lemma higher_faces_vanish.comp_σ {Y : C} {X : simplicial_object C} {n b q : ℕ} {φ : Y ⟶ X _[n+1]} (v : higher_faces_vanish q φ) (hnbq : n + 1 = b + q) : higher_faces_vanish q (φ ≫ X.σ ⟨b, by simpa only [hnbq, nat.lt_succ_iff, le_add_iff_nonneg_right] using zero_le q⟩) := λ j hj, begin rw [assoc, simplicial_object.δ_comp_σ_of_gt', fin.pred_succ, v.comp_δ_eq_zero_assoc _ _ hj, zero_comp], { intro hj', simpa only [hj', hnbq, fin.coe_zero, zero_add, add_comm b, add_assoc, false_and, add_le_iff_nonpos_right, le_zero_iff, add_eq_zero_iff, nat.one_ne_zero] using hj, }, { simp only [fin.lt_iff_coe_lt_coe, nat.lt_iff_add_one_le, fin.succ_mk, fin.coe_mk, fin.coe_succ, add_le_add_iff_right], linarith, }, end lemma σ_comp_P_eq_zero (X : simplicial_object C) {n q : ℕ} (i : fin (n + 1)) (hi : n + 1 ≤ i + q) : (X.σ i) ≫ (P q).f (n + 1) = 0 := begin induction q with q hq generalizing i hi, { exfalso, have h := fin.is_lt i, linarith, }, { by_cases n+1 ≤ (i : ℕ) + q, { unfold P, simp only [homological_complex.comp_f, ← assoc], rw [hq i h, zero_comp], }, { have hi' : n = (i : ℕ) + q, { cases le_iff_exists_add.mp hi with j hj, rw [← nat.lt_succ_iff, nat.succ_eq_add_one, add_assoc, hj, not_lt, add_le_iff_nonpos_right, nonpos_iff_eq_zero] at h, rw [← add_left_inj 1, add_assoc, hj, self_eq_add_right, h], }, cases n, { fin_cases i, rw [show q = 0, by linarith], unfold P, simp only [id_comp, homological_complex.add_f_apply, comp_add, homological_complex.id_f, Hσ, homotopy.null_homotopic_map'_f (c_mk 2 1 rfl) (c_mk 1 0 rfl), alternating_face_map_complex.obj_d_eq], erw [hσ'_eq' (zero_add 0).symm, hσ'_eq' (add_zero 1).symm, comp_id, fin.sum_univ_two, fin.sum_univ_succ, fin.sum_univ_two], simp only [pow_zero, pow_one, pow_two, fin.coe_zero, fin.coe_one, fin.coe_two, one_zsmul, neg_zsmul, fin.mk_zero, fin.mk_one, fin.coe_succ, pow_add, one_mul, neg_mul, neg_neg, fin.succ_zero_eq_one, fin.succ_one_eq_two, comp_neg, neg_comp, add_comp, comp_add], erw [simplicial_object.δ_comp_σ_self, simplicial_object.δ_comp_σ_self_assoc, simplicial_object.δ_comp_σ_succ, comp_id, simplicial_object.δ_comp_σ_of_le X (show (0 : fin(2)) ≤ fin.cast_succ 0, by rw fin.cast_succ_zero), simplicial_object.δ_comp_σ_self_assoc, simplicial_object.δ_comp_σ_succ_assoc], abel, }, { rw [← id_comp (X.σ i), ← (P_add_Q_f q n.succ : _ = 𝟙 (X.obj _)), add_comp, add_comp], have v : higher_faces_vanish q ((P q).f n.succ ≫ X.σ i) := (higher_faces_vanish.of_P q n).comp_σ hi', unfold P, erw [← assoc, v.comp_P_eq_self, homological_complex.add_f_apply, preadditive.comp_add, comp_id, v.comp_Hσ_eq hi', assoc, simplicial_object.δ_comp_σ_succ'_assoc, fin.eta, decomposition_Q n q, sum_comp, sum_comp, finset.sum_eq_zero, add_zero, add_neg_eq_zero], swap, { ext, simp only [fin.coe_mk, fin.coe_succ], }, { intros j hj, simp only [true_and, finset.mem_univ, finset.mem_filter] at hj, simp only [nat.succ_eq_add_one] at hi', obtain ⟨k, hk⟩ := nat.le.dest (nat.lt_succ_iff.mp (fin.is_lt j)), rw add_comm at hk, have hi'' : i = fin.cast_succ ⟨i, by linarith⟩ := by { ext, simp only [fin.cast_succ_mk, fin.eta], }, have eq := hq j.rev.succ begin simp only [← hk, fin.rev_eq j hk.symm, nat.succ_eq_add_one, fin.succ_mk, fin.coe_mk], linarith, end, rw [homological_complex.comp_f, assoc, assoc, assoc, hi'', simplicial_object.σ_comp_σ_assoc, reassoc_of eq, zero_comp, comp_zero, comp_zero, comp_zero], simp only [fin.rev_eq j hk.symm, fin.le_iff_coe_le_coe, fin.coe_mk], linarith, }, }, }, } end @[simp, reassoc] lemma σ_comp_P_infty (X : simplicial_object C) {n : ℕ} (i : fin (n+1)) : (X.σ i) ≫ P_infty.f (n+1) = 0 := begin rw [P_infty_f, σ_comp_P_eq_zero X i], simp only [le_add_iff_nonneg_left, zero_le], end @[reassoc] lemma degeneracy_comp_P_infty (X : simplicial_object C) (n : ℕ) {Δ' : simplex_category} (θ : [n] ⟶ Δ') (hθ : ¬mono θ) : X.map θ.op ≫ P_infty.f n = 0 := begin rw simplex_category.mono_iff_injective at hθ, cases n, { exfalso, apply hθ, intros x y h, fin_cases x, fin_cases y, }, { obtain ⟨i, α, h⟩ := simplex_category.eq_σ_comp_of_not_injective θ hθ, rw [h, op_comp, X.map_comp, assoc, (show X.map (simplex_category.σ i).op = X.σ i, by refl), σ_comp_P_infty, comp_zero], }, end end dold_kan end algebraic_topology
a723921622eb697888508b8c9324ab123e1d0be4
a537b538f2bea3181e24409d8a52590603d1ddd9
/test/rewrite_search_discovery.lean
e1a62664af81ae67de262c7a5a24c3f755245f66
[]
no_license
rwbarton/lean-tidy
6134813ded72b275d19d4d32514dba80c21708e3
fe1125d32adb60decda7a77d0f679614ba9f6fbb
refs/heads/master
1,585,549,718,705
1,538,120,619,000
1,538,120,624,000
150,864,330
0
0
null
1,538,225,790,000
1,538,225,790,000
null
UTF-8
Lean
false
false
4,606
lean
import tidy.rewrite_search open tidy.rewrite_search.metric open tidy.rewrite_search.strategy open tidy.rewrite_search.tracer open tidy.rewrite_search.discovery namespace tidy.rewrite_search.testing @[bundle] meta def algebraic_geometry : bundle := {} private axiom foo : [0] = [1] private axiom bar1 : [1] = [2] private axiom bar2 : [3] = [2] private axiom bar3 : [3] = [4] private def my_example (a : unit) : [[0],[0]] = [[4],[4]] := begin -- These don't work (because they don't know about the lemmas): success_if_fail { rewrite_search }, success_if_fail { rewrite_search_using [`search] }, -- But manually specifying them does: rewrite_search_with [foo, bar1, ← bar2, bar2, ← bar3], end -- Let's add them to the `algebraic_geometry` bundle: attribute [search algebraic_geometry] foo bar1 bar2 bar3 -- Now because they are under the `search xxx` namespace whatever, -- the following "old" thing will succeed private example : [[0],[0]] = [[4],[4]] := begin rewrite_search_using [`search], end -- And manually suggesting the `algebraic_geometry` bundle -- will work too: private example : [[0],[0]] = [[4],[4]] := begin rewrite_search {suggest := [`algebraic_geometry]} end -- Finally (and probably most commonly), you can suggest some number -- of bundles via: @[suggest] meta def my_suggestion := `algebraic_geometry -- or: @[suggest] meta def my_suggestion2 := [`algebraic_geometry, `default] -- The discovery code will accept both a name, or a list of names, -- as tagged with `[suggest]`. -- This is pretty cool, because any number of suggestions will be -- considered and are available to the `rewrite_search`er, not -- just the last one to be tagged `[suggest]` or something. -- -- Also, you can use `local attribute xxx` and imports to constrain -- the scope of where your suggestions apply, just like you were -- doing before with [search] in the category theory library. -- In terms of using `[search xxx]`, the attribute will accept any -- `xxx` which is a bundle which has already been declared as -- `@[bundle]`. You can also leave the `xxx` off and just annotate -- as `@[search]`, which will add the lemma to all of the default -- bundles. At the moment, the list consists of only one bundle, and -- it is called `default`. -- -- Lemmas can be part of multiple bundles too simultanously, either -- with annotations declared in separate places, or in the same place -- via the list syntax: @[search [algebraic_geometry, default]] private axiom bar4 : [3] = [4] -- (Here we add `bar4` to both `algebraic_geometry` and `default` -- at the same time.) -- When `rewrite_search` goes to run, it does not do several ugly -- attribute lookups over all bundles, and then all of their children. -- Instead, all of the membership is cached at *parse* time via -- some tricky (if I do say so myself ;)) hiding and updating of -- mutable state in annotations. In fact, we even cache the -- resolved names of which bundles you refer to when you annotate -- with `@[suggest]` (and then forget this state when you go out -- of scope). -- The idea is to have builtin bundles under -- -- tidy.rewrite_search.discovery.bundles -- -- which are imported everytime you include -- -- tidy.rewrite_search -- -- but as you can see, anyone can create one or modify an existing one -- on the fly. -- One more thing: the bundle names ARE NOT the names of objects -- declared of type bundle. They are anything you want, and can -- choosen as you like: @[bundle] meta def scotts_fave_bundle : bundle := {name := `the_real_name} -- And so this will work: @[search the_real_name] private axiom bar5 : [3] = [4] -- but this will not: -- UNCOMMENT ME -- @[search scotts_fave_bundle] private axiom bar4 : [3] = [4] -- This was intentional, because I didn't want the fully-scoped identifier -- to have to be available and `open`ed, or fully-qualified, when -- you go to write `@[search xxxx]`. -- -- I used some autoparams tricks to default the name of a bundle -- to its "lowest level" identifier (i.e. after the last dot). -- So in practise this means it always gets the name you expect, -- and you don't have to write it. -- We also fail gracefully if you try to break the rules: -- UNCOMMENT ME: -- @[suggest] meta def my_suggestion_rebel : ℕ := 0 -- UNCOMMENT ME: -- @[suggest] meta def my_suggestion_rebel2 : name := `fake_name -- Everything else gracefully handles errors, too: private example : tt := begin -- UNCOMMENT ME: -- rewrite_search {suggest := [`algssebraic_geometry]}, exact dec_trivial end end tidy.rewrite_search.testing
2aa4b3df2c9c3cf1cbd8e66a56915f4a63a9ef63
33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354
/lia/asubst.lean
10ebbb797107eba1f02780adfc215f6a4a85821f
[]
no_license
lclem/cooper
79554e72ced343c64fed24b2d892d24bf9447dfe
812afc6b158821f2e7dac9c91d3b6123c7a19faf
refs/heads/master
1,607,554,257,488
1,578,694,133,000
1,578,694,133,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,677
lean
import .atom open list znum def asubst (i') (ks') : atom → atom | (atom.le i (k::ks)) := atom.le (i - (k * i')) (comp_add (map_mul k ks') ks) | (atom.dvd d i (k::ks)) := atom.dvd d (i + (k * i')) (comp_add (map_mul k ks') ks) | (atom.ndvd d i (k::ks)) := atom.ndvd d (i + (k * i')) (comp_add (map_mul k ks') ks) | a := a meta def aval_subst_iff_tac := `[unfold asubst, unfold atom.eval, rewrite add_assoc, have he : (i' * k + dot_prod (comp_add (map_mul k ks') ks) xs) = (dot_prod (k :: ks) ((i' + dot_prod ks' xs) :: xs)), rw cons_dot_prod_cons_eq, rewrite mul_add, rewrite mul_comm, simp, rewrite comp_add_dot_prod, simp [dot_prod], apply map_mul_dot_prod, rewrite mul_comm at he, rewrite he] meta def aval_subst_iff_aux := `[unfold asubst, unfold atom.eval, repeat {rewrite nil_dot_prod}] lemma aval_subst_iff (i' ks' xs) : ∀ a, (asubst i' ks' a).eval xs ↔ a.eval ((i' + dot_prod ks' xs)::xs) | (atom.le i (k::ks)) := begin unfold asubst, simp, unfold atom.eval, rewrite znum.add_le_iff_le_sub, simp, have he : (i' * k + dot_prod (comp_add (map_mul k ks') ks) xs) = (dot_prod (k :: ks) ((i' + dot_prod ks' xs) :: xs)), { rewrite cons_dot_prod_cons_eq, rewrite mul_add, rewrite mul_comm, simp, rewrite comp_add_dot_prod, simp [dot_prod], apply map_mul_dot_prod }, rewrite mul_comm at he, simp at *, rewrite he end | (atom.dvd d i (k::ks)) := by aval_subst_iff_tac | (atom.ndvd d i (k::ks)) := by aval_subst_iff_tac | (atom.le i []) := by aval_subst_iff_aux | (atom.dvd d i []) := by aval_subst_iff_aux | (atom.ndvd d i []) := by aval_subst_iff_aux
d61d82671e0aa544410201d69d24c58e3b545d09
952248371e69ccae722eb20bfe6815d8641554a8
/src/datatypes/basic.lean
5305895514703f5b2b5d9cc3bc7e5e17e06342bb
[]
no_license
robertylewis/lean_polya
5fd079031bf7114449d58d68ccd8c3bed9bcbc97
1da14d60a55ad6cd8af8017b1b64990fccb66ab7
refs/heads/master
1,647,212,226,179
1,558,108,354,000
1,558,108,354,000
89,933,264
1
2
null
1,560,964,118,000
1,493,650,551,000
Lean
UTF-8
Lean
false
false
250
lean
import data.hash_map data.complex.basic rat_additions def {u v} hash_map.ifind {α : Type u} {β : α → Type v} [decidable_eq α] (m : hash_map α β) (a : α) [inhabited (β a)] : β a := match m.find a with | none := default _ | some b := b end
950c269f75f24140418dc7747591880b3c6f83d1
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Init/Data/Float.lean
ac99122aa68dbb3ef076fc1764ce957f95fcc855
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,409
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.Data.ToString.Basic structure FloatSpec where float : Type val : float lt : float → float → Prop le : float → float → Prop decLt : DecidableRel lt decLe : DecidableRel le -- Just show FloatSpec is inhabited. constant floatSpec : FloatSpec := { float := Unit, val := (), lt := fun _ _ => True, le := fun _ _ => True, decLt := fun _ _ => inferInstanceAs (Decidable True), decLe := fun _ _ => inferInstanceAs (Decidable True) } structure Float where val : floatSpec.float instance : Inhabited Float := ⟨{ val := floatSpec.val }⟩ @[extern "lean_float_of_nat"] constant Float.ofNat : (@& Nat) → Float @[extern c inline "#1 + #2"] constant Float.add : Float → Float → Float @[extern c inline "#1 - #2"] constant Float.sub : Float → Float → Float @[extern c inline "#1 * #2"] constant Float.mul : Float → Float → Float @[extern c inline "#1 / #2"] constant Float.div : Float → Float → Float @[extern c inline "(- #1)"] constant Float.neg : Float → Float set_option bootstrap.gen_matcher_code false def Float.lt : Float → Float → Prop := fun a b => match a, b with | ⟨a⟩, ⟨b⟩ => floatSpec.lt a b def Float.le : Float → Float → Prop := fun a b => floatSpec.le a.val b.val instance : OfNat Float n := ⟨Float.ofNat n⟩ instance : Add Float := ⟨Float.add⟩ instance : Sub Float := ⟨Float.sub⟩ instance : Mul Float := ⟨Float.mul⟩ instance : Div Float := ⟨Float.div⟩ instance : Neg Float := ⟨Float.neg⟩ instance : HasLess Float := ⟨Float.lt⟩ instance : HasLessEq Float := ⟨Float.le⟩ @[extern c inline "#1 == #2"] constant Float.beq (a b : Float) : Bool instance : BEq Float := ⟨Float.beq⟩ @[extern c inline "#1 < #2"] constant Float.decLt (a b : Float) : Decidable (a < b) := match a, b with | ⟨a⟩, ⟨b⟩ => floatSpec.decLt a b @[extern c inline "#1 <= #2"] constant Float.decLe (a b : Float) : Decidable (a ≤ b) := match a, b with | ⟨a⟩, ⟨b⟩ => floatSpec.decLe a b instance floatDecLt (a b : Float) : Decidable (a < b) := Float.decLt a b instance floatDecLe (a b : Float) : Decidable (a ≤ b) := Float.decLe a b @[extern "lean_float_to_string"] constant Float.toString : Float → String @[extern c inline "(uint8_t)#1"] constant Float.toUInt8 : Float → UInt8 @[extern c inline "(uint16_t)#1"] constant Float.toUInt16 : Float → UInt16 @[extern c inline "(uint32_t)#1"] constant Float.toUInt32 : Float → UInt32 @[extern c inline "(uint64_t)#1"] constant Float.toUInt64 : Float → UInt64 @[extern c inline "(size_t)#1"] constant Float.toUSize : Float → USize instance : ToString Float where toString := Float.toString instance : Repr Float where reprPrec n _ := Float.toString n instance : ReprAtom Float := ⟨⟩ abbrev Nat.toFloat (n : Nat) : Float := Float.ofNat n @[extern "sin"] constant Float.sin : Float → Float @[extern "cos"] constant Float.cos : Float → Float @[extern "tan"] constant Float.tan : Float → Float @[extern "asin"] constant Float.asin : Float → Float @[extern "acos"] constant Float.acos : Float → Float @[extern "atan"] constant Float.atan : Float → Float @[extern "atan2"] constant Float.atan2 : Float → Float → Float @[extern "sinh"] constant Float.sinh : Float → Float @[extern "cosh"] constant Float.cosh : Float → Float @[extern "tanh"] constant Float.tanh : Float → Float @[extern "asinh"] constant Float.asinh : Float → Float @[extern "acosh"] constant Float.acosh : Float → Float @[extern "atanh"] constant Float.atanh : Float → Float @[extern "exp"] constant Float.exp : Float → Float @[extern "exp2"] constant Float.exp2 : Float → Float @[extern "log"] constant Float.log : Float → Float @[extern "log2"] constant Float.log2 : Float → Float @[extern "log10"] constant Float.log10 : Float → Float @[extern "pow"] constant Float.pow : Float → Float → Float @[extern "sqrt"] constant Float.sqrt : Float → Float @[extern "cbrt"] constant Float.cbrt : Float → Float instance : Pow Float := ⟨Float.pow⟩ @[extern "lean_float_of_scientific"] constant Float.ofScientific (m : Nat) (s : Bool) (e : Nat) : Float
372d32597107eb2338117e6ab9a1a755b3d4d9e8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/fin/vec_notation.lean
cd64938c565d71ae6180cfa208ef2590ec7919fc
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,809
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.fin.basic import data.list.range import algebra.module.pi /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : fin 4 → α`. Nesting vectors gives a matrix, so `![![a, b], ![c, d]] : fin 2 → fin 2 → α`. Later we will define `matrix m n α` to be `m → n → α`, so the type of `![![a, b], ![c, d]]` can be written as `matrix (fin 2) (fin 2) α`. ## Main definitions * `vec_empty` is the empty vector (or `0` by `n` matrix) `![]` * `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} section matrix_notation /-- `![]` is the vector with no entries. -/ def vec_empty : fin 0 → α := fin_zero_elim /-- `vec_cons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vec_head` and `vec_tail`. The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`. -/ def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α := fin.cons h t notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l /-- `vec_head v` gives the first entry of the vector `v` -/ def vec_head {n : ℕ} (v : fin n.succ → α) : α := v 0 /-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/ def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α := v ∘ fin.succ variables {m n : ℕ} /-- Use `![...]` notation for displaying a vector `fin n → α`, for example: ``` #eval ![1, 2] + ![3, 4] -- ![4, 6] ``` -/ instance pi_fin.has_repr [has_repr α] : has_repr (fin n → α) := { repr := λ f, "![" ++ (string.intercalate ", " ((list.fin_range n).map (λ n, repr (f n)))) ++ "]" } end matrix_notation variables {m n o : ℕ} {m' n' o' : Type*} lemma empty_eq (v : fin 0 → α) : v = ![] := subsingleton.elim _ _ section val @[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl @[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨0, h⟩ = x := rfl @[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) : vec_cons x u i.succ = u i := by simp [vec_cons] @[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ := by simp only [vec_cons, fin.cons, fin.cases_succ'] @[simp] lemma head_cons (x : α) (u : fin m → α) : vec_head (vec_cons x u) = x := rfl @[simp] lemma tail_cons (x : α) (u : fin m → α) : vec_tail (vec_cons x u) = u := by { ext, simp [vec_tail] } @[simp] lemma empty_val' {n' : Type*} (j : n') : (λ i, (![] : fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] lemma cons_head_tail (u : fin m.succ → α) : vec_cons (vec_head u) (vec_tail u) = u := fin.cons_self_tail _ @[simp] lemma range_cons (x : α) (u : fin n → α) : set.range (vec_cons x u) = {x} ∪ set.range u := set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm] @[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ := set.range_eq_empty _ @[simp] lemma vec_cons_const (a : α) : vec_cons a (λ k : fin n, a) = λ _, a := funext $ fin.forall_fin_succ.2 ⟨rfl, cons_val_succ _ _⟩ lemma vec_single_eq_const (a : α) : ![a] = λ _, a := funext $ unique.forall_iff.2 rfl /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : fin 1 = 0 : fin 1`. -/ @[simp] lemma cons_val_one (x : α) (u : fin m.succ → α) : vec_cons x u 1 = vec_head u := by { rw [← fin.succ_zero_eq_one, cons_val_succ], refl } @[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) : vec_cons x u i = x := by { refine fin.forall_fin_one.2 _ i, refl } lemma cons_fin_one (x : α) (u : fin 0 → α) : vec_cons x u = (λ _, x) := funext (cons_val_fin_one x u) /-! ### Numeral (`bit0` and `bit1`) indices The following definitions and `simp` lemmas are to allow any numeral-indexed element of a vector given with matrix notation to be extracted by `simp` (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `fin n`). -/ @[simp] lemma empty_append (v : fin n → α) : fin.append (zero_add _).symm ![] v = v := by { ext, simp [fin.append] } @[simp] lemma cons_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) : fin.append ho (vec_cons x u) v = vec_cons x (fin.append (by rwa [add_assoc, add_comm 1, ←add_assoc, add_right_cancel_iff] at ho) u v) := begin ext i, simp_rw [fin.append], split_ifs with h, { rcases i with ⟨⟨⟩ | i, hi⟩, { simp }, { simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h, simp [h] } }, { rcases i with ⟨⟨⟩ | i, hi⟩, { simpa using h }, { rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h, simp [h] } } end /-- `vec_alt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩ /-- `vec_alt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩ lemma vec_alt0_append (v : fin n → α) : vec_alt0 rfl (fin.append rfl v v) = v ∘ bit0 := begin ext i, simp_rw [function.comp, bit0, vec_alt0, fin.append], split_ifs with h; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw tsub_lt_iff_left h, exact add_lt_add i.property i.property } end lemma vec_alt1_append (v : fin (n + 1) → α) : vec_alt1 rfl (fin.append rfl v v) = v ∘ bit1 := begin ext i, simp_rw [function.comp, vec_alt1, fin.append], cases n, { simp, congr }, { split_ifs with h; simp_rw [bit1, bit0]; congr, { simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], rw fin.coe_mk at h, rw fin.coe_one, rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h), rw nat.mod_eq_of_lt h }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw tsub_lt_iff_left h, exact nat.add_succ_lt_add i.property i.property } } end @[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt0 hm v) = v 0 := rfl @[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt1 hm v) = v 1 := by simp [vec_head, vec_alt1] @[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit0 i) = vec_alt0 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt0_append @[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit1 i) = vec_alt1 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt1_append @[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt0], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt0, nat.add_succ, nat.succ_add] } end -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] := by simp @[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt1], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt1, nat.add_succ, nat.succ_add] } end -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] := by simp end val section smul variables [semiring α] -- TODO: if I generalize these lemmas to `[has_scalar M α]`, then Lean fails to apply them -- in `data.complex.module` @[simp] lemma smul_empty (x : α) (v : fin 0 → α) : x • v = ![] := empty_eq _ @[simp] lemma smul_cons (x y : α) (v : fin n → α) : x • vec_cons y v = vec_cons (x * y) (x • v) := by { ext i, refine fin.cases _ _ i; simp } end smul section add variables [has_add α] @[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _ @[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl @[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl end add section sub variables [has_sub α] @[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _ @[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl @[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl end sub section zero variables [has_zero α] @[simp] lemma zero_empty : (0 : fin 0 → α) = ![] := empty_eq _ @[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 := by { ext i j, refine fin.cases _ _ i, { refl }, simp } @[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl @[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl @[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} : vec_cons x v = 0 ↔ x = 0 ∧ v = 0 := ⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩, λ ⟨hx, hv⟩, by simp [hx, hv] ⟩ open_locale classical lemma cons_nonzero_iff {v : fin n → α} {x : α} : vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) := ⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr), λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩ end zero section neg variables [has_neg α] @[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _ @[simp] lemma neg_cons (x : α) (v : fin n → α) : -(vec_cons x v) = vec_cons (-x) (-v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl @[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl end neg end matrix
30020905816e0d7f2cbf9247dfe25b7c9c24f488
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/order/filter/basic.lean
8317a58f0a608b87c99ab288b90d25b75e18ca5d
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
94,998
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.galois_connection order.zorn import data.set.finite /-! # Theory of filters on sets ## Main definitions * `filter` : filter on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `join` : operations on filters; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`. -/ open lattice set universes u v w x y open_locale classical namespace lattice variables {α : Type u} {ι : Sort v} def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}; subst_vars, exact @complete_lattice.le_refl α c, exact @complete_lattice.le_trans α c, exact @complete_lattice.le_antisymm α c, exact @complete_lattice.le_sup_left α c, exact @complete_lattice.le_sup_right α c, exact @complete_lattice.sup_le α c, exact @complete_lattice.inf_le_left α c, exact @complete_lattice.inf_le_right α c, exact @complete_lattice.le_inf α c, exact @complete_lattice.le_top α c, exact @complete_lattice.bot_le α c, exact @complete_lattice.le_Sup α c, exact @complete_lattice.Sup_le α c, exact @complete_lattice.Inf_le α c, exact @complete_lattice.le_Inf α c end end lattice open set lattice section order variables {α : Type u} (r : α → α → Prop) local infix ` ≼ ` : 50 := r lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ end order theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩)) structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by rw [filter_eq_iff, ext_iff] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := finite.induction_on hf (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff]) (assume i is _ hf hi hs, have h₁ : s i ∈ f, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma Inter_mem_sets_of_fintype {β : Type v} {s : β → set α} [fintype β] (h : ∀i, s i ∈ f) : (⋂i, s i) ∈ f := by simpa using Inter_mem_sets finite_univ (λi hi, h i) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ principal t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ principal s := subset.refl _ end principal section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ {} : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /- Galois insertion from sets of sets into a filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.lattice.has_top).1 (top_unique $ assume s hs, by have := univ_mem_sets ; finish) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.lattice.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [supr_sets_eq, iff_self, mem_Inter] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] lemma monotone_principal : monotone (principal : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f) : s.nonempty := have ∅ ∉ f, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), ne_empty_iff_nonempty.1 this lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_ne_empty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s ≠ ∅) ↔ f ≠ ⊥ := by simp only [(@empty_in_sets_eq_bot α f).symm, ne.def]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ f ≠ ⊥ := by simpa only [ne_empty_iff_nonempty] using forall_sets_ne_empty_iff_ne_bot lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f := have ∅ ∈ f ⊓ principal (- s), from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [mem_Union]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [infi_sets_eq h ne, mem_Union] @[nolint] -- Intentional use of `≥` lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl @[nolint] -- Intentional use of `≥` lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by simp only [binfi_sets_eq h ne, mem_bUnion_iff] lemma infi_sets_eq_finite (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), apply_instance end lemma mem_infi_finite {f : ι → filter α} (s) : s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets, by rw infi_sets_eq_finite @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.lattice.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} (f : filter α) (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (f.eventually_of_forall hq) /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} (hf : f ≠ ⊥) {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := begin assume h', have := h.and h', simp only [and_not_self, eventually_false_iff_eq_bot] at this, exact hf this end lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (f.eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from f.eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hf : f ≠ ⊥) : ∃ x, p x := (hp.frequently hf).exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true], assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal (f : filter α) (s t : set α) : s ∈ f ⊓ principal t ↔ { x | x ∈ t → x ∈ s } ∈ f := begin simp only [mem_inf_sets, mem_principal_sets, exists_prop], split, { rintros ⟨u, ul, v, tsubv, uvinter⟩, apply filter.mem_sets_of_superset ul, intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ }, intro h, refine ⟨_, h, t, set.subset.refl t, _⟩, rintros x ⟨hx, xt⟩, exact hx xt end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, principal (f i)) = principal (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, principal (f i)) = principal (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } end comap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite (-s) := iff.rfl lemma cofinite_ne_bot [infinite α] : @cofinite α ≠ ⊥ := mt empty_in_sets_eq_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ } lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `principal {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl lemma pure_eq_principal (a : α) : (pure a : filter α) = principal {a} := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := filter.ext $ λ s, iff.rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp only [this, subset.refl], by simp only [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : comap m f ≠ ⊥ := forall_sets_ne_empty_iff_ne_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in ne_bot_of_le_ne_bot (ne_empty_of_mem ha) t_s lemma comap_ne_bot_of_range_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : range m ∈ f) : comap m f ≠ ⊥ := comap_ne_bot $ assume t ht, let ⟨_, ha, a, rfl⟩ := inhabited_of_mem_sets hf (inter_mem_sets ht hm) in ⟨a, ha⟩ lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) {s : set α} (hs : m '' s ∈ f) : (comap m f ⊓ principal s) ≠ ⊥ := begin refine compl_compl s ▸ mt mem_sets_of_eq_bot _, rintros ⟨t, ht, hts⟩, rcases inhabited_of_mem_sets hf (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_ne_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : function.surjective m) : comap m f ≠ ⊥ := comap_ne_bot_of_range_mem hf $ univ_mem_sets' hm @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, iff_self, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f, filter_upwards [h, hs], simp only [subset_def, mem_preimage, mem_set_of_eq, forall_true_iff] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true] lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_inj : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl @[simp] lemma pure_ne_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := mt empty_in_sets_eq_bot.2 $ not_mem_empty a @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq] ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind /-- If `f : ι → filter α` is derected, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} (hn : nonempty ι) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd hn ∅).1 he, exact hb i (empty_in_sets_eq_bot.1 hi) end /-- If `f : ι → filter α` is derected, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := if hι : nonempty ι then infi_ne_bot_of_directed' hι hd hb else assume h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x) lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} (hn : nonempty ι) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume ne_bot i, ne_bot_of_le_ne_bot ne_bot (infi_le _ i), infi_ne_bot_of_directed' hn hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume ne_bot i, ne_bot_of_le_ne_bot ne_bot (infi_le _ i), infi_ne_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite] at hs, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- tendsto -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_cong hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ h₁ lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) (hx : x ≠ ⊥) : y ≠ ⊥ := ne_bot_of_le_ne_bot (map_ne_bot hx) h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap_comp, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, lattice.le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, lattice.le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} : tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a := by simp only [tendsto, le_principal_iff, mem_map, iff_self] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ {x | f x = b} ∈ a := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ principal p) l₂) (h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ filter.prod f g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ filter.prod f g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) := by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) := by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf] lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) := by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f.prod g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm] @[simp] lemma prod_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) := by simp [pure_eq_principal] lemma prod_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := by rw [(≠), prod_eq_bot, not_or_distrib] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_ne_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a)) @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := let ⟨a⟩ := ‹nonempty α› in iff.intro (assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (by apply_instance) ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true] lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f) := by simp only [at_top, tendsto_infi, tendsto_principal]; refl lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : {x | f₁ x ≤ f₂ x} ∈ l) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_top_mono [preorder β] (l : filter α) : monotone (λ f : α → β, tendsto f l at_top) := λ f₁ f₂ h, tendsto_at_top_mono' l $ univ_mem_sets' h section ordered_monoid variables [ordered_cancel_comm_monoid β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : {x | 0 ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_left) hf) hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' l (univ_mem_sets' hf) hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : {x | 0 ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' l hf (univ_mem_sets' hg) lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_left) ((tendsto_at_top _ _).1 hf (C + b)) lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_right) ((tendsto_at_top _ _).1 hf (b + C)) lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : {x | f x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : f x ≤ C), add_le_add_right hx (g x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' l C (univ_mem_sets' hC) lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : {x | g x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : g x ≤ C), add_le_add_left hx (f x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' l C (univ_mem_sets' hC) end ordered_monoid section ordered_group variables [ordered_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : {x | C ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simp [hf]) (by simp [hg]) lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : {x | C ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) end ordered_group lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl /-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [decidable_linear_order α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → b ≥ f a := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top.2 finset.exists_nat_subset_range lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (finset.image j) at_top at_top := have j ∘ i = id, from funext h, (finset.image_mono j).tendsto_at_top_at_top.2 $ assume s, ⟨s.image i, by simp only [finset.image_image, this, finset.image_id, le_refl]⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ := by simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod]; exact infi_comm lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin rw [@map_at_top_eq α _ ⟨g b'⟩], refine le_antisymm (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _) (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _), { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) }, { assume b hb, have hb' : b' ≤ b := le_trans le_sup_right hb, exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb), le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ } end lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /- ultrafilter -/ section ultrafilter open zorn 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 : f ⊓ g ≠ ⊥) : f ≤ g := 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 ≤ principal (-s), from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_eq_bot $ by simp only [h, eq_self_iff_true, lattice.neg_neg], 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 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 finite_image s his, 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⟩ := inhabited_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, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _ 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.val_range, 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.val_range, ←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} def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ 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 } 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 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, lattice.neg_neg], 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 α := have h : _ := compl_mem_hyperfilter_of_finite hf, by rwa [lattice.neg_neg] at h 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; apply ultrafilter_unique v.property u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ := ⟨assume ⟨u, uf⟩, lattice.ne_bot_of_le_ne_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩ end ultrafilter end filter namespace filter variables {α β γ : Type u} {f : β → filter α} {s : γ → set α} open list lemma mem_traverse_sets : ∀(fs : list β) (us : list γ), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) : t ∈ traverse f fs ↔ (∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) end filter open filter lemma set.infinite_iff_frequently_cofinite {α : Type u} {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (finite.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply finite_subset (finite_lt_nat N), assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end
51622704c21588ce3bb76bdad3a561992be1ea2d
dc253be9829b840f15d96d986e0c13520b085033
/algebra/ses.hlean
f4379878f65a1063912b211d83592ee5c6a6dc96
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
10,412
hlean
/- Copyright (c) 2017 Egbert Rijke. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Egbert Rijke Basic facts about short exact sequences. At the moment, it only covers short exact sequences of abelian groups, but this should be extended to short exact sequences in any abelian category. -/ import algebra.group_theory hit.set_quotient types.sigma types.list types.sum .quotient_group .subgroup .exactness open eq algebra is_trunc set_quotient relation sigma sigma.ops prod prod.ops sum list trunc function group trunc equiv is_equiv property structure SES (A B C : AbGroup) := ( f : A →g B) ( g : B →g C) ( Hf : is_embedding f) ( Hg : is_surjective g) ( ex : is_exact_ag f g) definition SES_of_inclusion {A B : AbGroup} (f : A →g B) (Hf : is_embedding f) : SES A B (quotient_ab_group (image f)) := begin have Hg : is_surjective (ab_qg_map (image f)), from is_surjective_ab_qg_map (image f), fapply SES.mk, exact f, exact ab_qg_map (image f), exact Hf, exact Hg, fapply is_exact.mk, intro a, fapply ab_qg_map_eq_one, fapply tr, fapply fiber.mk, exact a, reflexivity, intro b, intro p, exact rel_of_ab_qg_map_eq_one _ p end definition SES_of_subgroup {B : AbGroup} (S : property B) [is_subgroup B S] : SES (ab_subgroup S) B (quotient_ab_group S) := begin fapply SES.mk, exact incl_of_subgroup S, exact ab_qg_map S, exact is_embedding_incl_of_subgroup S, exact is_surjective_ab_qg_map S, fapply is_exact.mk, intro a, fapply ab_qg_map_eq_one, induction a with b p, exact p, intro b p, fapply tr, fapply fiber.mk, fapply sigma.mk b, fapply rel_of_ab_qg_map_eq_one, exact p, reflexivity, end definition SES_of_surjective_map {B C : AbGroup} (g : B →g C) (Hg : is_surjective g) : SES (ab_Kernel g) B C := begin fapply SES.mk, exact ab_Kernel_incl g, exact g, exact is_embedding_ab_kernel_incl g, exact Hg, fapply is_exact.mk, intro a, induction a with a p, exact p, intro b p, fapply tr, fapply fiber.mk, fapply sigma.mk, exact b, exact p, reflexivity, end definition SES_of_homomorphism {A B : AbGroup} (f : A →g B) : SES (ab_Kernel f) A (ab_Image f) := begin fapply SES.mk, exact ab_Kernel_incl f, exact image_lift f, exact is_embedding_ab_kernel_incl f, exact is_surjective_image_lift f, fapply is_exact.mk, intro a, induction a with a p, fapply subtype_eq, exact p, intro a p, fapply tr, fapply fiber.mk, fapply sigma.mk, exact a, exact calc f a = image_incl f (image_lift f a) : by exact homotopy_of_eq (ap group_fun (image_factor f)) a ... = image_incl f 1 : ap (image_incl f) p ... = 1 : by exact respect_one (image_incl f), reflexivity end definition SES_of_isomorphism_right {B C : AbGroup} (g : B ≃g C) : SES trivial_ab_group B C := begin fapply SES.mk, exact from_trivial_ab_group B, exact g, exact is_embedding_from_trivial_ab_group B, fapply is_surjective_of_is_equiv, fapply is_exact.mk, intro a, induction a, fapply respect_one, intro b p, have q : g b = g 1, from p ⬝ (respect_one g)⁻¹, note r := inj (equiv_of_isomorphism g) q, fapply tr, fapply fiber.mk, exact unit.star, rewrite r, end structure hom_SES {A B C A' B' C' : AbGroup} (ses : SES A B C) (ses' : SES A' B' C') := ( hA : A →g A') ( hB : B →g B') ( hC : C →g C') ( htpy1 : hB ∘g (SES.f ses) ~ (SES.f ses') ∘g hA) ( htpy2 : hC ∘g (SES.g ses) ~ (SES.g ses') ∘g hB) section ses parameters {A B C : AbGroup} (ses : SES A B C) local abbreviation f := SES.f ses local notation `g` := SES.g ses local abbreviation ex := SES.ex ses local abbreviation q := ab_qg_map (kernel g) local abbreviation B_mod_A := quotient_ab_group (kernel g) definition SES_iso_stable {A' B' C' : AbGroup} (f' : A' →g B') (g' : B' →g C') (α : A' ≃g A) (β : B' ≃g B) (γ : C' ≃g C) (Hαβ : f ∘g α ~ β ∘g f') (Hβγ : g ∘g β ~ γ ∘g g') : SES A' B' C' := begin fapply SES.mk, exact f', exact g', fapply is_embedding_of_is_injective, intros x y p, have path : f (α x) = f (α y), by exact calc f (α x) = β (f' x) : Hαβ x ... = β (f' y) : ap β p ... = f (α y) : (Hαβ y)⁻¹, have path' : α x = α y, by exact @is_injective_of_is_embedding _ _ f (SES.Hf ses) _ _ path, exact @is_injective_of_is_embedding _ _ α (is_embedding_of_is_equiv α) _ _ path', exact sorry, exact sorry, end definition SES_of_triangle_left {A' : AbGroup} (α : A' ≃g A) (f' : A' →g B) (H : Π a' : A', f (α a') = f' a') : SES A' B C := begin fapply SES.mk, exact f', exact g, fapply is_embedding_of_is_injective, intro x y p, fapply inj (equiv_of_isomorphism α), fapply @is_injective_of_is_embedding _ _ f (SES.Hf ses) (α x) (α y), rewrite [H x], rewrite [H y], exact p, exact SES.Hg ses, fapply is_exact.mk, intro a', rewrite [(H a')⁻¹], fapply is_exact.im_in_ker (SES.ex ses), intro b p, have t : image' f b, from is_exact.ker_in_im (SES.ex ses) b p, unfold image' at t, induction t, fapply tr, induction a with a h, fapply fiber.mk, exact α⁻¹ᵍ a, rewrite [(H (α⁻¹ᵍ a))⁻¹], krewrite [right_inv (equiv_of_isomorphism α) a], exact h end --definition quotient_SES {A B C : AbGroup} (ses : SES A B C) : -- quotient_ab_group (image_subgroup (SES.f ses)) ≃g C := -- begin -- fapply ab_group_first_iso_thm B C (SES.g ses), -- end -- definition pre_right_extend_SES (to separate the following definition and replace C with B/A) definition quotient_codomain_SES : B_mod_A ≃g C := begin exact (codomain_surjection_is_quotient g (SES.Hg ses)) end local abbreviation α := quotient_codomain_SES definition quotient_triangle_SES : α ∘g q ~ g := begin reflexivity end definition quotient_triangle_extend_SES {C': AbGroup} (k : B →g C') : (Σ (h : C →g C'), h ∘g g ~ k) ≃ (Σ (h' : B_mod_A →g C'), h' ∘g q ~ k) := begin fapply equiv.mk, intro pair, induction pair with h H, fapply sigma.mk, exact h ∘g α, intro b, exact H b, fapply adjointify, intro pair, induction pair with h' H', fapply sigma.mk, exact h' ∘g α⁻¹ᵍ, intro b, exact calc h' (α⁻¹ᵍ (g b)) = h' (α⁻¹ᵍ (α (q b))) : by reflexivity ... = h' (q b) : by exact hwhisker_left h' (left_inv α) (q b) ... = k b : by exact H' b, intro pair, induction pair with h' H', fapply sigma_eq, esimp, fapply homomorphism_eq, fapply hwhisker_left h' (left_inv α), esimp, fapply is_prop.elimo, fapply pi.is_trunc_pi, intro a, fapply is_trunc_eq, intro pair, induction pair with h H, fapply sigma_eq, esimp, fapply homomorphism_eq, fapply hwhisker_left h (right_inv α), esimp, fapply is_prop.elimo, fapply pi.is_trunc_pi, intro a, fapply is_trunc_eq, end parameters {A' B' C' : AbGroup} (ses' : SES A' B' C') (hA : A →g A') (hB : B →g B') (htpy1 : hB ∘g f ~ (SES.f ses') ∘g hA) local abbreviation f' := SES.f ses' local notation `g'` := SES.g ses' local abbreviation ex' := SES.ex ses' local abbreviation q' := ab_qg_map (kernel g') local abbreviation α' := quotient_codomain_SES include htpy1 definition quotient_extend_unique_SES : is_contr (Σ (hC : C →g C'), hC ∘g g ~ g' ∘g hB) := begin fapply @(is_trunc_equiv_closed_rev _ (quotient_triangle_extend_SES (g' ∘g hB))), fapply ab_qg_universal_property, intro b, intro K, have k : image' f b, from is_exact.ker_in_im ex b K, unfold image' at k, induction k, induction a with a p, induction p, refine (ap g' (htpy1 a)) ⬝ _, fapply is_exact.im_in_ker ex' (hA a) end /- -- We define a group homomorphism B/ker(g) →g B'/ker(g'), keeping in mind that ker(g)=A and ker(g')=A'. definition quotient_extend_SES : quotient_ab_group (kernel_subgroup g) →g quotient_ab_group (kernel_subgroup g') := begin fapply ab_group_quotient_homomorphism B B' (kernel_subgroup g) (kernel_subgroup g') hB, intro b, intro K, have k : trunctype.carrier (image_subgroup f b), from is_exact.ker_in_im ex b K, induction k, induction a with a p, rewrite [p⁻¹], rewrite [htpy1 a], fapply is_exact.im_in_ker ex' (hA a) end local abbreviation k := quotient_extend_SES definition quotient_extend_SES_square : k ∘g (ab_qg_map (kernel_subgroup g)) ~ (ab_qg_map (kernel_subgroup g')) ∘g hB := begin fapply quotient_group_compute end definition right_extend_SES : C →g C' := α' ∘g k ∘g α⁻¹ᵍ local abbreviation hC := right_extend_SES definition right_extend_SES_square : hC ∘g g ~ g' ∘ hB := begin exact calc hC ∘g g ~ hC ∘g α ∘g q : by reflexivity ... ~ α' ∘g k ∘g α⁻¹ᵍ ∘g α ∘g q : by reflexivity ... ~ α' ∘g k ∘g q : by exact hwhisker_left (α' ∘g k) (hwhisker_right q (left_inv α)) ... ~ α' ∘g q' ∘g hB : by exact hwhisker_left α' (quotient_extend_SES_square) ... ~ g' ∘g hB : by reflexivity end local abbreviation htpy2 := right_extend_SES_square definition right_extend_SES_unique_map_aux (hC' : C →g C') (htpy2' : g' ∘g hB ~ hC' ∘g g) : k ∘g q ~ α'⁻¹ᵍ ∘g hC' ∘g α ∘g q := begin exact calc k ∘g q ~ q' ∘g hB : by reflexivity ... ~ α'⁻¹ᵍ ∘g α' ∘g q' ∘g hB : by exact hwhisker_right (q' ∘g hB) (homotopy.symm (left_inv α')) ... ~ α'⁻¹ᵍ ∘g g' ∘g hB : by reflexivity ... ~ α'⁻¹ᵍ ∘g hC' ∘g g : by exact hwhisker_left (α'⁻¹ᵍ) htpy2' ... ~ α'⁻¹ᵍ ∘g hC' ∘g α ∘g q : by reflexivity end definition right_extend_SES_unique_map (hC' : C →g C') (htpy2' : hC' ∘g g ~ g' ∘g hB) : hC ~ hC' := begin exact calc hC ~ α' ∘g k ∘g α⁻¹ᵍ : by reflexivity ... ~ α' ∘g α'⁻¹ᵍ ∘g hC' ∘g α ∘g α⁻¹ᵍ : ... ~ hC' ∘g α ∘g α⁻¹ᵍ : _ ... ~ hC' : _ end definition right_extend_hom_SES : hom_SES ses ses' := begin fapply hom_SES.mk, exact hA, exact hB, exact hC, exact htpy1, exact htpy2 end -/ end ses
960e89eac14aec27f9e44823433ce80bd262c2a2
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/core.lean
0d169db89fc70886d66832bfecfbf7eb417d5e4d
[ "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
97,054
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import control.basic import data.dlist.basic import meta.expr import system.io import tactic.binder_matching import tactic.interactive_expr import tactic.lean_core_docs import tactic.project_dir universe u attribute [derive [has_reflect, decidable_eq]] tactic.transparency -- Rather than import order.lexicographic here, we can get away with defining the order by hand. instance : has_lt pos := { lt := λ x y, x.line < y.line ∨ x.line = y.line ∧ x.column < y.column } namespace tactic /-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/ meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) /-- Turns a conversion tactic into one that always succeeds, where failure is interpreted as a proof by reflexivity. -/ meta def or_refl_conv (tac : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := tac e <|> refl_conv e /-- Transitivity conversion: given two conversions (which take an expression `e` and returns `(e', ⊢ e = e')`), produces another conversion that combines them with transitivity, treating failures as reflexivity conversions. -/ meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace expr /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Convert a list of expressions to an expression denoting the list of those expressions. -/ meta def of_list (α : expr) : list expr → tactic expr | [] := tactic.mk_app ``list.nil [α] | (x :: xs) := do exs ← of_list xs, tactic.mk_app ``list.cons [α, x, exs] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace name /-- `pre.contains_sorry_aux nm` checks whether `sorry` occurs in the value of the declaration `nm` or (recusively) in any declarations occurring in the value of `nm` with namespace `pre`. Auxiliary function for `name.contains_sorry`. -/ meta def contains_sorry_aux (pre : name) : name → tactic bool | nm := do env ← get_env, decl ← get_decl nm, ff ← return decl.value.contains_sorry | return tt, (decl.value.list_names_with_prefix pre).mfold ff $ λ n b, if b then return tt else n.contains_sorry_aux /-- `nm.contains_sorry` checks whether `sorry` occurs in the value of the declaration `nm` or in any declarations `nm._proof_i` (or to be more precise: any declaration in namespace `nm`). See also `expr.contains_sorry`. -/ meta def contains_sorry (nm : name) : tactic bool := nm.contains_sorry_aux nm end name namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function export interaction_monad (get_state set_state run_with_state) /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.dedup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expressions are not necessarily in whnf. -/ meta def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr) := prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-- `get_univ_level t` returns the universe level of a type `t` -/ meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) : tactic level := do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive | fail "get_univ_level: argument is not a type", return u /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := do ctx ← unsafe.type_context.get_local_context.run, (some decl) ← pure $ ctx.get_local_decl e.local_uniq_name | fail format!"is_local_def: {e} is not a local constant", when decl.value.is_none $ fail format!"is_local_def: {e} is not a local definition" /-- Returns the local definitions from the context. A local definition is a local constant of the form `e : α := t`. The local definitions are returned in the order in which they appear in the context. -/ meta def local_defs : tactic (list expr) := do ctx ← unsafe.type_context.get_local_context.run, ctx' ← local_context, ctx'.mfilter $ λ h, do (some decl) ← pure $ ctx.get_local_decl h.local_uniq_name | fail format!"local_defs: local {h} not found in the local context", pure decl.value.is_some /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and substitute `t` for `h`. This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (h : expr) : tactic unit := do e ← do { -- we first find the variable being substituted away t ← infer_type h, let (f, args) := t.get_app_fn_args, if (f.const_name = `eq ∨ f.const_name = `heq) then do { let lhs := args.inth 1, let rhs := args.ilast, if rhs.is_local_constant then return rhs else if lhs.is_local_constant then return lhs else fail "subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." } else return h }, success_if_fail (is_local_def e) <|> fail format!("Cannot substitute variable {e.local_pp_name}, " ++ "it is a local definition. If you really want to do this, use `clear_value` first."), subst h /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Given the name of a user attribute, produces a list of `tactic expr`s, each of which is the application of `i_to_expr_for_apply` to a declaration with that attribute. -/ meta def resolve_attribute_expr_list (attr_name : name) : tactic (list (tactic expr)) := do l ← attribute.get_instances attr_name, list.map i_to_expr_for_apply <$> list.reverse <$> l.mmap resolve_name /--`apply_rules args attrs n`: apply the lists of rules `args` (given as pexprs) and `attrs` (given as names of attributes) and `the tactic assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (args : list pexpr) (attrs : list name) (n : nat) (opt : apply_cfg) : tactic unit := do attr_exprs ← lock_tactic_state $ attrs.mfoldl (λ l n, list.append l <$> resolve_attribute_expr_list n) [], let args_exprs := args.map i_to_expr_for_apply ++ attr_exprs, -- `args_exprs` is a list of `tactic expr`, rather than just `expr`, because these expressions will -- be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt args_exprs) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }}", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open _root_.lean open _root_.lean.parser open _root_.interactive _root_.interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean _root_.interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of any project. Requires as argument any declaration name `n` in that project, and `k`, the number of characters in the path of the file where `n` is declared not part of the `src` directory. Example: For `mathlib_dir_locator` this is the length of `tactic/project_dir.lean`, so `23`. Note: does not work in the file where `n` is declared. -/ meta def get_project_dir (n : name) (k : ℕ) : tactic string := do e ← get_env, s ← e.decl_olean n <|> fail!"Did not find declaration {n}. This command does not work in the file where {n} is declared.", return $ s.popn_back k /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := get_project_dir `mathlib_dir_locator 23 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail! "name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute. If the user attribute has a parameter, the default value will be used. This tactic raises an error if there is no `inhabited` instance for the parameter type. -/ meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name default %%persistent) <|> fail! ("Cannot set attribute @[{attr_name}].\n" ++ "The corresponding user attribute {user_attr_nm} " ++ "has a parameter without a default value.\n" ++ "Solution: provide an `inhabited` instance."), tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
d8f7dd13b89b8e25de7f5f88828c7a78d97bc83c
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/ring_theory/noetherian.lean
7e2808abeb46cc7faa78774630c3a347c32ac300
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
21,285
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import data.equiv.algebra import linear_algebra.finsupp import ring_theory.ideal_operations import ring_theory.subring import linear_algebra.basis open set lattice namespace submodule variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] def fg (s : submodule α β) : Prop := ∃ t : finset β, submodule.span α ↑t = s theorem fg_def {s : submodule α β} : s.fg ↔ ∃ t : set β, finite t ∧ span α t = s := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_coe, mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_coe, mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_coe, mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_coe, mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule α β).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {s₁ s₂ : submodule α β} (hs₁ : s₁.fg) (hs₂ : s₂.fg) : (s₁ ⊔ s₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hs₁, ⟨t₂, ht₂⟩ := fg_def.1 hs₂ in fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {γ : Type*} [add_comm_group γ] [module α γ] variables {f : β →ₗ[α] γ} theorem fg_map {s : submodule α β} (hs : s.fg) : (s.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule α β} {sc : submodule α γ} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, finite_union (finite_image _ htb.1) (finite_image _ htc.1), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule α β} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq α, haveI := classical.dec_eq β, haveI := classical.dec_eq γ, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : γ → β, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total β β α id).to_fun ((finsupp.lmap_domain α α g : (γ →₀ α) → β →₀ α) l), _, x - finsupp.total β β α id ((finsupp.lmap_domain α α g : (γ →₀ α) → β →₀ α) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited γ := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule class is_noetherian (α β) [ring α] [add_comm_group β] [module α β] : Prop := (noetherian : ∀ (s : submodule α β), s.fg) section variables {α : Type*} {β : Type*} {γ : Type*} variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] open is_noetherian include α theorem is_noetherian_submodule {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (β) theorem is_noetherian_of_surjective (f : β →ₗ[α] γ) (hf : f.range = ⊤) [is_noetherian α β] : is_noetherian α γ := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {β} theorem is_noetherian_of_linear_equiv (f : β ≃ₗ[α] γ) [is_noetherian α β] : is_noetherian α γ := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian α β] [is_noetherian α γ] : is_noetherian α (β × γ) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd α β γ) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd α β γ) ≤ linear_map.range (linear_map.inl α β γ), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {α ι : Type*} {β : ι → Type*} [ring α] [Π i, add_comm_group (β i)] [Π i, module α (β i)] [fintype ι] [∀ i, is_noetherian α (β i)] : is_noetherian α (Π i, β i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian α (Π i : (↑s : set ι), β i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext i, cases i, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot α).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (β a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show β i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show β i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext i, cases i with i his, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext i, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {α β} [ring α] [add_comm_group β] [module α β] : is_noetherian α β ↔ well_founded ((>) : submodule α β → submodule α β → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let M := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian M) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set β), { rw [← submodule.Union_coe_of_directed _ N _], { show t ⊆ M, rw ← h₂, apply submodule.subset_span }, { apply_instance }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : M ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ M ≤ N, ∃ s, finite s ∧ M ⊔ submodule.span α s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ M, h.induction M _, intros M IH MN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ M, { cases le_antisymm MN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬M ⊔ submodule.span α {x} ≤ M, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (M ⊔ submodule.span α {x}) ⟨@le_sup_left _ _ M _, this⟩ (sup_le MN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (α β) [ring α] [add_comm_group β] [module α β] : ∀ [is_noetherian α β], well_founded ((>) : submodule α β → submodule α β → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {α β} [nonzero_comm_ring α] [add_comm_group β] [module α β] [decidable_eq α] [decidable_eq β] [is_noetherian α β] {s : set β} (hs : linear_independent α (subtype.val : s → β)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt α β) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (subtype.val ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span α ((subtype.val ∘ f) '' {m | m ≤ a}) ≤ span α ((subtype.val ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff (@zero_ne_one α _) hs (this a) (this b), set.image_subset_image_iff (injective_comp subtype.val_injective f.inj'), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span α ((subtype.val ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end @[class] def is_noetherian_ring (α) [ring α] : Prop := is_noetherian α α instance is_noetherian_ring.to_is_noetherian {α : Type*} [ring α] : ∀ [is_noetherian_ring α], is_noetherian α α := id instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [finset.coe_to_finset', submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change s.attach.sum (λ i, (f i + g i) • _) = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change s.attach.sum (λ i, (c • f i) • _) = _, simp only [smul_eq_mul, mul_smul], exact finset.sum_hom _ } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x.1, subtype.eq _⟩, change s.attach.sum (λ i, l i.1 • i.1) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R → S) [is_ring_hom f] (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R → S) [is_ring_hom f] [is_noetherian_ring R] : is_noetherian_ring (set.range f) := @is_noetherian_ring_of_surjective R _ (set.range f) _ (λ x, ⟨f x, x, rfl⟩) (⟨subtype.eq (is_ring_hom.map_one f), λ _ _, subtype.eq (is_ring_hom.map_mul f), λ _ _, subtype.eq (is_ring_hom.map_add f)⟩) (λ ⟨x, y, hy⟩, ⟨y, subtype.eq hy⟩) _ theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃r S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.1 f.1.surjective namespace is_noetherian_ring variables {α : Type*} [integral_domain α] [is_noetherian_ring α] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : α, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x ) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f:multiset α, (∀b∈f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M^n).fg := nat.rec_on n (⟨finset.singleton 1, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
895566d5eeb171306496e974ad463a5a137f40df
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/algebra/restrict_scalars.lean
ea90c084b2611f88b420dcb5aac2fd803cc4d5dc
[ "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,463
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.tower /-! # The `restrict_scalars` type alias > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. See the documentation attached to the `restrict_scalars` definition for advice on how and when to use this type alias. As described there, it is often a better choice to use the `is_scalar_tower` typeclass instead. ## Main definitions * `restrict_scalars R S M`: the `S`-module `M` viewed as an `R` module when `S` is an `R`-algebra. Note that by default we do *not* have a `module S (restrict_scalars R S M)` instance for the original action. This is available as a def `restrict_scalars.module_orig` if really needed. * `restrict_scalars.add_equiv : restrict_scalars R S M ≃+ M`: the additive equivalence between the restricted and original space (in fact, they are definitionally equal, but sometimes it is helpful to avoid using this fact, to keep instances from leaking). * `restrict_scalars.ring_equiv : restrict_scalars R S A ≃+* A`: the ring equivalence between the restricted and original space when the module is an algebra. ## See also There are many similarly-named definitions elsewhere which do not refer to this type alias. These refer to restricting the scalar type in a bundled type, such as from `A →ₗ[R] B` to `A →ₗ[S] B`: * `linear_map.restrict_scalars` * `linear_equiv.restrict_scalars` * `alg_hom.restrict_scalars` * `alg_equiv.restrict_scalars` * `submodule.restrict_scalars` * `subalgebra.restrict_scalars` -/ variables (R S M A : Type*) /-- If we put an `R`-algebra structure on a semiring `S`, we get a natural equivalence from the category of `S`-modules to the category of representations of the algebra `S` (over `R`). The type synonym `restrict_scalars` is essentially this equivalence. Warning: use this type synonym judiciously! Consider an example where we want to construct an `R`-linear map from `M` to `S`, given: ```lean variables (R S M : Type*) variables [comm_semiring R] [semiring S] [algebra R S] [add_comm_monoid M] [module S M] ``` With the assumptions above we can't directly state our map as we have no `module R M` structure, but `restrict_scalars` permits it to be written as: ```lean -- an `R`-module structure on `M` is provided by `restrict_scalars` which is compatible example : restrict_scalars R S M →ₗ[R] S := sorry ``` However, it is usually better just to add this extra structure as an argument: ```lean -- an `R`-module structure on `M` and proof of its compatibility is provided by the user example [module R M] [is_scalar_tower R S M] : M →ₗ[R] S := sorry ``` The advantage of the second approach is that it defers the duty of providing the missing typeclasses `[module R M] [is_scalar_tower R S M]`. If some concrete `M` naturally carries these (as is often the case) then we have avoided `restrict_scalars` entirely. If not, we can pass `restrict_scalars R S M` later on instead of `M`. Note that this means we almost always want to state definitions and lemmas in the language of `is_scalar_tower` rather than `restrict_scalars`. An example of when one might want to use `restrict_scalars` would be if one has a vector space over a field of characteristic zero and wishes to make use of the `ℚ`-algebra structure. -/ @[nolint unused_arguments] def restrict_scalars (R S M : Type*) : Type* := M instance [I : inhabited M] : inhabited (restrict_scalars R S M) := I instance [I : add_comm_monoid M] : add_comm_monoid (restrict_scalars R S M) := I instance [I : add_comm_group M] : add_comm_group (restrict_scalars R S M) := I section module section variables [semiring S] [add_comm_monoid M] /-- We temporarily install an action of the original ring on `restrict_sclars R S M`. -/ def restrict_scalars.module_orig [I : module S M] : module S (restrict_scalars R S M) := I variables [comm_semiring R] [algebra R S] section local attribute [instance] restrict_scalars.module_orig /-- When `M` is a module over a ring `S`, and `S` is an algebra over `R`, then `M` inherits a module structure over `R`. The preferred way of setting this up is `[module R M] [module S M] [is_scalar_tower R S M]`. -/ instance [module S M] : module R (restrict_scalars R S M) := module.comp_hom M (algebra_map R S) /-- This instance is only relevant when `restrict_scalars.module_orig` is available as an instance. -/ instance [module S M] : is_scalar_tower R S (restrict_scalars R S M) := ⟨λ r S M, by { rw [algebra.smul_def, mul_smul], refl }⟩ end /-- When `M` is a right-module over a ring `S`, and `S` is an algebra over `R`, then `M` inherits a right-module structure over `R`. The preferred way of setting this up is `[module Rᵐᵒᵖ M] [module Sᵐᵒᵖ M] [is_scalar_tower Rᵐᵒᵖ Sᵐᵒᵖ M]`. -/ instance restrict_scalars.op_module [module Sᵐᵒᵖ M] : module Rᵐᵒᵖ (restrict_scalars R S M) := begin letI : module Sᵐᵒᵖ (restrict_scalars R S M) := ‹module Sᵐᵒᵖ M›, exact module.comp_hom M (algebra_map R S).op end instance restrict_scalars.is_central_scalar [module S M] [module Sᵐᵒᵖ M] [is_central_scalar S M] : is_central_scalar R (restrict_scalars R S M) := { op_smul_eq_smul := λ r x, (op_smul_eq_smul (algebra_map R S r) (_ : M) : _)} /-- The `R`-algebra homomorphism from the original coefficient algebra `S` to endomorphisms of `restrict_scalars R S M`. -/ def restrict_scalars.lsmul [module S M] : S →ₐ[R] module.End R (restrict_scalars R S M) := begin -- We use `restrict_scalars.module_orig` in the implementation, -- but not in the type. letI : module S (restrict_scalars R S M) := restrict_scalars.module_orig R S M, exact algebra.lsmul R (restrict_scalars R S M), end end variables [add_comm_monoid M] /-- `restrict_scalars.add_equiv` is the additive equivalence with the original module. -/ def restrict_scalars.add_equiv : restrict_scalars R S M ≃+ M := add_equiv.refl M variables [comm_semiring R] [semiring S] [algebra R S] [module S M] @[simp] lemma restrict_scalars.add_equiv_map_smul (c : R) (x : restrict_scalars R S M) : restrict_scalars.add_equiv R S M (c • x) = (algebra_map R S c) • restrict_scalars.add_equiv R S M x := rfl lemma restrict_scalars.smul_def (c : R) (x : restrict_scalars R S M) : c • x = (restrict_scalars.add_equiv R S M).symm (algebra_map R S c • restrict_scalars.add_equiv R S M x) := rfl lemma restrict_scalars.add_equiv_symm_map_algebra_map_smul (r : R) (x : M) : (restrict_scalars.add_equiv R S M).symm (algebra_map R S r • x) = r • (restrict_scalars.add_equiv R S M).symm x := rfl lemma restrict_scalars.add_equiv_symm_map_smul_smul (r : R) (s : S) (x : M) : (restrict_scalars.add_equiv R S M).symm ((r • s) • x) = r • (restrict_scalars.add_equiv R S M ).symm (s • x) := by { rw [algebra.smul_def, mul_smul], refl, } lemma restrict_scalars.lsmul_apply_apply (s : S) (x : restrict_scalars R S M) : restrict_scalars.lsmul R S M s x = (restrict_scalars.add_equiv R S M).symm (s • (restrict_scalars.add_equiv R S M x)) := rfl end module section algebra instance [I : semiring A] : semiring (restrict_scalars R S A) := I instance [I : ring A] : ring (restrict_scalars R S A) := I instance [I : comm_semiring A] : comm_semiring (restrict_scalars R S A) := I instance [I : comm_ring A] : comm_ring (restrict_scalars R S A) := I variables [semiring A] /-- Tautological ring isomorphism `restrict_scalars R S A ≃+* A`. -/ def restrict_scalars.ring_equiv : restrict_scalars R S A ≃+* A := ring_equiv.refl _ variables [comm_semiring S] [algebra S A] [comm_semiring R] [algebra R S] @[simp] lemma restrict_scalars.ring_equiv_map_smul (r : R) (x : restrict_scalars R S A) : restrict_scalars.ring_equiv R S A (r • x) = (algebra_map R S r) • restrict_scalars.ring_equiv R S A x := rfl /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance : algebra R (restrict_scalars R S A) := { smul := (•), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } @[simp] lemma restrict_scalars.ring_equiv_algebra_map (r : R) : restrict_scalars.ring_equiv R S A (algebra_map R (restrict_scalars R S A) r) = algebra_map S A (algebra_map R S r) := rfl end algebra
35e76266f6900e0b7be1afe69f8a5057225b844c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/specialize2.lean
55b62870ebf3d33a30af673b6faadcf9baaa9125
[ "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
328
lean
example : (p → q → False) ↔ (¬ p ∨ ¬ q) := by apply Iff.intro · intro h by_cases hp:p <;> by_cases hq:q · specialize h hp hq; contradiction · exact Or.inr hq · exact Or.inl hp · exact Or.inr hq · intro | Or.inl hnp => intros; contradiction | Or.inr hnq => intros; contradiction
25ceae7e27b93329aade464838d6e105082f486e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/laurent_series.lean
4b18c5ab9bbc1a43c1cd4ea89b86ae8c6bc878d1
[ "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
6,230
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import ring_theory.hahn_series import ring_theory.localization /-! # Laurent Series ## Main Definitions * Defines `laurent_series` as an abbreviation for `hahn_series ℤ`. * Provides a coercion `power_series R` into `laurent_series R` given by `hahn_series.of_power_series`. * Defines `laurent_series.power_series_part` * Defines the localization map `laurent_series.of_power_series_localization` which evaluates to `hahn_series.of_power_series`. -/ open hahn_series open_locale big_operators classical noncomputable theory /-- A `laurent_series` is implemented as a `hahn_series` with value group `ℤ`. -/ abbreviation laurent_series (R : Type*) [has_zero R] := hahn_series ℤ R variables {R : Type*} namespace laurent_series section semiring variable [semiring R] instance : has_coe (power_series R) (laurent_series R) := ⟨hahn_series.of_power_series ℤ R⟩ lemma coe_power_series (x : power_series R) : (x : laurent_series R) = hahn_series.of_power_series ℤ R x := rfl @[simp] lemma coeff_coe_power_series (x : power_series R) (n : ℕ) : hahn_series.coeff (x : laurent_series R) n = power_series.coeff R n x := by rw [← int.nat_cast_eq_coe_nat, coe_power_series, of_power_series_apply_coeff] /-- This is a power series that can be multiplied by an integer power of `X` to give our Laurent series. If the Laurent series is nonzero, `power_series_part` has a nonzero constant term. -/ def power_series_part (x : laurent_series R) : power_series R := power_series.mk (λ n, x.coeff (x.order + n)) @[simp] lemma power_series_part_coeff (x : laurent_series R) (n : ℕ) : power_series.coeff R n x.power_series_part = x.coeff (x.order + n) := power_series.coeff_mk _ _ @[simp] lemma power_series_part_zero : power_series_part (0 : laurent_series R) = 0 := by { ext, simp } @[simp] lemma power_series_part_eq_zero (x : laurent_series R) : x.power_series_part = 0 ↔ x = 0 := begin split, { contrapose!, intro h, rw [power_series.ext_iff, not_forall], refine ⟨0, _⟩, simp [coeff_order_ne_zero h] }, { rintro rfl, simp } end @[simp] lemma single_order_mul_power_series_part (x : laurent_series R) : (single x.order 1 : laurent_series R) * x.power_series_part = x := begin ext n, rw [← sub_add_cancel n x.order, single_mul_coeff_add, sub_add_cancel, one_mul], by_cases h : x.order ≤ n, { rw [int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), coeff_coe_power_series, power_series_part_coeff, ← int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), add_sub_cancel'_right] }, { rw [coe_power_series, of_power_series_apply, emb_domain_notin_range], { contrapose! h, exact order_le_of_coeff_ne_zero h.symm }, { contrapose! h, simp only [set.mem_range, rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk, int.nat_cast_eq_coe_nat] at h, obtain ⟨m, hm⟩ := h, rw [← sub_nonneg, ← hm], exact int.zero_le_of_nat _ } } end lemma of_power_series_power_series_part (x : laurent_series R) : of_power_series ℤ R x.power_series_part = single (-x.order) 1 * x := begin refine eq.trans _ (congr rfl x.single_order_mul_power_series_part), rw [← mul_assoc, single_mul_single, neg_add_self, mul_one, ← C_apply, C_one, one_mul, coe_power_series], end @[simp] lemma of_power_series_X : of_power_series ℤ R power_series.X = single 1 1 := begin ext n, cases n, { rw [int.of_nat_eq_coe, ← int.nat_cast_eq_coe_nat, of_power_series_apply_coeff], by_cases h1 : n = 1, { simp [h1] }, { rw [power_series.coeff_X, single_coeff, if_neg h1, if_neg], contrapose! h1, rw [← nat.cast_one] at h1, exact nat.cast_injective h1 } }, { rw [of_power_series_apply, emb_domain_notin_range, single_coeff_of_ne], { dec_trivial }, rw [set.mem_range, not_exists], intro m, simp only [rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk, int.nat_cast_eq_coe_nat], dec_trivial } end end semiring @[simp] lemma of_power_series_X_pow [comm_semiring R] (n : ℕ) : of_power_series ℤ R (power_series.X ^ n) = single (n : ℤ) 1 := begin rw ring_hom.map_pow, induction n with n ih, { refl }, rw [pow_succ, int.coe_nat_succ, ih, of_power_series_X, mul_comm, single_mul_single, one_mul], end /-- The localization map from power series to Laurent series. -/ @[simps] def of_power_series_localization [comm_ring R] : localization_map (submonoid.powers (power_series.X : power_series R)) (laurent_series R) := ring_hom.to_localization_map (hahn_series.of_power_series ℤ R) (begin rintro ⟨_, n, rfl⟩, refine ⟨⟨single (n : ℤ) 1, single (-n : ℤ) 1, _, _⟩, _⟩, { simp only [single_mul_single, mul_one, add_right_neg], refl }, { simp only [single_mul_single, mul_one, add_left_neg], refl }, { simp } end) (begin intro z, by_cases h : 0 ≤ z.order, { refine ⟨⟨power_series.X ^ (int.nat_abs z.order) * power_series_part z, 1⟩, _⟩, simp only [ring_hom.map_one, mul_one, ring_hom.map_mul, of_power_series_X_pow, submonoid.coe_one], rw [int.nat_abs_of_nonneg h, ← coe_power_series, single_order_mul_power_series_part] }, { refine ⟨⟨power_series_part z, power_series.X ^ (int.nat_abs z.order), ⟨_, rfl⟩⟩, _⟩, simp only [of_power_series_power_series_part], rw [mul_comm _ z], refine congr rfl _, rw [subtype.coe_mk, of_power_series_X_pow, int.of_nat_nat_abs_of_nonpos], exact le_of_not_ge h } end) (begin intros x y, rw of_power_series_injective.eq_iff, split, { rintro rfl, exact ⟨1, rfl⟩ }, { rintro ⟨⟨_, n, rfl⟩, hc⟩, rw [← sub_eq_zero, ← sub_mul, power_series.ext_iff] at hc, rw [← sub_eq_zero, power_series.ext_iff], intro m, have h := hc (m + n), rw [linear_map.map_zero, subtype.coe_mk, power_series.X_pow_eq, power_series.monomial, power_series.coeff, finsupp.single_add, mv_power_series.coeff_add_mul_monomial, mul_one] at h, exact h } end) end laurent_series
f0cc9ab6332f206876d2d1b1bafea4cc8fd9e04b
fd3506535396cef3d1bdcf4ae5b87c8ed9ff2c2e
/migrated/nat.lean
a81b65fd2c284bd9b01a54e66a5755a6ae32f066
[]
no_license
williamdemeo/leanproved
77933dbcb8bfbae61a753ae31fa669b3ed8cda9d
d8c2e2ca0002b252fce049c4ff9be0e9e83a6374
refs/heads/master
1,598,674,802,432
1,437,528,488,000
1,437,528,488,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
685
lean
import theories.number_theory.primes data.nat open nat eq.ops namespace shadow section order lemma lt_succ_of_lt {i j : nat} : i < j → i < succ j := assume Plt, lt.trans Plt (self_lt_succ j) end order section power lemma pow_dvd_of_pow_succ_dvd {p i n : nat} : p^(succ i) ∣ n → p^i ∣ n := assume Psuccdvd, assert Pdvdsucc : p^i ∣ p^(succ i), from by rewrite [pow_succ]; apply dvd_of_eq_mul; apply rfl, dvd.trans Pdvdsucc Psuccdvd lemma dvd_of_pow_succ_dvd_mul_pow {p i n : nat} (Ppos : p > 0) : p^(succ i) ∣ (n * p^i) → p ∣ n := by rewrite [pow_succ']; apply dvd_of_mul_dvd_mul_right; apply pow_pos_of_pos _ Ppos end power section prime end prime end shadow
b1e838c127f981301f80fa228a4b390d10524e2d
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/01_polymorphicFunctions.lean
4b38191d4d3b7e1ae031fde4fe511955fe71c817
[]
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
936
lean
def id_nat : nat → nat := λ n, n def id_string : string → string := λ n, n def id_bool : bool → bool := λ n, n -- parametric polymorphism namespace hidden #check 1 #check "Hello" #check tt -- Types are terms #check nat #check string #check bool def id' : Π (α : Type), α → α := λ α, λ n, n #eval id' bool tt #eval id' string "Hello, Lean!" #eval id' nat 5 -- Type inference #eval id' _ tt #eval id' _ "Hello, Lean!" #eval id' _ 5 -- implicit type inference universe u def id : Π { α : Type u}, α → α := λ α, fun a, a /- λ α, λ n, n -/ #eval id tt #eval id "Hello, Lean!" #eval id 5 -- error cases #eval id _ -- can't infer α #eval id nat _ -- type error! -- turn off implicit typing #eval (@id nat) _ -- all goot, expects ℕ #check 1 #check nat #check Type #check Type 1 #reduce (id nat) end hidden #check hidden.id
ed920d07a943f6def503c6d98c2858e2fb4d2723
4efff1f47634ff19e2f786deadd394270a59ecd2
/docs/tutorial/category_theory/calculating_colimits_in_Top.lean
b74ebc59c3d0e3f1c15cb82a030a92fd99b1f8f7
[ "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
3,567
lean
import topology.category.Top.limits import category_theory.limits.shapes import topology.instances.real import topology.tactic /-! This file contains some demos of using the (co)limits API to do topology. -/ noncomputable theory open category_theory open category_theory.limits def R : Top := Top.of ℝ def I : Top := Top.of (set.Icc 0 1 : set ℝ) def pt : Top := Top.of unit section MappingCylinder -- Let's construct the mapping cylinder. def to_pt (X : Top) : X ⟶ pt := { to_fun := λ _, unit.star, } -- We don't need to prove continuity: this is done automatically. def I₀ : pt ⟶ I := { to_fun := λ _, ⟨(0 : ℝ), by norm_num [set.left_mem_Icc]⟩, } def I₁ : pt ⟶ I := { to_fun := λ _, ⟨(1 : ℝ), by norm_num [set.right_mem_Icc]⟩, } def cylinder (X : Top) : Top := prod X I -- To define a map to the cylinder, we give a map to each factor. -- `prod.lift` is a helper method, providing a wrapper around `limit.lift` for binary products. def cylinder₀ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₀) def cylinder₁ (X : Top) : X ⟶ cylinder X := prod.lift (𝟙 X) (to_pt X ≫ I₁) -- The mapping cylinder is the pushout of the diagram -- X -- ↙ ↘ -- Y (X x I) -- (`pushout` is implemented just as a wrapper around `colimit`) is def mapping_cylinder {X Y : Top} (f : X ⟶ Y) : Top := pushout f (cylinder₁ X) /-- We construct the map from `X` into the "bottom" of the mapping cylinder for `f : X ⟶ Y`, as the composition of the inclusion of `X` into the bottom of the cylinder `prod X I`, followed by the map `pushout.inr` of `prod X I` into `mapping_cylinder f`. -/ def mapping_cylinder₀ {X Y : Top} (f : X ⟶ Y) : X ⟶ mapping_cylinder f := cylinder₀ X ≫ pushout.inr /-- The mapping cone is defined as the pushout of ``` X ↙ ↘ (Cyl f) pt ``` (where the left arrow is `mapping_cylinder₀`). This makes it an iterated colimit; one could also define it in one step as the colimit of ``` -- X X -- ↙ ↘ ↙ ↘ -- Y (X x I) pt ``` -/ def mapping_cone {X Y : Top} (f : X ⟶ Y) : Top := pushout (mapping_cylinder₀ f) (to_pt X) -- TODO Hopefully someone will write a nice tactic for generating diagrams quickly, -- and we'll be able to verify that this iterated construction is the same as the colimit -- over a single diagram. end MappingCylinder section Gluing -- Here's two copies of the real line glued together at a point. def f : pt ⟶ R := { to_fun := λ _, (0 : ℝ), } /-- Two copies of the real line glued together at 0. -/ def X : Top := pushout f f -- To define a map out of it, we define maps out of each copy of the line, -- and check the maps agree at 0. def g : X ⟶ R := pushout.desc (𝟙 _) (𝟙 _) rfl end Gluing universes v u w section Products /-- The countably infinite product of copies of `ℝ`. -/ def Y : Top := ∏ (λ n : ℕ, R) /-- We can define a point in this infinite product by specifying its coordinates. Let's define the point whose `n`-th coordinate is `n + 1` (as a real number). -/ def q : pt ⟶ Y := pi.lift (λ (n : ℕ), ⟨λ (_ : pt), (n + 1 : ℝ), by continuity⟩) -- "Looking under the hood", we see that `q` is a `subtype`, whose `val` is a function `unit → Y.α`. -- #check q.val -- q.val : pt.α → Y.α -- `q.property` is the fact this function is continuous (i.e. no content, since `pt` is a singleton) -- We can check that this function is definitionally just the function we specified. example : (q ()).val (9 : ℕ) = ((10 : ℕ) : ℝ) := rfl end Products
a6a78454d958d5ae01fbfe71a3272797dd4ba460
f09e92753b1d3d2eb3ce2cfb5288a7f5d1d4bd89
/src/for_mathlib/is_cover.lean
d0de1575c65768790fc50e290f1202fa6ef59e53
[ "Apache-2.0" ]
permissive
PatrickMassot/lean-perfectoid-spaces
7f63c581db26461b5a92d968e7563247e96a5597
5f70b2020b3c6d508431192b18457fa988afa50d
refs/heads/master
1,625,797,721,782
1,547,308,357,000
1,547,309,364,000
136,658,414
0
1
Apache-2.0
1,528,486,100,000
1,528,486,100,000
null
UTF-8
Lean
false
false
274
lean
import analysis.topology.topological_space definition is_cover {X γ : Type} (U : γ → set X) := ∀ x, ∃ i, x ∈ U i structure is_open_cover {X γ : Type} [H : topological_space X] (U : γ → set X) := (is_open : ∀ i, H.is_open (U i)) (is_cover : is_cover U)
c5c0c6487a6a1cf645de78920a1e4c17f698661f
f4e8ebc2be0df6ce96aeff2aea4781e55522cb21
/src/solutions/02_iff_if_and.lean
896fced5baf5a544c1937f1cccd5cdd44747837f
[ "Apache-2.0" ]
permissive
robertylewis/tutorials
fb8a78d1352405077d4c82c6a04deabb32c1e37b
d3e1ac9ce73b9ed93a20036ce2a354ee923c783e
refs/heads/master
1,666,261,949,784
1,591,464,085,000
1,591,464,607,000
270,056,466
0
0
Apache-2.0
1,591,465,315,000
1,591,465,314,000
null
UTF-8
Lean
false
false
15,330
lean
import data.real.basic /- In the previous file, we saw how to rewrite using equalities. The analogue operation with mathematical statements is rewriting using equivalences. This is also done using the `rw` tactic. Lean uses ↔ to denote equivalence instead of ⇔. In the following exercises we will use the lemma: sub_nonneg {x y : ℝ} : 0 ≤ y - x ↔ x ≤ y The curly braces around x and y instead of parentheses mean Lean will always try to figure out what x and y are from context, unless we really insist on telling it (we'll see how to insist much later). Let's not worry about that for now. In order to announce an intermediate statement we use: have my_name : my statement, This triggers the apparition of a new goal: proving the statement. After this is done, the statement becomes available under the name `my_name`. We can focus on the current goal by typing tactics between curly braces. -/ example {a b c : ℝ} (hab : a ≤ b) : c + a ≤ c + b := begin rw ← sub_nonneg, have key : (c + b) - (c + a) = b - a, -- Here we introduce an intermediate statement named key { ring, }, -- and prove it between curly braces rw key, -- we can now use the key statement rw sub_nonneg, exact hab, end /- Of course the previous lemma is already in the core library, named `add_le_add_left`, so we can use it below. Let's prove a variation (without invoking commutativity of addition since this would spoil our fun). -/ -- 0009 example {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c := begin -- sorry have key : (b + c) - (a + c) = b - a, { ring }, rw ← sub_nonneg, rw key, rw sub_nonneg, exact hab, -- sorry end /- Let's see how we could use this lemma. It is already in the core library, under the name `add_le_add_right`: add_le_add_right {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c This can be read as: "add_le_add_right is a function that will take as input real numbers a and b, an assumption `hab` claiming a ≤ b and a real number c, and will output a proof of a + c ≤ b + c". In addition, recall that curly braces around a b mean Lean will figure out those arguments unless we insist to help. This is because they can be deduced from the next argument `hab`. So it will be sufficient to feed `hab` and c to this function. -/ example {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : by exact add_le_add_right ha b, end /- In the second line of the above proof, we need to prove 0 + b ≤ a + b. The proof after the colon says: this is exactly lemma `add_le_add_right` applied to ha and b. Actually the `calc` block expects proof terms, and the `by` keyword is used to tell Lean we will use tactics to build such a proof term. But since the only tactic used in this block is `exact`, we can skip tactics entirely, and write: -/ example (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : add_le_add_right ha b, end /- Let's do a variant. -/ -- 0010 example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin -- sorry calc a = a + 0 : by ring ... ≤ a + b : add_le_add_left hb a, -- sorry end /- The two preceding examples are in the core library : le_add_of_nonneg_left {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b le_add_of_nonneg_right {a b : ℝ} (hb : 0 ≤ b) : a ≤ a + b Again, there won't be any need to memorize those names, we will soon see how to get rid of such goals automatically. But we can already try to understand how their names are built: "le_add" describe the conclusion "less or equal than some addition" It comes first because we are focussed on proving stuff, and auto-completion works by looking at the beginning of words. "of" introduces assumptions. "nonneg" is Lean's abbreviation for non-negative. "left" or "right" disambiguates between the two variations. Let's use those lemmas by hand for now. -/ -- 0011 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin -- sorry calc 0 ≤ a : ha ... ≤ a + b : le_add_of_nonneg_right hb, -- sorry end /- And let's combine with our earlier lemmas. -/ -- 0012 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin -- sorry calc a + c ≤ b + c : add_le_add_right hab c ... ≤ b + d : add_le_add_left hcd b, -- sorry end /- In the above examples, we prepared proofs of assumptions of our lemmas beforehand, so that we could feed them to the lemmas. This is called forward reasonning. The `calc` proofs also belong to this category. We can also announce the use of a lemma, and provide proofs after the fact, using the `apply` tactic. This is called backward reasonning because we get the conclusion first, and provide proofs later. Using `rw` on the goal (rather than on an assumption from the local context) is also backward reasonning. Let's do that using the lemma mul_nonneg' {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : 0 ≤ x*y -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, have key : b*c - a*c = (b - a)*c, { ring }, rw key, apply mul_nonneg', -- Here we don't provide proofs for the lemma's assumptions -- Now we need to provide the proofs. { rw sub_nonneg, exact hab }, { exact hc }, end /- Let's prove the same statement using only forward reasonning: announcing stuff, proving it by working with known facts, moving forward. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rw ← sub_nonneg at hab, exact hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg' hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rw h₂ at h₁, exact h₁, }, rw sub_nonneg at h₃, exact h₃, end /- One reason why the backward reasoning proof is shorter is because Lean can infer of lot of things by comparing the goal and the lemma statement. Indeed in the `apply mul_nonneg'` line, we didn't need to tell Lean that x = b - a and y = c in the lemma. It was infered by "unification" between the lemma statement and the goal. To be fair to the forward reasoning version, we should introduce a convenient variation on `rw`. The `rwa` tactic performs rewrite and then looks for an assumption matching the goal. We can use it to rewrite our latest proof as: -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rwa ← sub_nonneg at hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg' hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rwa h₂ at h₁, }, rwa sub_nonneg at h₃, end /- Let's now combine forward and backward reasonning, to get our most efficient proof of this statement. Note in particular how unification is used to know what to prove inside the parentheses in the `mul_nonneg'` arguments. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, calc 0 ≤ (b - a)*c : mul_nonneg' (by rwa sub_nonneg) hc ... = b*c - a*c : by ring, end /- Let's now practice all three styles using: mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b sub_nonpos {a b : α} : a - b ≤ 0 ↔ a ≤ b -/ /- First using mostly backward reasonning -/ -- 0013 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin -- sorry rw ← sub_nonneg, have fact : a*c - b*c = (a - b)*c, ring, rw fact, apply mul_nonneg_of_nonpos_of_nonpos, { rwa sub_nonpos }, { exact hc }, -- sorry end /- Using forward reasonning -/ -- 0014 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin -- sorry have hab' : a - b ≤ 0, { rwa ← sub_nonpos at hab, }, have h₁ : 0 ≤ (a - b)*c, { exact mul_nonneg_of_nonpos_of_nonpos hab' hc }, have h₂ : (a - b)*c = a*c - b*c, { ring, }, have h₃ : 0 ≤ a*c - b*c, { rwa h₂ at h₁, }, rwa sub_nonneg at h₃, -- sorry end /-- Using a combination of both, with a `calc` block -/ -- 0015 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin -- sorry have hab' : a - b ≤ 0, { rwa sub_nonpos }, rw ← sub_nonneg, calc 0 ≤ (a - b)*c : mul_nonneg_of_nonpos_of_nonpos hab' hc ... = a*c - b*c : by ring, -- sorry end /- Let's now move to proving implications. Lean denotes implications using a simple arrow →, the same it uses for functions (say denoting the type of functions from ℕ to ℕ by ℕ → ℕ). This is because it sees a proof of P ⇒ Q as a function turning a proof of P into a proof Q. Many of the examples that we already met are implications under the hood. For instance we proved le_add_of_nonneg_left (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b But this can be rephrased as le_add_of_nonneg_left (a b : ℝ) : 0 ≤ a → b ≤ a + b In order to prove P → Q, we use the tactic `intros`, followed by an assumption name. This creates an assumption with that name asserting that P holds, and turns the goal into Q. Let's check we can go from our old version of `le_add_of_nonneg_left` to the new one. -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := begin intros ha, exact le_add_of_nonneg_left ha, end /- Actually Lean doesn't make any difference between those two versions. It is also happy with -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := le_add_of_nonneg_left /- No tactic state is shown in the above line because we don't even need to enter tactic mode using `begin` or `by`. Let's practise using `intros`. -/ -- 0016 example (a b : ℝ): 0 ≤ b → a ≤ a + b := begin -- sorry intros hb, calc a = a + 0 : by ring ... ≤ a + b : add_le_add_left hb a, -- sorry end /- What about lemmas having more than one assumption? For instance: add_nonneg {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b A natural idea is to use the conjunction operator (logical AND), which Lean denotes by ∧. Assumptions built using this operator can be decomposed using the `cases` tactic, which is a very general assumption-decomposing tactic. -/ example {a b : ℝ} : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b := begin intros hyp, cases hyp with ha hb, exact add_nonneg ha hb, end /- Needing that intermediate line invoking `cases` shows this formulation is not what is used by Lean. It rather sees `add_nonneg` as two nested implications: if a is non-negative then if b is non-negative then a+b is non-negative. It reads funny, but it is much more convenient to use in practice. -/ example {a b : ℝ} : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := add_nonneg /- The above pattern is so common that implications are defined as right-associative operators, hence parentheses are not needed above. Let's prove that the naive conjunction version implies the funny Lean version. For this we need to know how to prove a conjunction. The `split` tactic creates two goals from a conjunction goal. It can also be used to create two implication goals from an equivalence goal. -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha, intros hb, apply H, split, exact ha, exact hb, end /- Let's practice `cases` and `split`. In the next exercise, P, Q and R denote unspecified mathematical statements. -/ -- 0017 example (P Q R : Prop) : P ∧ Q → Q ∧ P := begin -- sorry intro hyp, cases hyp with hP hQ, split, exact hQ, exact hP, -- sorry end /- Of course using `split` only to be able to use `exact` twice in a row feels silly. One can also use the anonymous constructor syntax: ⟨ ⟩ Beware those are not parentheses but angle brackets. This is a generic way of providing compound objects to Lean when Lean already has a very clear idea of what it is waiting for. So we could have replaced the last three lines by: exact ⟨hQ, hP⟩ We can also combine the `intros` steps. We can now compress our earlier proof to: -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha hb, exact H ⟨ha, hb⟩, end /- The anonymous contructor trick actually also works in `intros` provided we use its recursive version `rintros`. So we can replace intro h, cases h with h₁ h₂ by rintros ⟨h₁, h₂⟩, Now redo the previous exercise using all those compressing techniques, in exactly two lines. -/ -- 0018 example (P Q R : Prop): P ∧ Q → Q ∧ P := begin -- sorry rintros ⟨hP, hQ⟩, exact ⟨hQ, hP⟩, -- sorry end /- We are ready to come back to the equivalence between the different formulations of lemmas having two assumptions. Remember the `split` tactic can be used to split an equivalence into two implications. -/ -- 0019 example (P Q R : Prop) : (P ∧ Q → R) ↔ (P → (Q → R)) := begin -- sorry split, { intros hyp hP hQ, exact hyp ⟨hP, hQ⟩ }, { rintro hyp ⟨hP, hQ⟩, exact hyp hP hQ }, -- sorry end /- If you used more than five lines in the above exercise then try to compress things (without simply removing line ends). One last compression technique: given a proof h of a conjunction P ∧ Q, one can get a proof of P using h.left and a proof of Q using h.right, without using cases. One can also use the more generic (but less legible) names h.1 and h.2. Similarly, given a proof h of P ↔ Q, one can get a proof of P → Q using h.mp and a proof of Q → P using h.mpr (or the generic h.1 and h.2 that are even less legible in this case). Before the final exercise in this file, let's make sure we'll be able to leave without learning 10 lemma names. The `linarith` tactic will prove any equality or inequality or contradiction that follows by linear combinations of assumptions from the context (with constant coefficients). -/ example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin linarith, end /- Now let's enjoy this for a while. -/ -- 0020 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin -- sorry linarith, -- sorry end /- And let's combine with our earlier lemmas. -/ -- 0021 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin -- sorry linarith, -- sorry end /- Final exercise In the last exercise of this file, we will use the divisibility relation on ℕ, denoted by ∣ (beware this is a unicode divisibility bar, not the ASCII pipe character), and the gcd function. The definitions are the usual ones, but our goal is to avoid using these definitions and only use the following three lemmas: dvd_refl (a : ℕ) : a ∣ a dvd_antisymm {a b : ℕ} : a ∣ b → b ∣ a → a = b := dvd_gcd_iff {a b c : ℕ} : c ∣ gcd a b ↔ c ∣ a ∧ c ∣ b -/ -- All functions and lemmas below are about natural numbers. open nat -- 0022 example (a b : ℕ) : a ∣ b ↔ gcd a b = a := begin -- sorry have fact : gcd a b ∣ a ∧ gcd a b ∣ b, { rw ← dvd_gcd_iff }, split, { intro h, apply dvd_antisymm fact.left, rw dvd_gcd_iff, exact ⟨dvd_refl a, h⟩ }, { intro h, rw ← h, exact fact.right }, -- sorry end
15b1e8df87ebd002bedde4cca7b706c1187e9dff
9995dfaf2c112e67489d4a6be1858e7b3c67ded6
/proofs.lean
ff6fe9ab60ab2aa1ed51faab9157092a6ded5ee9
[]
no_license
PJ41/proof-checking
dfe291be8e6a8872ec81e01c8326dc51ff06a17a
e7ce9c7905434f84e02e5707cec4f6a07749c4dd
refs/heads/master
1,596,760,214,588
1,570,386,047,000
1,570,386,047,000
213,219,595
0
0
null
null
null
null
UTF-8
Lean
false
false
3,722
lean
/- ****************** -/ /- *** PREDICATES *** -/ /- ****************** -/ /- Define a function called isOdd that takes an argument, n : ℕ, and returns a proposition that asserts that n is odd. The function will thus be a predicate on values of type ℕ. Hint: a number is odd if it's one more than an even number. -/ def isOdd (n :ℕ) : Prop := ∃ m : nat, 2 * m + 1 = n /- To test your predicate, use "example" to write and prove isOdd(15). -/ example : isOdd 15 := begin unfold isOdd, apply exists.intro 7, apply rfl, end /- Define isSmall : ℕ → Prop, to be a predicate that is true exactly when the argument, n, is such that n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 ∨ n = 4 ∨ n = 5. (Don't try to rewrite this proposition as an inequality; just use it as is.) -/ def isSmall (n :ℕ) : Prop := n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 ∨ n = 4 ∨ n = 5 /- Define a predicate, isBoth(n:ℕ) that is true exacly when n satisfies both the isOdd and isSmall predicates. Use isOdd and isSmall in your answer. -/ def isBoth (n : ℕ) : Prop := isOdd n ∧ isSmall n /- ******************* -/ /- *** DISJUNCTIONS ***-/ /- ******************* -/ /- Jane walks to school or she carries her lunch. In either case, she uses a bag. If she walks, she uses a bag for her books. If she carries her lunch, she uses a bag to carry her food. So if she walks, she uses a bag, and if she carries her lunch, she uses a bag. From the fact that she walks or carries her lunch, and from the added facts that in either case she uses a bag, we can conclude that she uses a bag. Using Walks, Carries, and Bag as names of propositions, write a Lean example that asserts the following proposition; then prove it. If Walks, Carries, and Bag are propositions, then if (Walks ∨ Carries) is true, and then if (Walks implies Bag) is true, and then if (Carries implies Bag) is true, then Bag is true. -/ example : ∀ (Walks Carries Bag : Prop), ((Walks ∨ Carries) ∧ (Walks → Bag) ∧ (Carries → Bag)) → Bag := begin assume W C B f, have f1 := f.1, cases f1 with w c, exact f.2.1 w, exact f.2.2 c, end /- Prove the following proposition. -/ example : ∀ (P Q R : Prop), (P ∧ Q) → (Q ∨ R) → (P ∨ R) := begin assume P Q R paq qar, exact or.inl paq.1, end /- ********************* -/ /- *** EXISTENTIALS *** -/ /- ********************* -/ /- Referring to the isBoth predicate you defined in question #1, state and prove the proposition that there *exists* a number, n, that satisfies isBoth. Remember that you can use the unfold tactic to expand the name of a predicate in a goal. Use "example" to state the proposition. -/ lemma pf3isOdd : isOdd 3 := begin unfold isOdd, apply exists.intro 1, apply rfl, end lemma pf3isSmall : isSmall 3 := begin unfold isSmall, apply or.intro_right, apply or.intro_right, apply or.intro_right, apply or.intro_left, apply rfl, end example : ∃ n : ℕ, isBoth n := begin unfold isBoth, apply exists.intro 3, have pfOdd := pf3isOdd, have pfSmall := pf3isSmall, exact and.intro pfOdd pfSmall, end /- Suppose that Heavy and Round are predicates on values of any type, T. Prove the proposition that if every t : T is Heavy (satisfies the Heavy predicate) and if there exists some t : T that is Round (satisfies the Round predicate) then there exists some t : T is both Heavy and Round (satisfies the conjunction of the two properties). -/ example : ∀ T : Type, ∀ (Heavy Round : T → Prop), (∀ t, Heavy t) → (∃ t, Round t) → (∃ t, Heavy t ∧ Round t) := begin assume T h r aht ert, apply exists.elim ert, assume x rt, apply exists.intro x, exact and.intro (aht x) rt, end
d5fb8a9b8df63a17400a515b9c2ed3f60864c12b
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/def13.lean
a41c43be30bc48f478aa5f85a62be9950b3ab454
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
586
lean
variable {α} (p : α → Prop) [DecidablePred p] def filter : List α → List α | [] => [] | a::as => if p a then a :: filter as else filter as theorem filter_nil : filter p [] = [] := rfl theorem filter_cons (a : α) (as : List α) : filter p (a :: as) = if p a then a :: filter p as else filter p as := rfl theorem filter_cons_of_pos {a : α} (as : List α) (h : p a) : filter p (a :: as) = a :: filter p as := by rw filter_cons; rw ifPos h theorem filter_cons_of_neg {a : α} (as : List α) (h : ¬ p a) : filter p (a :: as) = filter p as := by rw filter_cons; rw ifNeg h
2f26986901398895adce064102889fe069d73e89
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/well_founded_tactics.lean
92ad74b9af83e8ab3e45640b8546e0a25fc20c25
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
6,223
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta init.data.sigma.lex init.data.nat.lemmas init.data.list.instances import init.data.list.qsort /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_of_zero_lt_left (a b : nat) (h : 0 < b) : a < a + b := suffices a + 0 < a + b, by {simp at this, assumption}, by {apply nat.add_lt_add_left, assumption} /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.zero_lt_one_add (a : nat) : 0 < 1 + a := suffices 0 < a + 1, by {simp, assumption}, nat.zero_lt_succ _ /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_right (a b c : nat) : a < b → a < b + c := λ h, lt_of_lt_of_le h (nat.le_add_right _ _) /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_left (a b c : nat) : a < b → a < c + b := λ h, lt_of_lt_of_le h (nat.le_add_left _ _) namespace well_founded_tactics open tactic private meta def clear_wf_rec_goal_aux : list expr → tactic unit | [] := return () | (h::hs) := clear_wf_rec_goal_aux hs >> try (guard (h.local_pp_name.is_internal || h.is_aux_decl) >> clear h) meta def clear_internals : tactic unit := local_context >>= clear_wf_rec_goal_aux meta def unfold_wf_rel : tactic unit := dunfold [``has_well_founded.r] meta def is_psigma_mk : expr → tactic (expr × expr) | `(psigma.mk %%a %%b) := return (a, b) | _ := failed meta def process_lex : tactic unit → tactic unit | tac := do t ← target >>= whnf, if t.is_napp_of `psigma.lex 6 then let a := t.app_fn.app_arg in let b := t.app_arg in do (a₁, a₂) ← is_psigma_mk a, (b₁, b₂) ← is_psigma_mk b, (is_def_eq a₁ b₁ >> `[apply psigma.lex.right] >> process_lex tac) <|> (`[apply psigma.lex.left] >> tac) else tac private meta def unfold_sizeof_measure : tactic unit := dunfold [``sizeof_measure, ``measure, ``inv_image] private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns private meta def collect_sizeof_lemmas (e : expr) : tactic simp_lemmas := e.mfold simp_lemmas.mk $ λ c d s, if c.is_constant then match c.const_name with | name.mk_string "sizeof" p := do eqns ← get_eqn_lemmas_for tt c.const_name, add_simps s eqns | _ := return s end else return s private meta def unfold_sizeof_loop : tactic unit := do dunfold [``sizeof, ``has_sizeof.sizeof], S ← target >>= collect_sizeof_lemmas, (simplify_goal S >> unfold_sizeof_loop) <|> try simp meta def unfold_sizeof : tactic unit := unfold_sizeof_measure >> unfold_sizeof_loop /- The following section should be removed as soon as we implement the algebraic normalizer. -/ section simple_dec_tac open tactic expr private meta def collect_add_args : expr → list expr | `(%%a + %%b) := collect_add_args a ++ collect_add_args b | e := [e] private meta def mk_nat_add : list expr → tactic expr | [] := to_expr ``(0) | [a] := return a | (a::as) := do rs ← mk_nat_add as, to_expr ``(%%a + %%rs) private meta def mk_nat_add_add : list expr → list expr → tactic expr | [] b := mk_nat_add b | a [] := mk_nat_add a | a b := do t ← mk_nat_add a, s ← mk_nat_add b, to_expr ``(%%t + %%s) private meta def get_add_fn (e : expr) : expr := if is_napp_of e `has_add.add 4 then e.app_fn.app_fn else e private meta def prove_eq_by_perm (a b : expr) : tactic expr := (is_def_eq a b >> to_expr ``(eq.refl %%a)) <|> perm_ac (get_add_fn a) `(nat.add_assoc) `(nat.add_comm) a b private meta def num_small_lt (a b : expr) : bool := if a = b then ff else if is_napp_of a `has_one.one 2 then tt else if is_napp_of b `has_one.one 2 then ff else a.lt b private meta def sort_args (args : list expr) : list expr := args.qsort num_small_lt meta def cancel_nat_add_lt : tactic unit := do `(%%lhs < %%rhs) ← target, ty ← infer_type lhs >>= whnf, guard (ty = `(nat)), let lhs_args := collect_add_args lhs, let rhs_args := collect_add_args rhs, let common := lhs_args.bag_inter rhs_args, if common = [] then return () else do let lhs_rest := lhs_args.diff common, let rhs_rest := rhs_args.diff common, new_lhs ← mk_nat_add_add common (sort_args lhs_rest), new_rhs ← mk_nat_add_add common (sort_args rhs_rest), lhs_pr ← prove_eq_by_perm lhs new_lhs, rhs_pr ← prove_eq_by_perm rhs new_rhs, target_pr ← to_expr ``(congr (congr_arg (<) %%lhs_pr) %%rhs_pr), new_target ← to_expr ``(%%new_lhs < %%new_rhs), replace_target new_target target_pr, `[apply nat.add_lt_add_left] <|> `[apply nat.lt_add_of_zero_lt_left] meta def check_target_is_value_lt : tactic unit := do `(%%lhs < %%rhs) ← target, guard lhs.is_numeral meta def trivial_nat_lt : tactic unit := comp_val <|> `[apply nat.zero_lt_one_add] <|> assumption <|> (do check_target_is_value_lt, (`[apply nat.lt_add_right] >> trivial_nat_lt) <|> (`[apply nat.lt_add_left] >> trivial_nat_lt)) <|> failed end simple_dec_tac meta def default_dec_tac : tactic unit := abstract $ do clear_internals, unfold_wf_rel, process_lex (unfold_sizeof >> cancel_nat_add_lt >> trivial_nat_lt) end well_founded_tactics /-- Argument for using_well_founded The tactic `rel_tac` has to synthesize an element of type (has_well_founded A). The two arguments are: a local representing the function being defined by well founded recursion, and a list of recursive equations. The equations can be used to decide which well founded relation should be used. The tactic `dec_tac` has to synthesize decreasing proofs. -/ meta structure well_founded_tactics := (rel_tac : expr → list expr → tactic unit := λ _ _, tactic.apply_instance) (dec_tac : tactic unit := well_founded_tactics.default_dec_tac) meta def well_founded_tactics.default : well_founded_tactics := {}
7fd0e40b6363fb56ef1a075dc181ac952e387e5e
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/ring_theory/ideal/basic.lean
be50543493ad8e3bcbbfba3e518853169be1331c
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,658
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn import order.atoms import order.compactly_generated /-! # Ideals over a ring This file defines `ideal R`, the type of ideals over a commutative ring `R`. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support one-sided ideals, and ideals over non-commutative rings. See `algebra.ring_quot` for quotients of non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators pointwise /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set α) = ⊤ := by rw [←set.singleton_one, span_singleton_one] /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal α) : Prop := (ne_top' : I ≠ ⊤) (mem_or_mem' : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal α} : is_prime I ↔ I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ theorem is_prime.ne_top {I : ideal α} (hI : I.is_prime) : I ≠ ⊤ := hI.1 theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem lemma bot_prime {R : Type*} [integral_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal α) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal α} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal α} (h : I.is_maximal) : I ≠ ⊤ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal α) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (α) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) bot_ne_top in ⟨I, hI⟩ variables {α} instance [nontrivial α] : nontrivial (ideal α) := begin rcases @exists_maximal α _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊤ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [comm_semiring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, ∃ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Type*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Type*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl end pi end ideal end semiring section comm_semiring variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring α] (I : ideal α) @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [integral_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin let J : ideal α := submodule.span α (insert x ↑I), have IJ : I ≤ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a • x + b)) := congr_arg (λ g : α, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : ℕ) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (λ m hm, (pow_succ a m).symm ▸ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := λ x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (λ hr, I.pow_mem_of_mem hr n hn)⟩ end ideal end comm_semiring section ring namespace ideal variables [ring α] (I : ideal α) {a b : α} lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end lemma eq_bot_of_prime [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (⊥ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} /-- The quotient `R/I` of a ring `R` by an ideal `I`. The ideal quotient of `I` is defined to equal the quotient of `I` as an `R`-submodule of `R`. This definition is marked `reducible` so that typeclass instances can be shared between `ideal.quotient I` and `submodule.quotient I`. -/ -- Note that at present `ideal` means a left-ideal, -- so this quotient is only useful in a commutative ring. -- We should develop quotients by two-sided ideals as well. @[reducible] def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} instance (I : ideal α) : has_one I.quotient := ⟨submodule.quotient.mk 1⟩ instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin have F := I.add_mem (I.mul_mem_left a₂ h₁) (I.mul_mem_right b₁ h₂), have : a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁, { rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] }, rw ← this at F, change _ ∈ _, convert F, end⟩ instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg submodule.quotient.mk (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/ def mk (I : ideal α) : α →+* I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ /- Two `ring_homs`s from the quotient by an ideal are equal if their compositions with `ideal.quotient.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext [non_assoc_semiring β] ⦃f g : I.quotient →+* β⦄ (h : f.comp (mk I) = g.comp (mk I)) : f = g := ring_hom.ext $ λ x, quotient.induction_on' x $ (ring_hom.congr_fun h : _) instance : inhabited (quotient I) := ⟨mk I 37⟩ protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I @[simp] theorem mk_eq_mk (x : α) : (submodule.quotient.mk x : quotient I) = mk I x := rfl lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nontrivial {I : ideal α} (hI : I ≠ ⊤) : nontrivial I.quotient := ⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩ lemma mk_surjective : function.surjective (mk I) := λ y, quotient.induction_on' y (λ x, exists.intro x rfl) /-- If `I` is an ideal of a commutative ring `R`, if `q : R → R/I` is the quotient map, and if `s ⊆ R` is a subset, then `q⁻¹(q(s)) = ⋃ᵢ(i + s)`, the union running over all `i ∈ I`. -/ lemma quotient_ring_saturate (I : ideal α) (s : set α) : mk I ⁻¹' (mk I '' s) = (⋃ x : I, (λ y, x.1 + y) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq], exact ⟨λ ⟨a, a_in, h⟩, ⟨⟨_, I.neg_mem h⟩, a, a_in, by simp⟩, λ ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact I.neg_mem hi⟩⟩ end instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), .. quotient.comm_ring I, .. quotient.nontrivial hI.1 } lemma is_integral_domain_iff_prime (I : ideal α) : is_integral_domain I.quotient ↔ I.is_prime := ⟨ λ ⟨h1, h2, h3⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h1⟩, λ x y h, by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h3 _ _ h}⟩, λ h, by exactI integral_domain.to_is_integral_domain I.quotient⟩ lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, rcases hI.exists_inv (mt eq_zero_iff_mem.2 h) with ⟨b, c, hc, abc⟩, rw [mul_comm] at abc, refine ⟨mk _ b, quot.sound _⟩, --quot.sound hb rw ← eq_sub_iff_add_eq' at abc, rw [abc, ← neg_mem_iff, neg_sub] at hc, convert hc, end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.integral_domain I } /-- If the quotient by an ideal is a field, then the ideal is maximal. -/ theorem maximal_of_is_field (I : ideal α) (hqf : is_field I.quotient) : I.is_maximal := begin apply ideal.is_maximal_iff.2, split, { intro h, rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩, exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) }, { intros J x hIJ hxnI hxJ, rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩, rw [← zero_add (1 : α), ← sub_self (x * y), sub_add], refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) } end /-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/ theorem maximal_ideal_iff_is_field_quotient (I : ideal α) : I.is_maximal ↔ is_field I.quotient := ⟨λ h, @field.to_is_field I.quotient (@ideal.quotient.field _ _ I h), λ h, maximal_of_is_field I h⟩ variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl end quotient /-- Quotienting by equal ideals gives equivalent rings. See also `submodule.quot_equiv_of_eq`. -/ def quot_equiv_of_eq {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) : I.quotient ≃+* J.quotient := { map_mul' := by { rintro ⟨x⟩ ⟨y⟩, refl }, .. submodule.quot_equiv_of_eq I J h } @[simp] lemma quot_equiv_of_eq_mk {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) (x : R) : quot_equiv_of_eq h (ideal.quotient.mk I x) = ideal.quotient.mk J x := rfl section pi variables (ι : Type v) /-- `R^n/I^n` is a `R/I`-module. -/ instance module_pi : module (I.quotient) (I.pi ι).quotient := begin refine { smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) _, .. }, { intros c₁ m₁ c₂ m₂ hc hm, change c₁ - c₂ ∈ I at hc, change m₁ - m₂ ∈ (I.pi ι) at hm, apply ideal.quotient.eq.2, have : c₁ • (m₂ - m₁) ∈ I.pi ι, { rw ideal.mem_pi, intro i, simp only [smul_eq_mul, pi.smul_apply, pi.sub_apply], apply ideal.mul_mem_left, rw ←ideal.neg_mem_iff, simpa only [neg_sub] using hm i }, rw [←ideal.add_mem_iff_left (I.pi ι) this, sub_eq_add_neg, add_comm, ←add_assoc, ←smul_add, sub_add_cancel, ←sub_eq_add_neg, ←sub_smul, ideal.mem_pi], exact λ i, I.mul_mem_right _ hc }, all_goals { rintro ⟨a⟩ ⟨b⟩ ⟨c⟩ <|> rintro ⟨a⟩, simp only [(•), submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk], change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, simp [mul_assoc, mul_add, add_mul] } end /-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/ noncomputable def pi_quot_equiv : (I.pi ι).quotient ≃ₗ[I.quotient] (ι → I.quotient) := { to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $ λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)), map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl }, map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl }, inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i), left_inv := begin rintro ⟨x⟩, exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _)) end, right_inv := begin intro x, ext i, obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i), simp_rw ←hr, convert quotient.out_eq' _ end } /-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is contained in `I^m`. -/ lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → α) (hi : ∀ i, x i ∈ I) (f : (ι → α) →ₗ[α] (ι' → α)) (i : ι') : f x i ∈ I := begin rw pi_eq_sum_univ x, simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul], exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j)) end end pi end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, finish, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : α} /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (α : Type u) [comm_ring α] extends nontrivial α : Prop := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) namespace local_ring variables [comm_ring α] [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal α := { carrier := nonunits α, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.mul_mem_left ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨maximal_ideal α, maximal_ideal.is_maximal α, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal α).1.1 $ λ x hx, hI.1.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} lemma eq_maximal_ideal {I : ideal α} (hI : I.is_maximal) : I = maximal_ideal α := unique_of_exists_unique (maximal_ideal_unique α) hI $ maximal_ideal.is_maximal α lemma le_maximal_ideal {J : ideal α} (hJ : J ≠ ⊤) : J ≤ maximal_ideal α := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring lemma local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨⟨hPnot_top, _⟩⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.1.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end lemma local_of_surjective {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] [nontrivial B] (f : A →+* B) (hf : function.surjective f) : local_ring B := { is_local := begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end, .. ‹nontrivial B› } /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) instance is_local_ring_hom_id (A : Type*) [semiring A] : is_local_ring_hom (ring_hom.id A) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff {A B : Type*} [semiring A] [semiring B] (f : A →+* B) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ instance is_local_ring_hom_comp {A B C : Type*} [semiring A] [semiring B] [semiring C] (g : B →+* C) (f : A →+* B) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring α] [semiring β] (f : α →+* β) [h : is_local_ring_hom f] {x : α} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.not_unit $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.is_unit_or_is_unit $ f.map_mul p q ▸ congr_arg f hx⟩ section open local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ maximal_ideal α) : f a ∈ maximal_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variable (α) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := (maximal_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (maximal_ideal α) noncomputable instance : inhabited (residue_field α) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk _ namespace residue_field variables {α β} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (maximal_ideal α) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit.mk0 a h } end field
94d0bae095da320889114fc1e7970d988e5c8972
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/cubical/squareover.hlean
2f833ef141be8a8e22f635b53d2e2bcabcee1e86
[ "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
17,129
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Squareovers -/ import .square open eq equiv is_equiv sigma namespace eq -- we give the argument B explicitly, because Lean would find (λa, B a) by itself, which -- makes the type uglier (of course the two terms are definitionally equal) inductive squareover {A : Type} (B : A → Type) {a₀₀ : A} {b₀₀ : B a₀₀} : Π{a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₁₂ : a₀₂ = a₂₂} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} (q₁₀ : pathover B b₀₀ p₁₀ b₂₀) (q₁₂ : pathover B b₀₂ p₁₂ b₂₂) (q₀₁ : pathover B b₀₀ p₀₁ b₀₂) (q₂₁ : pathover B b₂₀ p₂₁ b₂₂), Type := idsquareo : squareover B ids idpo idpo idpo idpo variables {A A' : Type} {B : A → Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A} /-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂} {b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄} /-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/ {q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂} /-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/ {q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄} /-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/ definition squareo := @squareover A B a₀₀ definition idsquareo [reducible] [constructor] (b₀₀ : B a₀₀) := @squareover.idsquareo A B a₀₀ b₀₀ definition idso [reducible] [constructor] := @squareover.idsquareo A B a₀₀ b₀₀ definition apds (f : Πa, B a) (s : square p₁₀ p₁₂ p₀₁ p₂₁) : squareover B s (apd f p₁₀) (apd f p₁₂) (apd f p₀₁) (apd f p₂₁) := square.rec_on s idso definition vrflo : squareover B vrfl q₁₀ q₁₀ idpo idpo := by induction q₁₀; exact idso definition hrflo : squareover B hrfl idpo idpo q₁₀ q₁₀ := by induction q₁₀; exact idso definition vdeg_squareover {p₁₀'} {s : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (r : change_path s q₁₀ = q₁₀') : squareover B (vdeg_square s) q₁₀ q₁₀' idpo idpo := by induction s; esimp at *; induction r; exact vrflo definition hdeg_squareover {p₀₁'} {s : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (r : change_path s q₀₁ = q₀₁') : squareover B (hdeg_square s) idpo idpo q₀₁ q₀₁' := by induction s; esimp at *; induction r; exact hrflo definition hconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₃₁ : squareover B s₃₁ q₃₀ q₃₂ q₂₁ q₄₁) : squareover B (hconcat s₁₁ s₃₁) (q₁₀ ⬝o q₃₀) (q₁₂ ⬝o q₃₂) q₀₁ q₄₁ := by induction t₃₁; exact t₁₁ definition vconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₁₃ : squareover B s₁₃ q₁₂ q₁₄ q₀₃ q₂₃) : squareover B (vconcat s₁₁ s₁₃) q₁₀ q₁₄ (q₀₁ ⬝o q₀₃) (q₂₁ ⬝o q₂₃) := by induction t₁₃; exact t₁₁ definition hinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (hinverse s₁₁) q₁₀⁻¹ᵒ q₁₂⁻¹ᵒ q₂₁ q₀₁ := by induction t₁₁; constructor definition vinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (vinverse s₁₁) q₁₂ q₁₀ q₀₁⁻¹ᵒ q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition eq_vconcato {q : b₀₀ =[p₁₀] b₂₀} (r : q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q q₁₂ q₀₁ q₂₁ := by induction r; exact t₁₁ definition vconcato_eq {q : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₁₂ = q) : squareover B s₁₁ q₁₀ q q₀₁ q₂₁ := by induction r; exact t₁₁ definition eq_hconcato {q : b₀₀ =[p₀₁] b₀₂} (r : q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q q₂₁ := by induction r; exact t₁₁ definition hconcato_eq {q : b₂₀ =[p₂₁] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₂₁ = q) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q := by induction r; exact t₁₁ definition pathover_vconcato {p : a₀₀ = a₂₀} {sp : p = p₁₀} {q : b₀₀ =[p] b₂₀} (r : change_path sp q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝pv s₁₁) q q₁₂ q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ definition vconcato_pathover {p : a₀₂ = a₂₂} {sp : p₁₂ = p} {q : b₀₂ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₁₂ = q) : squareover B (s₁₁ ⬝vp sp) q₁₀ q q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ definition pathover_hconcato {p : a₀₀ = a₀₂} {sp : p = p₀₁} {q : b₀₀ =[p] b₀₂} (r : change_path sp q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝ph s₁₁) q₁₀ q₁₂ q q₂₁ := by induction sp; induction r; exact t₁₁ definition hconcato_pathover {p : a₂₀ = a₂₂} {sp : p₂₁ = p} {q : b₂₀ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₂₁ = q) : squareover B (s₁₁ ⬝hp sp) q₁₀ q₁₂ q₀₁ q := by induction sp; induction r; exact t₁₁ -- relating squareovers to squares definition square_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁) := by induction t₁₁; esimp; constructor /- definition squareover_of_square (q : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁)) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := sorry -/ definition square_of_squareover_ids {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (so : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r)) : square t b l r := begin note H := square_of_squareover so, -- use apply ... in rewrite [▸* at H,+idp_con at H,+ap_id at H,↑pathover_idp_of_eq at H], rewrite [+to_right_inv !(pathover_equiv_tr_eq (refl a)) at H], exact H end definition squareover_ids_of_square {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (q : square t b l r) : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r) := square.rec_on q idso -- relating pathovers to squareovers definition pathover_of_squareover' (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := by induction t₁₁; constructor definition pathover_of_squareover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (t₁₁ : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂ := begin revert s t₁₁, refine equiv_rect' !square_equiv_eq⁻¹ᵉ (λa b, squareover B b _ _ _ _ → _) _, intro s, exact pathover_of_squareover' end definition squareover_of_pathover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (r : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂) : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₁₂; esimp [concato] at r;induction r;induction q₂₁;induction q₁₀;constructor definition pathover_top_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ =[eq_top_of_square s₁₁] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition squareover_of_pathover_top {s : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹} (r : q₁₀ =[s] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B (square_of_eq_top s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₂₁; induction q₁₂; esimp at r;induction r;induction q₁₀;constructor definition pathover_of_hdeg_squareover {p₀₁' : a₀₀ = a₀₂} {r : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (hdeg_square r) idpo idpo q₀₁ q₀₁') : q₀₁ =[r] q₀₁' := by induction r; induction q₀₁'; exact (pathover_of_squareover' t)⁻¹ᵒ definition pathover_of_vdeg_squareover {p₁₀' : a₀₀ = a₂₀} {r : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (t : squareover B (vdeg_square r) q₁₀ q₁₀' idpo idpo) : q₁₀ =[r] q₁₀' := by induction r; induction q₁₀'; exact pathover_of_squareover' t definition squareover_of_eq_top (r : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := begin induction s₁₁, revert q₁₂ q₁₀ r, eapply idp_rec_on q₂₁, clear q₂₁, intro q₁₂, eapply idp_rec_on q₁₂, clear q₁₂, esimp, intros, induction r, eapply idp_rec_on q₁₀, constructor end definition eq_top_of_squareover (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction r; reflexivity definition change_square {s₁₁'} (p : s₁₁ = s₁₁') (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁' q₁₀ q₁₂ q₀₁ q₂₁ := p ▸ r /- definition squareover_equiv_pathover (q₁₀ : b₀₀ =[p₁₀] b₂₀) (q₁₂ : b₀₂ =[p₁₂] b₂₂) (q₀₁ : b₀₀ =[p₀₁] b₀₂) (q₂₁ : b₂₀ =[p₂₁] b₂₂) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ ≃ q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := begin fapply equiv.MK, { exact pathover_of_squareover}, { intro r, rewrite [-to_left_inv !square_equiv_eq s₁₁], apply squareover_of_pathover, exact r}, { intro r, }, --need characterization of squareover lying over ids. { intro s, induction s, apply idp}, end -/ definition eq_of_vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (p : squareover B vrfl q₁₀ q₁₀' idpo idpo) : q₁₀ = q₁₀' := begin note H := square_of_squareover p, -- use apply ... in induction p₁₀, -- if needed we can remove this induction and use con_tr_idp in types/eq2 rewrite [▸* at H,idp_con at H,+ap_id at H], let H' := eq_of_vdeg_square H, exact eq_of_fn_eq_fn !pathover_equiv_tr_eq H' end -- definition vdeg_tr_squareover {q₁₂ : p₀₁ ▸ b₀₀ =[p₁₂] p₂₁ ▸ b₂₀} (r : q₁₀ =[_] q₁₂) -- : squareover B s₁₁ q₁₀ q₁₂ !pathover_tr !pathover_tr := -- by induction p;exact vrflo /- A version of eq_pathover where the type of the equality also varies -/ definition eq_pathover_dep {f g : Πa, B a} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : squareover B hrfl (pathover_idp_of_eq q) (pathover_idp_of_eq r) (apd f p) (apd g p)) : q =[p] r := begin induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_square, exact square_of_squareover_ids s end /- charcaterization of pathovers in pathovers -/ -- in this version the fibration (B) of the pathover does not depend on the variable (a) definition pathover_pathover {a' a₂' : A'} {p : a' = a₂'} {f g : A' → A} {b : Πa, B (f a)} {b₂ : Πa, B (g a)} {q : Π(a' : A'), f a' = g a'} (r : pathover B (b a') (q a') (b₂ a')) (r₂ : pathover B (b a₂') (q a₂') (b₂ a₂')) (s : squareover B (natural_square_tr q p) r r₂ (pathover_ap B f (apd b p)) (pathover_ap B g (apd b₂ p))) : pathover (λa, pathover B (b a) (q a) (b₂ a)) r p r₂ := begin induction p, esimp at s, apply pathover_idp_of_eq, apply eq_of_vdeg_squareover, exact s end definition squareover_change_path_left {p₀₁' : a₀₀ = a₀₂} (r : p₀₁' = p₀₁) {q₀₁ : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (r ⬝ph s₁₁) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ (change_path r q₀₁) q₂₁ := by induction r; exact t definition squareover_change_path_right {p₂₁' : a₂₀ = a₂₂} (r : p₂₁' = p₂₁) {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r⁻¹) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r q₂₁) := by induction r; exact t definition squareover_change_path_right' {p₂₁' : a₂₀ = a₂₂} (r : p₂₁ = p₂₁') {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r⁻¹ q₂₁) := by induction r; exact t /- You can construct a square in a sigma-type by giving a squareover -/ definition square_dpair_eq_dpair {a₀₀ a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} {p₁₂ : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂} {q₁₂ : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (dpair_eq_dpair p₁₀ q₁₀) (dpair_eq_dpair p₁₂ q₁₂) (dpair_eq_dpair p₀₁ q₀₁) (dpair_eq_dpair p₂₁ q₂₁) := by induction t₁₁; constructor definition sigma_square {v₀₀ v₂₀ v₀₂ v₂₂ : Σa, B a} {p₁₀ : v₀₀ = v₂₀} {p₀₁ : v₀₀ = v₀₂} {p₂₁ : v₂₀ = v₂₂} {p₁₂ : v₀₂ = v₂₂} (s₁₁ : square p₁₀..1 p₁₂..1 p₀₁..1 p₂₁..1) (t₁₁ : squareover B s₁₁ p₁₀..2 p₁₂..2 p₀₁..2 p₂₁..2) : square p₁₀ p₁₂ p₀₁ p₂₁ := begin induction v₀₀, induction v₂₀, induction v₀₂, induction v₂₂, rewrite [▸* at *, -sigma_eq_eta p₁₀, -sigma_eq_eta p₁₂, -sigma_eq_eta p₀₁, -sigma_eq_eta p₂₁], exact square_dpair_eq_dpair s₁₁ t₁₁ end end eq
fc56090e838da95f6f3454e61baa22772b69b191
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.28.lean
7a92e70e0080bcf6b7d807fc421b7fc862cbc4ba
[]
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
300
lean
/- page 59 -/ import standard import data.nat open nat variable f : ℕ → ℕ premise H : ∀ x : ℕ, f x ≤ f (x + 1) -- BEGIN example : f 0 ≤ f 3 := have f 0 ≤ f 1, from H 0, have f 0 ≤ f 2, from le.trans `f 0 ≤ f 1` (H 1), show f 0 ≤ f 3, from le.trans `f 0 ≤ f 2` (H 2) -- END
415f0b807c6338bae64b8c64a4a259c9dbac9026
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/padics/padic_norm.lean
50d5e71656b944b29b638bd0e84aef9039afbcc4
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
26,096
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import ring_theory.int.basic import algebra.field_power import ring_theory.multiplicity import data.real.cau_seq import tactic.ring_exp import tactic.basic /-! # p-adic norm This file defines the p-adic valuation and the p-adic norm on ℚ. The p-adic valuation on ℚ is the difference of the multiplicities of `p` in the numerator and denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate assumptions on p. The valuation induces a norm on ℚ. This norm is a nonarchimedean absolute value. It takes values in {0} ∪ {1/p^k | k ∈ ℤ}. ## Notations This file uses the local notation `/.` for `rat.mk`. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation -/ universe u open nat open_locale rat open multiplicity /-- For `p ≠ 1`, the p-adic valuation of an integer `z ≠ 0` is the largest natural number `n` such that p^n divides z. `padic_val_rat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the valuation of `q.denom`. If `q = 0` or `p = 1`, then `padic_val_rat p q` defaults to 0. -/ def padic_val_rat (p : ℕ) (q : ℚ) : ℤ := if h : q ≠ 0 ∧ p ≠ 1 then (multiplicity (p : ℤ) q.num).get (multiplicity.finite_int_iff.2 ⟨h.2, rat.num_ne_zero_of_ne_zero h.1⟩) - (multiplicity (p : ℤ) q.denom).get (multiplicity.finite_int_iff.2 ⟨h.2, by exact_mod_cast rat.denom_ne_zero _⟩) else 0 /-- A simplification of the definition of `padic_val_rat p q` when `q ≠ 0` and `p` is prime. -/ lemma padic_val_rat_def (p : ℕ) [hp : fact p.prime] {q : ℚ} (hq : q ≠ 0) : padic_val_rat p q = (multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp.ne_one, rat.num_ne_zero_of_ne_zero hq⟩) - (multiplicity (p : ℤ) q.denom).get (finite_int_iff.2 ⟨hp.ne_one, by exact_mod_cast rat.denom_ne_zero _⟩) := dif_pos ⟨hq, hp.ne_one⟩ namespace padic_val_rat open multiplicity variables {p : ℕ} /-- `padic_val_rat p q` is symmetric in `q`. -/ @[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q := begin unfold padic_val_rat, split_ifs, { simp [-add_comm]; refl }, { exfalso, simp * at * }, { exfalso, simp * at * }, { refl } end /-- `padic_val_rat p 1` is 0 for any `p`. -/ @[simp] protected lemma one : padic_val_rat p 1 = 0 := by unfold padic_val_rat; split_ifs; simp * /-- For `p ≠ 0, p ≠ 1, `padic_val_rat p p` is 1. -/ @[simp] lemma padic_val_rat_self (hp : 1 < p) : padic_val_rat p p = 1 := by unfold padic_val_rat; split_ifs; simp [*, nat.one_lt_iff_ne_zero_and_ne_one] at * /-- The p-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`. -/ lemma padic_val_rat_of_int (z : ℤ) (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get (finite_int_iff.2 ⟨hp, hz⟩) := by rw [padic_val_rat, dif_pos]; simp *; refl end padic_val_rat /-- A convenience function for the case of `padic_val_rat` when both inputs are natural numbers. -/ def padic_val_nat (p : ℕ) (n : ℕ) : ℕ := int.to_nat (padic_val_rat p n) section padic_val_nat /-- `padic_val_nat` is defined as an `int.to_nat` cast; this lemma ensures that the cast is well-behaved. -/ lemma zero_le_padic_val_rat_of_nat (p n : ℕ) : 0 ≤ padic_val_rat p n := begin unfold padic_val_rat, split_ifs, { simp, }, { trivial, }, end /-- `padic_val_rat` coincides with `padic_val_nat`. -/ @[simp, norm_cast] lemma padic_val_rat_of_nat (p n : ℕ) : ↑(padic_val_nat p n) = padic_val_rat p n := begin unfold padic_val_nat, rw int.to_nat_of_nonneg (zero_le_padic_val_rat_of_nat p n), end /-- A simplification of `padic_val_nat` when one input is prime, by analogy with `padic_val_rat_def`. -/ lemma padic_val_nat_def {p : ℕ} [hp : fact p.prime] {n : ℕ} (hn : n ≠ 0) : padic_val_nat p n = (multiplicity p n).get (multiplicity.finite_nat_iff.2 ⟨nat.prime.ne_one hp, bot_lt_iff_ne_bot.mpr hn⟩) := begin have n_nonzero : (n : ℚ) ≠ 0, by simpa only [cast_eq_zero, ne.def], -- Infinite loop with @simp padic_val_rat_of_nat unless we restrict the available lemmas here, -- hence the very long list simpa only [ int.coe_nat_multiplicity p n, rat.coe_nat_denom n, (padic_val_rat_of_nat p n).symm, int.coe_nat_zero, int.coe_nat_inj', sub_zero, get_one_right, int.coe_nat_succ, zero_add, rat.coe_nat_num ] using padic_val_rat_def p n_nonzero, end lemma one_le_padic_val_nat_of_dvd {n p : nat} [prime : fact p.prime] (nonzero : n ≠ 0) (div : p ∣ n) : 1 ≤ padic_val_nat p n := begin rw @padic_val_nat_def _ prime _ nonzero, let one_le_mul : _ ≤ multiplicity p n := @multiplicity.le_multiplicity_of_pow_dvd _ _ _ p n 1 (begin norm_num, exact div end), simp only [enat.coe_one] at one_le_mul, rcases one_le_mul with ⟨_, q⟩, dsimp at q, solve_by_elim, end @[simp] lemma padic_val_nat_zero (m : nat) : padic_val_nat m 0 = 0 := by simpa @[simp] lemma padic_val_nat_one (m : nat) : padic_val_nat m 1 = 0 := by simp [padic_val_nat] end padic_val_nat namespace padic_val_rat open multiplicity variables (p : ℕ) [p_prime : fact p.prime] include p_prime /-- The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`. -/ lemma finite_int_prime_iff {p : ℕ} [p_prime : fact p.prime] {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 := by simp [finite_int_iff, ne.symm (ne_of_lt (p_prime.one_lt))] /-- A rewrite lemma for `padic_val_rat p q` when `q` is expressed in terms of `rat.mk`. -/ protected lemma defn {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) : padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.one_lt, λ hn, by simp * at *⟩) - (multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt p_prime.one_lt, λ hd, by simp * at *⟩) := have hn : n ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqz qdf, have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf, let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hn hd qdf in by rw [padic_val_rat, dif_pos]; simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime), (ne.symm (ne_of_lt p_prime.one_lt)), hqz] /-- A rewrite lemma for `padic_val_rat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r := have q*r = (q.num * r.num) /. (↑q.denom * ↑r.denom), by rw_mod_cast rat.mul_num_denom, have hq' : q.num /. q.denom ≠ 0, by rw rat.num_denom; exact hq, have hr' : r.num /. r.denom ≠ 0, by rw rat.num_denom; exact hr, have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 p_prime, begin rw [padic_val_rat.defn p (mul_ne_zero hq hr) this], conv_rhs { rw [←(@rat.num_denom q), padic_val_rat.defn p hq', ←(@rat.num_denom r), padic_val_rat.defn p hr'] }, rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp [add_comm, add_left_comm, sub_eq_add_neg] end /-- A rewrite lemma for `padic_val_rat p (q^k) with condition `q ≠ 0`. -/ protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} : padic_val_rat p (q ^ k) = k * padic_val_rat p q := by induction k; simp [*, padic_val_rat.mul _ hq (pow_ne_zero _ hq), pow_succ, add_mul, add_comm] /-- A rewrite lemma for `padic_val_rat p (q⁻¹)` with condition `q ≠ 0`. -/ protected lemma inv {q : ℚ} (hq : q ≠ 0) : padic_val_rat p (q⁻¹) = -padic_val_rat p q := by rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul p (inv_ne_zero hq) hq, inv_mul_cancel hq, padic_val_rat.one] /-- A rewrite lemma for `padic_val_rat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r := by rw [div_eq_mul_inv, padic_val_rat.mul p hq (inv_ne_zero hr), padic_val_rat.inv p hr, sub_eq_add_neg] /-- A condition for `padic_val_rat p (n₁ / d₁) ≤ padic_val_rat p (n₂ / d₂), in terms of divisibility by `p^n`. -/ lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ} (hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) : padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔ ∀ (n : ℕ), ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ := have hf1 : finite (p : ℤ) (n₁ * d₂), from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂), have hf2 : finite (p : ℤ) (n₂ * d₁), from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁), by conv { to_lhs, rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl, padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le], norm_cast, rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf1, add_comm, ← multiplicity.mul' (nat.prime_iff_prime_int.1 p_prime) hf2, enat.get_le_get, multiplicity_le_multiplicity_iff] } /-- Sufficient conditions to show that the p-adic valuation of `q` is less than or equal to the p-adic vlauation of `q + r`. -/ theorem le_padic_val_rat_add_of_le {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_val_rat p q ≤ padic_val_rat p (q + r) := have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq, have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr, have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hqreq : q + r = (((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ)), from rat.add_num_denom _ _, have hqrd : q.num * ↑(r.denom) + ↑(q.denom) * r.num ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqr hqreq, begin conv_lhs { rw ←(@rat.num_denom q) }, rw [hqreq, padic_val_rat_le_padic_val_rat_iff p hqn hqrd hqd (mul_ne_zero hqd hrd), ← multiplicity_le_multiplicity_iff, mul_left_comm, multiplicity.mul (nat.prime_iff_prime_int.1 p_prime), add_mul], rw [←(@rat.num_denom q), ←(@rat.num_denom r), padic_val_rat_le_padic_val_rat_iff p hqn hrn hqd hrd, ← multiplicity_le_multiplicity_iff] at h, calc _ ≤ min (multiplicity ↑p (q.num * ↑(r.denom) * ↑(q.denom))) (multiplicity ↑p (↑(q.denom) * r.num * ↑(q.denom))) : (le_min (by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 p_prime), add_comm]) (by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ) (_ * _) (nat.prime_iff_prime_int.1 p_prime)]; exact add_le_add_left h _)) ... ≤ _ : min_le_multiplicity_add end /-- The minimum of the valuations of `q` and `r` is less than or equal to the valuation of `q + r`. -/ theorem min_le_padic_val_rat_add {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) (hqr : q + r ≠ 0) : min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) := (le_total (padic_val_rat p q) (padic_val_rat p r)).elim (λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le _ hq hr hqr h) (λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le _ hr hq (by rwa add_comm) h) open_locale big_operators /-- A finite sum of rationals with positive p-adic valuation has positive p-adic valuation (if the sum is non-zero). -/ theorem sum_pos_of_pos {n : ℕ} {F : ℕ → ℚ} (hF : ∀ i, i < n → 0 < padic_val_rat p (F i)) (hn0 : ∑ i in finset.range n, F i ≠ 0) : 0 < padic_val_rat p (∑ i in finset.range n, F i) := begin induction n with d hd, { exact false.elim (hn0 rfl) }, { rw finset.sum_range_succ at hn0 ⊢, by_cases h : ∑ (x : ℕ) in finset.range d, F x = 0, { rw [h, add_zero], exact hF d (lt_add_one _) }, { refine lt_of_lt_of_le _ (min_le_padic_val_rat_add p (λ h1, _) h hn0), { refine lt_min (hF d (lt_add_one _)) (hd (λ i hi, _) h), exact hF _ (lt_trans hi (lt_add_one _)) }, { have h2 := hF d (lt_add_one _), rw h1 at h2, exact lt_irrefl _ h2 } } } end end padic_val_rat namespace padic_val_nat /-- A rewrite lemma for `padic_val_nat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma mul (p : ℕ) [p_prime : fact p.prime] {q r : ℕ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_nat p (q * r) = padic_val_nat p q + padic_val_nat p r := begin apply int.coe_nat_inj, simp only [padic_val_rat_of_nat, nat.cast_mul], rw padic_val_rat.mul, norm_cast, exact cast_ne_zero.mpr hq, exact cast_ne_zero.mpr hr, end /-- Dividing out by a prime factor reduces the padic_val_nat by 1. -/ protected lemma div {p : ℕ} [p_prime : fact p.prime] {b : ℕ} (dvd : p ∣ b) : (padic_val_nat p (b / p)) = (padic_val_nat p b) - 1 := begin by_cases b_split : (b = 0), { simp [b_split], }, { have split_frac : padic_val_rat p (b / p) = padic_val_rat p b - padic_val_rat p p := padic_val_rat.div p (nat.cast_ne_zero.mpr b_split) (nat.cast_ne_zero.mpr (nat.prime.ne_zero p_prime)), rw padic_val_rat.padic_val_rat_self (nat.prime.one_lt p_prime) at split_frac, have r : 1 ≤ padic_val_nat p b := one_le_padic_val_nat_of_dvd b_split dvd, exact_mod_cast split_frac, } end end padic_val_nat section padic_val_nat /-- If a prime doesn't appear in `n`, `padic_val_nat p n` is `0`. -/ lemma padic_val_nat_of_not_dvd {p : ℕ} [fact p.prime] {n : ℕ} (not_dvd : ¬(p ∣ n)) : padic_val_nat p n = 0 := begin by_cases hn : n = 0, { subst hn, simp at not_dvd, trivial, }, { rw padic_val_nat_def hn, exact (@multiplicity.unique' _ _ _ p n 0 (by simp) (by simpa using not_dvd)).symm, assumption, }, end lemma dvd_of_one_le_padic_val_nat {n p : nat} [prime : fact p.prime] (hp : 1 ≤ padic_val_nat p n) : p ∣ n := begin by_contra h, rw padic_val_nat_of_not_dvd h at hp, exact lt_irrefl 0 (lt_of_lt_of_le zero_lt_one hp), end lemma padic_val_nat_primes {p q : ℕ} [p_prime : fact p.prime] [q_prime : fact q.prime] (neq : p ≠ q) : padic_val_nat p q = 0 := @padic_val_nat_of_not_dvd p p_prime q $ (not_congr (iff.symm (prime_dvd_prime_iff_eq p_prime q_prime))).mp neq protected lemma padic_val_nat.div' {p : ℕ} [p_prime : fact p.prime] : ∀ {m : ℕ} (cpm : coprime p m) {b : ℕ} (dvd : m ∣ b), padic_val_nat p (b / m) = padic_val_nat p b | 0 := λ cpm b dvd, by { rw zero_dvd_iff at dvd, rw [dvd, nat.zero_div], } | (n + 1) := λ cpm b dvd, begin rcases dvd with ⟨c, rfl⟩, rw [mul_div_right c (nat.succ_pos _)],by_cases hc : c = 0, { rw [hc, mul_zero] }, { rw padic_val_nat.mul, { suffices : ¬ p ∣ (n+1), { rw [padic_val_nat_of_not_dvd this, zero_add] }, contrapose! cpm, exact p_prime.dvd_iff_not_coprime.mp cpm }, { exact nat.succ_ne_zero _ }, { exact hc } }, end lemma padic_val_nat_eq_factors_count (p : ℕ) [hp : fact p.prime] : ∀ (n : ℕ), padic_val_nat p n = (factors n).count p | 0 := rfl | 1 := by { rw padic_val_nat_one, refl } | (m + 2) := let n := m + 2 in let q := min_fac n in have hq : fact q.prime := min_fac_prime (show m + 2 ≠ 1, by linarith), have wf : n / q < n := nat.div_lt_self (nat.succ_pos _) hq.one_lt, begin rw factors_add_two, show padic_val_nat p n = list.count p (q :: (factors (n / q))), rw [list.count_cons', ← padic_val_nat_eq_factors_count], split_ifs with h, have p_dvd_n : p ∣ n, { have: q ∣ n := nat.min_fac_dvd n, cc }, { rw [←h, padic_val_nat.div], { have: 1 ≤ padic_val_nat p n := one_le_padic_val_nat_of_dvd (by linarith) p_dvd_n, exact (nat.sub_eq_iff_eq_add this).mp rfl, }, { exact p_dvd_n, }, }, { suffices : p.coprime q, { rw [padic_val_nat.div' this (min_fac_dvd n), add_zero], }, rwa nat.coprime_primes hp hq, }, end open_locale big_operators lemma prod_pow_prime_padic_val_nat (n : nat) (hn : n ≠ 0) (m : nat) (pr : n < m) : ∏ p in finset.filter nat.prime (finset.range m), p ^ (padic_val_nat p n) = n := begin rw ← pos_iff_ne_zero at hn, have H : (factors n : multiset ℕ).prod = n, { rw [multiset.coe_prod, prod_factors hn], }, rw finset.prod_multiset_count at H, conv_rhs { rw ← H, }, refine finset.prod_bij_ne_one (λ p hp hp', p) _ _ _ _, { rintro p hp hpn, rw [finset.mem_filter, finset.mem_range] at hp, haveI Hp : fact p.prime := hp.2, rw [multiset.mem_to_finset, multiset.mem_coe, mem_factors_iff_dvd hn Hp], contrapose! hpn, rw [padic_val_nat_of_not_dvd hpn, pow_zero], }, { intros, assumption }, { intros p hp hpn, rw [multiset.mem_to_finset, multiset.mem_coe] at hp, haveI Hp : fact p.prime := mem_factors hp, simp only [exists_prop, ne.def, finset.mem_filter, finset.mem_range], refine ⟨p, ⟨_, Hp⟩, ⟨_, rfl⟩⟩, { rw mem_factors_iff_dvd hn Hp at hp, exact lt_of_le_of_lt (le_of_dvd hn hp) pr }, { rw padic_val_nat_eq_factors_count, simpa [ne.def, multiset.coe_count] using hpn } }, { intros p hp hpn, rw [finset.mem_filter, finset.mem_range] at hp, haveI Hp : fact p.prime := hp.2, rw [padic_val_nat_eq_factors_count, multiset.coe_count] } end end padic_val_nat /-- If `q ≠ 0`, the p-adic norm of a rational `q` is `p ^ (-(padic_val_rat p q))`. If `q = 0`, the p-adic norm of `q` is 0. -/ def padic_norm (p : ℕ) (q : ℚ) : ℚ := if q = 0 then 0 else (↑p : ℚ) ^ (-(padic_val_rat p q)) namespace padic_norm section padic_norm open padic_val_rat variables (p : ℕ) /-- Unfolds the definition of the p-adic norm of `q` when `q ≠ 0`. -/ @[simp] protected lemma eq_fpow_of_nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q = p ^ (-(padic_val_rat p q)) := by simp [hq, padic_norm] /-- The p-adic norm is nonnegative. -/ protected lemma nonneg (q : ℚ) : 0 ≤ padic_norm p q := if hq : q = 0 then by simp [hq, padic_norm] else begin unfold padic_norm; split_ifs, apply fpow_nonneg_of_nonneg, exact_mod_cast nat.zero_le _ end /-- The p-adic norm of 0 is 0. -/ @[simp] protected lemma zero : padic_norm p 0 = 0 := by simp [padic_norm] /-- The p-adic norm of 1 is 1. -/ @[simp] protected lemma one : padic_norm p 1 = 1 := by simp [padic_norm] /-- The p-adic norm of `p` is `1/p` if `p > 1`. See also `padic_norm.padic_norm_p_of_prime` for a version that assumes `p` is prime. -/ lemma padic_norm_p {p : ℕ} (hp : 1 < p) : padic_norm p p = 1 / p := by simp [padic_norm, (show p ≠ 0, by linarith), padic_val_rat.padic_val_rat_self hp] /-- The p-adic norm of `p` is `1/p` if `p` is prime. See also `padic_norm.padic_norm_p` for a version that assumes `1 < p`. -/ @[simp] lemma padic_norm_p_of_prime (p : ℕ) [fact p.prime] : padic_norm p p = 1 / p := padic_norm_p $ nat.prime.one_lt ‹_› /-- The p-adic norm of `p` is less than 1 if `1 < p`. See also `padic_norm.padic_norm_p_lt_one_of_prime` for a version assuming `prime p`. -/ lemma padic_norm_p_lt_one {p : ℕ} (hp : 1 < p) : padic_norm p p < 1 := begin rw [padic_norm_p hp, div_lt_iff, one_mul], { exact_mod_cast hp }, { exact_mod_cast zero_lt_one.trans hp }, end /-- The p-adic norm of `p` is less than 1 if `p` is prime. See also `padic_norm.padic_norm_p_lt_one` for a version assuming `1 < p`. -/ lemma padic_norm_p_lt_one_of_prime (p : ℕ) [fact p.prime] : padic_norm p p < 1 := padic_norm_p_lt_one $ nat.prime.one_lt ‹_› /-- `padic_norm p q` takes discrete values `p ^ -z` for `z : ℤ`. -/ protected theorem values_discrete {q : ℚ} (hq : q ≠ 0) : ∃ z : ℤ, padic_norm p q = p ^ (-z) := ⟨ (padic_val_rat p q), by simp [padic_norm, hq] ⟩ /-- `padic_norm p` is symmetric. -/ @[simp] protected lemma neg (q : ℚ) : padic_norm p (-q) = padic_norm p q := if hq : q = 0 then by simp [hq] else by simp [padic_norm, hq] variable [hp : fact p.prime] include hp /-- If `q ≠ 0`, then `padic_norm p q ≠ 0`. -/ protected lemma nonzero {q : ℚ} (hq : q ≠ 0) : padic_norm p q ≠ 0 := begin rw padic_norm.eq_fpow_of_nonzero p hq, apply fpow_ne_zero_of_ne_zero, exact_mod_cast ne_of_gt hp.pos end /-- If the p-adic norm of `q` is 0, then `q` is 0. -/ lemma zero_of_padic_norm_eq_zero {q : ℚ} (h : padic_norm p q = 0) : q = 0 := begin apply by_contradiction, intro hq, unfold padic_norm at h, rw if_neg hq at h, apply absurd h, apply fpow_ne_zero_of_ne_zero, exact_mod_cast hp.ne_zero end /-- The p-adic norm is multiplicative. -/ @[simp] protected theorem mul (q r : ℚ) : padic_norm p (q*r) = padic_norm p q * padic_norm p r := if hq : q = 0 then by simp [hq] else if hr : r = 0 then by simp [hr] else have q*r ≠ 0, from mul_ne_zero hq hr, have (↑p : ℚ) ≠ 0, by simp [hp.ne_zero], by simp [padic_norm, *, padic_val_rat.mul, fpow_add this, mul_comm] /-- The p-adic norm respects division. -/ @[simp] protected theorem div (q r : ℚ) : padic_norm p (q / r) = padic_norm p q / padic_norm p r := if hr : r = 0 then by simp [hr] else eq_div_of_mul_eq (padic_norm.nonzero _ hr) (by rw [←padic_norm.mul, div_mul_cancel _ hr]) /-- The p-adic norm of an integer is at most 1. -/ protected theorem of_int (z : ℤ) : padic_norm p ↑z ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else begin unfold padic_norm, rw [if_neg _], { refine fpow_le_one_of_nonpos _ _, { exact_mod_cast le_of_lt hp.one_lt, }, { rw [padic_val_rat_of_int _ hp.ne_one hz, neg_nonpos], norm_cast, simp }}, exact_mod_cast hz end private lemma nonarchimedean_aux {q r : ℚ} (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) := have hnqp : padic_norm p q ≥ 0, from padic_norm.nonneg _ _, have hnrp : padic_norm p r ≥ 0, from padic_norm.nonneg _ _, if hq : q = 0 then by simp [hq, max_eq_right hnrp, le_max_right] else if hr : r = 0 then by simp [hr, max_eq_left hnqp, le_max_left] else if hqr : q + r = 0 then le_trans (by simpa [hqr] using hnqp) (le_max_left _ _) else begin unfold padic_norm, split_ifs, apply le_max_iff.2, left, apply fpow_le_of_le, { exact_mod_cast le_of_lt hp.one_lt }, { apply neg_le_neg, have : padic_val_rat p q = min (padic_val_rat p q) (padic_val_rat p r), from (min_eq_left h).symm, rw this, apply min_le_padic_val_rat_add; assumption } end /-- The p-adic norm is nonarchimedean: the norm of `p + q` is at most the max of the norm of `p` and the norm of `q`. -/ protected theorem nonarchimedean {q r : ℚ} : padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) := begin wlog hle := le_total (padic_val_rat p q) (padic_val_rat p r) using [q r], exact nonarchimedean_aux p hle end /-- The p-adic norm respects the triangle inequality: the norm of `p + q` is at most the norm of `p` plus the norm of `q`. -/ theorem triangle_ineq (q r : ℚ) : padic_norm p (q + r) ≤ padic_norm p q + padic_norm p r := calc padic_norm p (q + r) ≤ max (padic_norm p q) (padic_norm p r) : padic_norm.nonarchimedean p ... ≤ padic_norm p q + padic_norm p r : max_le_add_of_nonneg (padic_norm.nonneg p _) (padic_norm.nonneg p _) /-- The p-adic norm of a difference is at most the max of each component. Restates the archimedean property of the p-adic norm. -/ protected theorem sub {q r : ℚ} : padic_norm p (q - r) ≤ max (padic_norm p q) (padic_norm p r) := by rw [sub_eq_add_neg, ←padic_norm.neg p r]; apply padic_norm.nonarchimedean /-- If the p-adic norms of `q` and `r` are different, then the norm of `q + r` is equal to the max of the norms of `q` and `r`. -/ lemma add_eq_max_of_ne {q r : ℚ} (hne : padic_norm p q ≠ padic_norm p r) : padic_norm p (q + r) = max (padic_norm p q) (padic_norm p r) := begin wlog hle := le_total (padic_norm p r) (padic_norm p q) using [q r], have hlt : padic_norm p r < padic_norm p q, from lt_of_le_of_ne hle hne.symm, have : padic_norm p q ≤ max (padic_norm p (q + r)) (padic_norm p r), from calc padic_norm p q = padic_norm p (q + r - r) : by congr; ring ... ≤ max (padic_norm p (q + r)) (padic_norm p (-r)) : padic_norm.nonarchimedean p ... = max (padic_norm p (q + r)) (padic_norm p r) : by simp, have hnge : padic_norm p r ≤ padic_norm p (q + r), { apply le_of_not_gt, intro hgt, rw max_eq_right_of_lt hgt at this, apply not_lt_of_ge this, assumption }, have : padic_norm p q ≤ padic_norm p (q + r), by rwa [max_eq_left hnge] at this, apply _root_.le_antisymm, { apply padic_norm.nonarchimedean p }, { rw max_eq_left_of_lt hlt, assumption } end /-- The p-adic norm is an absolute value: positive-definite and multiplicative, satisfying the triangle inequality. -/ instance : is_absolute_value (padic_norm p) := { abv_nonneg := padic_norm.nonneg p, abv_eq_zero := begin intros, constructor; intro, { apply zero_of_padic_norm_eq_zero p, assumption }, { simp [*] } end, abv_add := padic_norm.triangle_ineq p, abv_mul := padic_norm.mul p } variable {p} lemma dvd_iff_norm_le {n : ℕ} {z : ℤ} : ↑(p^n) ∣ z ↔ padic_norm p z ≤ ↑p ^ (-n : ℤ) := begin unfold padic_norm, split_ifs with hz, { norm_cast at hz, have : 0 ≤ (p^n : ℚ), {apply pow_nonneg, exact_mod_cast le_of_lt hp.pos }, simp [hz, this] }, { rw [fpow_le_iff_le, neg_le_neg_iff, padic_val_rat_of_int _ hp.ne_one _], { norm_cast, rw [← enat.coe_le_coe, enat.coe_get, ← multiplicity.pow_dvd_iff_le_multiplicity], simp }, { exact_mod_cast hz }, { exact_mod_cast hp.one_lt } } end end padic_norm end padic_norm
716f21a12745609d2fabcaa4bb57f90ff6bef7ed
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/analysis/special_functions/pow.lean
11c1967daf2281053f5b822f49e09d338ee33435
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
64,858
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.trigonometric import analysis.calculus.extend_deriv /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ennreal` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ennreal`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [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] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[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_add, hx, pow_add, cpow_nat_cast n] @[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_iff (nat.cast_pos.2 hn : (0 : ℝ) < _)).mpr (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_nonneg h n.cast_nonneg) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h n.cast_nonneg), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_iff' (nat.cast_pos.2 hn : (0 : ℝ) < _)).mpr (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 (pos_iff_ne_zero.1 hn)), cpow_one] end complex namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl 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 * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos @[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 zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } 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 abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end 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 variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { simp only [← H, h, rpow_eq_zero_iff_of_nonneg, true_and, zero_rpow, eq_self_iff_true, ne.def, not_false_iff, zero_eq_mul], by_contradiction F, push_neg at F, apply h, simp [F] }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end 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 * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } @[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 rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, fpow_one, fpow_neg], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := begin by_cases hy0 : y = 0, { simp [*] }, by_cases hx0 : x = 0, { simp [*] }, simp only [real.rpow_def_of_nonneg hx, real.rpow_def_of_nonneg (inv_nonneg.2 hx), if_false, hx0, mt inv_eq_zero.1 hx0, log_inv, ← neg_mul_eq_neg_mul, exp_neg] end lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2, log_neg_eq_log] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert (is_open_lt' (0:ℝ)).prod is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert (is_open_gt' (0:ℝ)).prod is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), metric.tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero, subtype.coe_mk], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_univ.prod (is_open_lt' (0:ℝ)), ext, finish }) hy) lemma continuous_at_rpow {x y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := by { cases h, exact continuous_at_rpow_of_ne_zero h _, exact continuous_at_rpow_of_pos h x } variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section prove_rpow_is_differentiable lemma has_deriv_at_rpow_of_pos {x : ℝ} (h : 0 < x) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p)) (p * x^(p-1)) x, { convert (has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_gt h)).mul_const p) using 1, field_simp [rpow_def_of_pos h, mul_sub, exp_sub, exp_log h, ne_of_gt h], ring }, apply this.congr_of_eventually_eq, have : set.Ioi (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Ioi h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_pos hy _) end lemma has_deriv_at_rpow_of_neg {x : ℝ} (h : x < 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin have : has_deriv_at (λ x, exp (log x * p) * cos (p * π)) (p * x^(p-1)) x, { convert ((has_deriv_at_exp _).comp x ((has_deriv_at_log (ne_of_lt h)).mul_const p)).mul_const _ using 1, field_simp [rpow_def_of_neg h, mul_sub, exp_sub, sub_mul, cos_sub, exp_log_of_neg h, ne_of_lt h], ring }, apply this.congr_of_eventually_eq, have : set.Iio (0 : ℝ) ∈ 𝓝 x := mem_nhds_sets is_open_Iio h, exact filter.eventually_of_mem this (λ y hy, rpow_def_of_neg hy _) end lemma has_deriv_at_rpow {x : ℝ} (h : x ≠ 0) (p : ℝ) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin rcases lt_trichotomy x 0 with H|H|H, { exact has_deriv_at_rpow_of_neg H p }, { exact (h H).elim }, { exact has_deriv_at_rpow_of_pos H p }, end lemma has_deriv_at_rpow_zero_of_one_le {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * (0 : ℝ)^(p-1)) 0 := begin apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, has_deriv_at_rpow hx p), { exact (continuous_rpow_of_pos (λ _, (lt_of_lt_of_le zero_lt_one h)) continuous_id continuous_const).continuous_at }, { rcases le_iff_eq_or_lt.1 h with rfl|h, { simp [continuous_const.continuous_at] }, { exact (continuous_const.mul (continuous_rpow_of_pos (λ _, sub_pos_of_lt h) continuous_id continuous_const)).continuous_at } } end lemma has_deriv_at_rpow_of_one_le (x : ℝ) {p : ℝ} (h : 1 ≤ p) : has_deriv_at (λ x, x^p) (p * x^(p-1)) x := begin by_cases hx : x = 0, { rw hx, exact has_deriv_at_rpow_zero_of_one_le h }, { exact has_deriv_at_rpow hx p } end end prove_rpow_is_differentiable section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt end real section measurability_real lemma real.measurable_rpow : measurable (λ p : ℝ × ℝ, p.1 ^ p.2) := begin have h_meas : is_measurable {p : ℝ × ℝ | p.1 = 0} := (is_closed_singleton.preimage continuous_fst).is_measurable, refine measurable_of_measurable_union_cover {p : ℝ × ℝ | p.1 = 0} {p : ℝ × ℝ | p.1 ≠ 0} h_meas h_meas.compl _ _ _, { intro x, simp [em (x.fst = 0)], }, { have h_eq_ite : (λ a : {p : ℝ × ℝ | p.fst = 0}, (a:ℝ×ℝ).fst ^ (a:ℝ×ℝ).snd) = λ a : {p : ℝ × ℝ | p.fst = 0}, ite ((a:ℝ×ℝ).snd = 0) 1 0, { ext1 a, have h_fst_zero : (a:ℝ×ℝ).fst = 0, from a.prop, rw h_fst_zero, split_ifs with h_snd, { rw h_snd, exact real.rpow_zero _, }, exact real.zero_rpow h_snd, }, rw h_eq_ite, change measurable ((λ x : ℝ, ite (x = 0) (1:ℝ) (0:ℝ)) ∘ (λ a : {p : ℝ × ℝ | p.fst = 0}, (a:ℝ×ℝ).snd)), refine measurable.comp _ (measurable_snd.comp measurable_subtype_coe), exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const, }, { refine continuous.measurable _, rw continuous_iff_continuous_at, intro x, change continuous_at ((λ a : ℝ × ℝ, a.fst ^ a.snd) ∘ (λ a : {p : ℝ × ℝ | p.fst ≠ 0}, (a:ℝ×ℝ))) x, refine continuous_at.comp _ continuous_at_subtype_coe, change continuous_at (λ (p : ℝ × ℝ), p.fst ^ p.snd) x.val, have h_x : x.val = (x.val.fst, x.val.snd), by simp, rw h_x, exact real.continuous_at_rpow_of_ne_zero x.prop _, }, end lemma measurable.rpow {α} [measurable_space α] {f g : α → ℝ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := begin change measurable ((λ p : ℝ × ℝ, p.1 ^ p.2) ∘ (λ a : α, (f a, g a))), exact real.measurable_rpow.comp (measurable.prod hf hg), end lemma real.measurable_rpow_const {y : ℝ} : measurable (λ x : ℝ, x ^ y) := begin change measurable ((λ p : ℝ × ℝ, p.1 ^ p.2) ∘ (λ x : ℝ, (id x, (λ x, y) x))), refine real.measurable_rpow.comp (measurable.prod measurable_id _), change measurable (λ (a : ℝ), y), exact measurable_const, end lemma measurable.rpow_const {α} [measurable_space α] {f : α → ℝ} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.rpow measurable_const end measurability_real section differentiability open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} (p : ℝ) /- Differentiability statements for the power of a function, when the function does not vanish and the exponent is arbitrary-/ lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow hx p).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow p hx end lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow p hx).differentiable_within_at @[simp] lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow p hx).differentiable_at lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow p (hx x h) @[simp] lemma differentiable.rpow (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow p (hx x) lemma deriv_within_rpow (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow p hx).deriv_within hxs @[simp] lemma deriv_rpow (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow p hx).deriv /- Differentiability statements for the power of a function, when the function may vanish but the exponent is at least one. -/ variable {p} lemma has_deriv_within_at.rpow_of_one_le (hf : has_deriv_within_at f f' s x) (hp : 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) s x := begin convert (has_deriv_at_rpow_of_one_le (f x) hp).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_of_one_le (hf : has_deriv_at f f' x) (hp : 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_of_one_le hp end lemma differentiable_within_at.rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) : differentiable_within_at ℝ (λx, (f x)^p) s x := (hf.has_deriv_within_at.rpow_of_one_le hp).differentiable_within_at @[simp] lemma differentiable_at.rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : differentiable_at ℝ (λx, (f x)^p) x := (hf.has_deriv_at.rpow_of_one_le hp).differentiable_at lemma differentiable_on.rpow_of_one_le (hf : differentiable_on ℝ f s) (hp : 1 ≤ p) : differentiable_on ℝ (λx, (f x)^p) s := λx h, (hf x h).rpow_of_one_le hp @[simp] lemma differentiable.rpow_of_one_le (hf : differentiable ℝ f) (hp : 1 ≤ p) : differentiable ℝ (λx, (f x)^p) := λx, (hf x).rpow_of_one_le hp lemma deriv_within_rpow_of_one_le (hf : differentiable_within_at ℝ f s x) (hp : 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x)^p) s x = (deriv_within f s x) * p * (f x)^(p-1) := (hf.has_deriv_within_at.rpow_of_one_le hp).deriv_within hxs @[simp] lemma deriv_rpow_of_one_le (hf : differentiable_at ℝ f x) (hp : 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_of_one_le hp).deriv /- Differentiability statements for the square root of a function, when the function does not vanish -/ lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x := begin simp only [sqrt_eq_rpow], convert hf.rpow (1/2) hx, rcases lt_trichotomy (f x) 0 with H|H|H, { have A : (f x)^((1:ℝ)/2) = 0, { rw rpow_def_of_neg H, have : cos (1/2 * π) = 0, by { convert cos_pi_div_two using 2, ring }, rw [this], simp }, have B : f x ^ ((1:ℝ) / 2 - 1) = 0, { rw rpow_def_of_neg H, have : cos (π/2 - π) = 0, by simp [cos_sub], have : cos (((1:ℝ)/2 - 1) * π) = 0, by { convert this using 2, ring }, rw this, simp }, rw [A, B], simp }, { exact (hx H).elim }, { have A : 0 < (f x)^((1:ℝ)/2) := rpow_pos_of_pos H _, have B : (f x) ^ (-(1:ℝ)) = (f x)^(-((1:ℝ)/2)) * (f x)^(-((1:ℝ)/2)), { rw [← rpow_add H], congr, norm_num }, rw [sub_eq_add_neg, rpow_add H, B, rpow_neg (le_of_lt H)], field_simp } end lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x := begin rw ← has_deriv_within_at_univ at *, exact hf.sqrt hx end lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, sqrt (f x)) s x := (hf.has_deriv_within_at.sqrt hx).differentiable_within_at @[simp] lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, sqrt (f x)) x := (hf.has_deriv_at.sqrt hx).differentiable_at lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, sqrt (f x)) s := λx h, (hf x h).sqrt (hx x h) @[simp] lemma differentiable.sqrt (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, sqrt (f x)) := λx, (hf x).sqrt (hx x) lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) := (hf.has_deriv_within_at.sqrt hx).deriv_within hxs @[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) := (hf.has_deriv_at.sqrt hx).deriv end differentiability section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto.inv_tendsto_at_top (tendsto_rpow_at_top hy)) /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring } end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = nnreal.of_real ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, nnreal.coe_of_real _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end lemma of_real_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : nnreal.of_real (x ^ y) = (nnreal.of_real x) ^ y := begin nth_rewrite 0 ← nnreal.coe_of_real x hx, rw [←nnreal.coe_rpow, nnreal.of_real_coe], end end nnreal section measurability_nnreal lemma nnreal.measurable_rpow : measurable (λ p : ℝ≥0 × ℝ, p.1 ^ p.2) := begin have h_rw : (λ p : ℝ≥0 × ℝ, p.1 ^ p.2) = (λ p : ℝ≥0 × ℝ, nnreal.of_real(↑(p.1) ^ p.2)), { ext1 a, rw [←nnreal.coe_rpow, nnreal.of_real_coe], }, rw h_rw, exact (measurable_fst.nnreal_coe.rpow measurable_snd).nnreal_of_real, end lemma measurable.nnreal_rpow {α} [measurable_space α] {f : α → ℝ≥0} (hf : measurable f) {g : α → ℝ} (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := begin change measurable ((λ p : ℝ≥0 × ℝ, p.1 ^ p.2) ∘ (λ a : α, (f a, g a))), exact nnreal.measurable_rpow.comp (measurable.prod hf hg), end lemma nnreal.measurable_rpow_const {y : ℝ} : measurable (λ a : ℝ≥0, a ^ y) := begin have h_rw : (λ a : ℝ≥0, a ^ y) = (λ a : ℝ≥0, nnreal.of_real(↑a ^ y)), { ext1 a, rw [←nnreal.coe_rpow, nnreal.of_real_coe], }, rw h_rw, exact nnreal.measurable_coe.rpow_const.nnreal_of_real, end lemma measurable.nnreal_rpow_const {α} [measurable_space α] {f : α → ℝ≥0} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.nnreal_rpow measurable_const end measurability_nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ennreal` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ennreal → ℝ → ennreal | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ennreal ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ennreal) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ennreal} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ennreal) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ennreal) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ennreal) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ennreal) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ennreal) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ennreal) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ennreal) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ennreal) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ennreal) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ennreal) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ennreal) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ennreal} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ennreal} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ennreal} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ennreal) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ennreal} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ennreal} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := ennreal.lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ennreal} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ennreal) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_neg_one (x : ennreal) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ennreal) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ennreal) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ennreal) * y) ^ z = x^z * y^z := begin rcases lt_trichotomy z 0 with H|H|H, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_neg, H] }, { have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_neg, H, with_top.top_mul this] }, { have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_neg H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, { simp [H] }, { by_cases hx : x = 0; by_cases hy : y = 0, { simp [hx, hy, zero_rpow_of_pos, H] }, { have : (y : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hy], simp [hx, hy, zero_rpow_of_pos H, with_top.top_mul this] }, { have : (x : ennreal) ^ z ≠ 0, by simp [rpow_eq_zero_iff, hx], simp [hx, hy, zero_rpow_of_pos H, with_top.mul_top this] }, { rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx, coe_rpow_of_ne_zero hy], simp [hx, hy] } }, end lemma mul_rpow_of_ne_top {x y : ennreal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := begin lift x to ℝ≥0 using hx, lift y to ℝ≥0 using hy, exact coe_mul_rpow x y z end lemma mul_rpow_of_ne_zero {x y : ennreal} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := begin rcases lt_trichotomy z 0 with H|H|H, { cases x; cases y, { simp [hx, hy, top_rpow_of_neg, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_neg, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } }, { simp [H] }, { cases x; cases y, { simp [hx, hy, top_rpow_of_pos, H] }, { have : y ≠ 0, by simpa using hy, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have : x ≠ 0, by simpa using hx, simp [hx, hy, top_rpow_of_pos, H, rpow_eq_zero_iff, this] }, { have hx' : x ≠ 0, by simpa using hx, have hy' : y ≠ 0, by simpa using hy, simp only [some_eq_coe], rw [← coe_mul, coe_rpow_of_ne_zero, nnreal.mul_rpow, coe_mul, coe_rpow_of_ne_zero hx', coe_rpow_of_ne_zero hy'], simp [hx', hy'] } } end lemma mul_rpow_of_nonneg (x y : ennreal) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := begin rcases le_iff_eq_or_lt.1 hz with H|H, { simp [← H] }, by_cases h : x = 0 ∨ y = 0, { cases h; simp [h, zero_rpow_of_pos H] }, push_neg at h, exact mul_rpow_of_ne_zero h.1 h.2 z end lemma inv_rpow_of_pos {x : ennreal} {y : ℝ} (hy : 0 < y) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin by_cases h0 : x = 0, { rw [h0, zero_rpow_of_pos hy, inv_zero, top_rpow_of_pos hy], }, by_cases h_top : x = ⊤, { rw [h_top, top_rpow_of_pos hy, inv_top, zero_rpow_of_pos hy], }, rw ←coe_to_nnreal h_top, have h : x.to_nnreal ≠ 0, { rw [ne.def, to_nnreal_eq_zero_iff], simp [h0, h_top], }, rw [←coe_inv h, coe_rpow_of_nonneg _ (le_of_lt hy), coe_rpow_of_nonneg _ (le_of_lt hy), ←coe_inv], { rw coe_eq_coe, exact nnreal.inv_rpow x.to_nnreal y, }, { simp [h], }, end lemma div_rpow_of_nonneg (x y : ennreal) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := begin by_cases h0 : z = 0, { simp [h0], }, rw ←ne.def at h0, have hz_pos : 0 < z, from lt_of_le_of_ne hz h0.symm, rw [div_eq_mul_inv, mul_rpow_of_nonneg x y⁻¹ hz, inv_rpow_of_pos hz_pos, ←div_eq_mul_inv], end lemma rpow_le_rpow {x y : ennreal} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases le_iff_eq_or_lt.1 h₂ with H|H, { simp [← H, le_refl] }, cases y, { simp [top_rpow_of_pos H] }, cases x, { exact (not_top_le_coe h₁).elim }, simp at h₁, simp [coe_rpow_of_nonneg _ h₂, nnreal.rpow_le_rpow h₁ h₂] end lemma rpow_lt_rpow {x y : ennreal} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := begin cases x, { exact (not_top_lt h₁).elim }, cases y, { simp [top_rpow_of_pos h₂, coe_rpow_of_nonneg _ (le_of_lt h₂)] }, simp at h₁, simp [coe_rpow_of_nonneg _ (le_of_lt h₂), nnreal.rpow_lt_rpow h₁ h₂] end lemma rpow_le_rpow_iff {x y : ennreal} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := begin refine ⟨λ h, _, λ h, rpow_le_rpow h (le_of_lt hz)⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul, ←one_div], exact rpow_le_rpow h (by simp [le_of_lt hz]), end lemma rpow_lt_rpow_iff {x y : ennreal} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := begin refine ⟨λ h_lt, _, λ h, rpow_lt_rpow h hz⟩, rw [←rpow_one x, ←rpow_one y, ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rpow_mul, rpow_mul], exact rpow_lt_rpow h_lt (by simp [hz]), end lemma le_rpow_one_div_iff {x y : ennreal} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ennreal} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ennreal} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ennreal} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ennreal} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ennreal} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ennreal} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ennreal} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ennreal} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ennreal} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ennreal} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ennreal} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ennreal} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ennreal} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ennreal} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ennreal) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ennreal) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ennreal, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ennreal, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ennreal, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma rpow_left_monotone_of_nonneg {x : ℝ} (hx : 0 ≤ x) : monotone (λ y : ennreal, y^x) := λ y z hyz, rpow_le_rpow hyz hx lemma rpow_left_strict_mono_of_pos {x : ℝ} (hx : 0 < x) : strict_mono (λ y : ennreal, y^x) := λ y z hyz, rpow_lt_rpow hyz hx end ennreal section measurability_ennreal lemma ennreal.measurable_rpow : measurable (λ p : ennreal × ℝ, p.1 ^ p.2) := begin refine ennreal.measurable_of_measurable_nnreal_prod _ _, { simp_rw ennreal.coe_rpow_def, refine measurable.ite _ measurable_const nnreal.measurable_rpow.ennreal_coe, exact is_measurable.inter (measurable_fst (is_measurable_singleton 0)) (measurable_snd is_measurable_Iio), }, { simp_rw ennreal.top_rpow_def, refine measurable.ite is_measurable_Ioi measurable_const _, exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const, }, end lemma measurable.ennreal_rpow {α} [measurable_space α] {f : α → ennreal} (hf : measurable f) {g : α → ℝ} (hg : measurable g) : measurable (λ a : α, (f a) ^ (g a)) := begin change measurable ((λ p : ennreal × ℝ, p.1 ^ p.2) ∘ (λ a, (f a, g a))), exact ennreal.measurable_rpow.comp (measurable.prod hf hg), end lemma ennreal.measurable_rpow_const {y : ℝ} : measurable (λ a : ennreal, a ^ y) := begin change measurable ((λ p : ennreal × ℝ, p.1 ^ p.2) ∘ (λ a, (a, y))), refine ennreal.measurable_rpow.comp (measurable.prod measurable_id _), dsimp only, exact measurable_const, end lemma measurable.ennreal_rpow_const {α} [measurable_space α] {f : α → ennreal} (hf : measurable f) {y : ℝ} : measurable (λ a : α, (f a) ^ y) := hf.ennreal_rpow measurable_const lemma ae_measurable.ennreal_rpow_const {α} [measurable_space α] {f : α → ennreal} {μ : measure_theory.measure α} (hf : ae_measurable f μ) {y : ℝ} : ae_measurable (λ a : α, (f a) ^ y) μ := ennreal.measurable_rpow_const.comp_ae_measurable hf end measurability_ennreal
a4a5aa3373619543a85c724abd91aad58cdccb50
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/category.lean
df14d9953cbc34f2277e6441b06597744bd1e50f
[ "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
5,258
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton Defines a category, as a typeclass parametrised by the type of objects. Introduces notations `X ⟶ Y` for the morphism spaces, `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ``` local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ import tactic.restate_axiom import tactic.replacer import tactic.interactive import tactic.tidy namespace category_theory universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted /- The propositional fields of `category` are annotated with the auto_param `obviously`, which is defined here as a [`replacer` tactic](https://github.com/leanprover/mathlib/blob/master/docs/tactics.md#def_replacer). We then immediately set up `obviously` to call `tidy`. Later, this can be replaced with more powerful tactics. -/ def_replacer obviously @[obviously] meta def obviously' := tactic.tidy class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h class category_struct (obj : Type u) extends has_hom.{v} obj := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) -/ class category (obj : Type u) extends category_struct.{v} obj := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp lemma category.assoc_symm {C : Type u} [category.{v} C] {W X Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) : f ≫ (g ≫ h) = (f ≫ g) ≫ h := by rw ←category.assoc /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [𝒞 : category.{v} C] {X Y Z : C} include 𝒞 class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) @[simp] lemma cancel_epi (f : X ⟶ Y) [epi f] (g h : Y ⟶ Z) : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ @[simp] lemma cancel_mono (f : X ⟶ Y) [mono f] (g h : Z ⟶ X) : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end variables (α : Type u) instance [preorder α] : small_category α := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans f.down.down g.down.down ⟩ ⟩ } section variables {C : Type u} def End [has_hom.{v} C] (X : C) := X ⟶ X instance End.has_one [category_struct.{v} C] {X : C} : has_one (End X) := by refine { one := 𝟙 X } instance End.has_mul [category_struct.{v} C] {X : C} : has_mul (End X) := by refine { mul := λ x y, x ≫ y } instance End.monoid [category.{v} C] {X : C} : monoid (End X) := by refine { .. End.has_one, .. End.has_mul, .. }; dsimp [has_mul.mul,has_one.one]; obviously @[simp] lemma End.one_def {C : Type u} [category_struct.{v} C] {X : C} : (1 : End X) = 𝟙 X := rfl @[simp] lemma End.mul_def {C : Type u} [category_struct.{v} C] {X : C} (xs ys : End X) : xs * ys = xs ≫ ys := rfl end end category_theory
01ff050a22a8d0dd1c293c04418aa3b6076c15bd
7565ffb53cc64430691ce89265da0f944ee43051
/hott/algebra/inf_group.hlean
5a8009b43721468d2f390da7785f8d96f520f248
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,768
hlean
/- 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 -/ import algebra.binary algebra.priority open eq eq.ops -- note: ⁻¹ will be overloaded open binary algebra is_trunc set_option class.force_new true variable {A : Type} /- inf_semigroup -/ namespace algebra structure inf_semigroup [class] (A : Type) extends has_mul A := (mul_assoc : Πa b c, mul (mul a b) c = mul a (mul b c)) definition mul.assoc [s : inf_semigroup A] (a b c : A) : a * b * c = a * (b * c) := !inf_semigroup.mul_assoc structure comm_inf_semigroup [class] (A : Type) extends inf_semigroup A := (mul_comm : Πa b, mul a b = mul b a) definition mul.comm [s : comm_inf_semigroup A] (a b : A) : a * b = b * a := !comm_inf_semigroup.mul_comm theorem mul.left_comm [s : comm_inf_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) := binary.left_comm (@mul.comm A _) (@mul.assoc A _) a b c theorem mul.right_comm [s : comm_inf_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b := binary.right_comm (@mul.comm A _) (@mul.assoc A _) a b c structure left_cancel_inf_semigroup [class] (A : Type) extends inf_semigroup A := (mul_left_cancel : Πa b c, mul a b = mul a c → b = c) theorem mul.left_cancel [s : left_cancel_inf_semigroup A] {a b c : A} : a * b = a * c → b = c := !left_cancel_inf_semigroup.mul_left_cancel abbreviation eq_of_mul_eq_mul_left' := @mul.left_cancel structure right_cancel_inf_semigroup [class] (A : Type) extends inf_semigroup A := (mul_right_cancel : Πa b c, mul a b = mul c b → a = c) definition mul.right_cancel [s : right_cancel_inf_semigroup A] {a b c : A} : a * b = c * b → a = c := !right_cancel_inf_semigroup.mul_right_cancel abbreviation eq_of_mul_eq_mul_right' := @mul.right_cancel /- additive inf_semigroup -/ definition add_inf_semigroup [class] : Type → Type := inf_semigroup definition has_add_of_add_inf_semigroup [reducible] [trans_instance] (A : Type) [H : add_inf_semigroup A] : has_add A := has_add.mk (@inf_semigroup.mul A H) definition add.assoc [s : add_inf_semigroup A] (a b c : A) : a + b + c = a + (b + c) := @mul.assoc A s a b c definition add_comm_inf_semigroup [class] : Type → Type := comm_inf_semigroup definition add_inf_semigroup_of_add_comm_inf_semigroup [reducible] [trans_instance] (A : Type) [H : add_comm_inf_semigroup A] : add_inf_semigroup A := @comm_inf_semigroup.to_inf_semigroup A H definition add.comm [s : add_comm_inf_semigroup A] (a b : A) : a + b = b + a := @mul.comm A s a b theorem add.left_comm [s : add_comm_inf_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) := binary.left_comm (@add.comm A _) (@add.assoc A _) a b c theorem add.right_comm [s : add_comm_inf_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b := binary.right_comm (@add.comm A _) (@add.assoc A _) a b c definition add_left_cancel_inf_semigroup [class] : Type → Type := left_cancel_inf_semigroup definition add_inf_semigroup_of_add_left_cancel_inf_semigroup [reducible] [trans_instance] (A : Type) [H : add_left_cancel_inf_semigroup A] : add_inf_semigroup A := @left_cancel_inf_semigroup.to_inf_semigroup A H definition add.left_cancel [s : add_left_cancel_inf_semigroup A] {a b c : A} : a + b = a + c → b = c := @mul.left_cancel A s a b c abbreviation eq_of_add_eq_add_left := @add.left_cancel definition add_right_cancel_inf_semigroup [class] : Type → Type := right_cancel_inf_semigroup definition add_inf_semigroup_of_add_right_cancel_inf_semigroup [reducible] [trans_instance] (A : Type) [H : add_right_cancel_inf_semigroup A] : add_inf_semigroup A := @right_cancel_inf_semigroup.to_inf_semigroup A H definition add.right_cancel [s : add_right_cancel_inf_semigroup A] {a b c : A} : a + b = c + b → a = c := @mul.right_cancel A s a b c abbreviation eq_of_add_eq_add_right := @add.right_cancel /- inf_monoid -/ structure inf_monoid [class] (A : Type) extends inf_semigroup A, has_one A := (one_mul : Πa, mul one a = a) (mul_one : Πa, mul a one = a) definition one_mul [s : inf_monoid A] (a : A) : 1 * a = a := !inf_monoid.one_mul definition mul_one [s : inf_monoid A] (a : A) : a * 1 = a := !inf_monoid.mul_one structure comm_inf_monoid [class] (A : Type) extends inf_monoid A, comm_inf_semigroup A /- additive inf_monoid -/ definition add_inf_monoid [class] : Type → Type := inf_monoid definition add_inf_semigroup_of_add_inf_monoid [reducible] [trans_instance] (A : Type) [H : add_inf_monoid A] : add_inf_semigroup A := @inf_monoid.to_inf_semigroup A H definition has_zero_of_add_inf_monoid [reducible] [trans_instance] (A : Type) [H : add_inf_monoid A] : has_zero A := has_zero.mk (@inf_monoid.one A H) definition zero_add [s : add_inf_monoid A] (a : A) : 0 + a = a := @inf_monoid.one_mul A s a definition add_zero [s : add_inf_monoid A] (a : A) : a + 0 = a := @inf_monoid.mul_one A s a definition add_comm_inf_monoid [class] : Type → Type := comm_inf_monoid definition add_inf_monoid_of_add_comm_inf_monoid [reducible] [trans_instance] (A : Type) [H : add_comm_inf_monoid A] : add_inf_monoid A := @comm_inf_monoid.to_inf_monoid A H definition add_comm_inf_semigroup_of_add_comm_inf_monoid [reducible] [trans_instance] (A : Type) [H : add_comm_inf_monoid A] : add_comm_inf_semigroup A := @comm_inf_monoid.to_comm_inf_semigroup A H section add_comm_inf_monoid variables [s : add_comm_inf_monoid A] include s theorem add_comm_three (a b c : A) : a + b + c = c + b + a := by rewrite [{a + _}add.comm, {_ + c}add.comm, -*add.assoc] theorem add.comm4 : Π (n m k l : A), n + m + (k + l) = n + k + (m + l) := comm4 add.comm add.assoc end add_comm_inf_monoid /- group -/ structure inf_group [class] (A : Type) extends inf_monoid A, has_inv A := (mul_left_inv : Πa, mul (inv a) a = one) -- Note: with more work, we could derive the axiom one_mul section inf_group variable [s : inf_group A] include s definition mul.left_inv (a : A) : a⁻¹ * a = 1 := !inf_group.mul_left_inv theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := by rewrite [-mul.assoc, mul.left_inv, one_mul] theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a := by rewrite [mul.assoc, mul.left_inv, mul_one] theorem inv_eq_of_mul_eq_one {a b : A} (H : a * b = 1) : a⁻¹ = b := by rewrite [-mul_one a⁻¹, -H, inv_mul_cancel_left] theorem one_inv : 1⁻¹ = (1 : A) := inv_eq_of_mul_eq_one (one_mul 1) theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul.left_inv a) theorem inv.inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b := by rewrite [-inv_inv a, H, inv_inv b] theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b := iff.intro (assume H, inv.inj H) (assume H, ap _ H) theorem inv_eq_one_iff_eq_one (a : A) : a⁻¹ = 1 ↔ a = 1 := one_inv ▸ inv_eq_inv_iff_eq a 1 theorem inv_eq_one {a : A} (H : a = 1) : a⁻¹ = 1 := iff.mpr (inv_eq_one_iff_eq_one a) H theorem eq_one_of_inv_eq_one (a : A) : a⁻¹ = 1 → a = 1 := iff.mp !inv_eq_one_iff_eq_one theorem eq_inv_of_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ := by rewrite [H, inv_inv] theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ := iff.intro !eq_inv_of_eq_inv !eq_inv_of_eq_inv theorem eq_inv_of_mul_eq_one {a b : A} (H : a * b = 1) : a = b⁻¹ := begin apply eq_inv_of_eq_inv, symmetry, exact inv_eq_of_mul_eq_one H end theorem mul.right_inv (a : A) : a * a⁻¹ = 1 := calc a * a⁻¹ = (a⁻¹)⁻¹ * a⁻¹ : inv_inv ... = 1 : mul.left_inv theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = a * a⁻¹ * b : by rewrite mul.assoc ... = 1 * b : mul.right_inv ... = b : one_mul theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a := calc a * b * b⁻¹ = a * (b * b⁻¹) : mul.assoc ... = a * 1 : mul.right_inv ... = a : mul_one theorem mul_inv (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_eq_of_mul_eq_one (calc a * b * (b⁻¹ * a⁻¹) = a * (b * (b⁻¹ * a⁻¹)) : mul.assoc ... = a * a⁻¹ : mul_inv_cancel_left ... = 1 : mul.right_inv) theorem eq_of_mul_inv_eq_one {a b : A} (H : a * b⁻¹ = 1) : a = b := calc a = a * b⁻¹ * b : by rewrite inv_mul_cancel_right ... = 1 * b : H ... = b : one_mul theorem eq_mul_inv_of_mul_eq {a b c : A} (H : a * c = b) : a = b * c⁻¹ := by rewrite [-H, mul_inv_cancel_right] theorem eq_inv_mul_of_mul_eq {a b c : A} (H : b * a = c) : a = b⁻¹ * c := by rewrite [-H, inv_mul_cancel_left] theorem inv_mul_eq_of_eq_mul {a b c : A} (H : b = a * c) : a⁻¹ * b = c := by rewrite [H, inv_mul_cancel_left] theorem mul_inv_eq_of_eq_mul {a b c : A} (H : a = c * b) : a * b⁻¹ = c := by rewrite [H, mul_inv_cancel_right] theorem eq_mul_of_mul_inv_eq {a b c : A} (H : a * c⁻¹ = b) : a = b * c := !inv_inv ▸ (eq_mul_inv_of_mul_eq H) theorem eq_mul_of_inv_mul_eq {a b c : A} (H : b⁻¹ * a = c) : a = b * c := !inv_inv ▸ (eq_inv_mul_of_mul_eq H) theorem mul_eq_of_eq_inv_mul {a b c : A} (H : b = a⁻¹ * c) : a * b = c := !inv_inv ▸ (inv_mul_eq_of_eq_mul H) theorem mul_eq_of_eq_mul_inv {a b c : A} (H : a = c * b⁻¹) : a * b = c := !inv_inv ▸ (mul_inv_eq_of_eq_mul H) theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c := iff.intro eq_inv_mul_of_mul_eq mul_eq_of_eq_inv_mul theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ := iff.intro eq_mul_inv_of_mul_eq mul_eq_of_eq_mul_inv theorem mul_left_cancel {a b c : A} (H : a * b = a * c) : b = c := by rewrite [-inv_mul_cancel_left a b, H, inv_mul_cancel_left] theorem mul_right_cancel {a b c : A} (H : a * b = c * b) : a = c := by rewrite [-mul_inv_cancel_right a b, H, mul_inv_cancel_right] theorem mul_eq_one_of_mul_eq_one {a b : A} (H : b * a = 1) : a * b = 1 := by rewrite [-inv_eq_of_mul_eq_one H, mul.left_inv] theorem mul_eq_one_iff_mul_eq_one (a b : A) : a * b = 1 ↔ b * a = 1 := iff.intro !mul_eq_one_of_mul_eq_one !mul_eq_one_of_mul_eq_one definition conj_by (g a : A) := g * a * g⁻¹ definition is_conjugate (a b : A) := Σ x, conj_by x b = a local infixl ` ~ ` := is_conjugate local infixr ` ∘c `:55 := conj_by lemma conj_compose (f g a : A) : f ∘c g ∘c a = f*g ∘c a := calc f ∘c g ∘c a = f * (g * a * g⁻¹) * f⁻¹ : rfl ... = f * (g * a) * g⁻¹ * f⁻¹ : mul.assoc ... = f * g * a * g⁻¹ * f⁻¹ : mul.assoc ... = f * g * a * (g⁻¹ * f⁻¹) : mul.assoc ... = f * g * a * (f * g)⁻¹ : mul_inv lemma conj_id (a : A) : 1 ∘c a = a := calc 1 * a * 1⁻¹ = a * 1⁻¹ : one_mul ... = a * 1 : one_inv ... = a : mul_one lemma conj_one (g : A) : g ∘c 1 = 1 := calc g * 1 * g⁻¹ = g * g⁻¹ : mul_one ... = 1 : mul.right_inv lemma conj_inv_cancel (g : A) : Π a, g⁻¹ ∘c g ∘c a = a := assume a, calc g⁻¹ ∘c g ∘c a = g⁻¹*g ∘c a : conj_compose ... = 1 ∘c a : mul.left_inv ... = a : conj_id lemma conj_inv (g : A) : Π a, (g ∘c a)⁻¹ = g ∘c a⁻¹ := take a, calc (g * a * g⁻¹)⁻¹ = g⁻¹⁻¹ * (g * a)⁻¹ : mul_inv ... = g⁻¹⁻¹ * (a⁻¹ * g⁻¹) : mul_inv ... = g⁻¹⁻¹ * a⁻¹ * g⁻¹ : mul.assoc ... = g * a⁻¹ * g⁻¹ : inv_inv lemma is_conj.refl (a : A) : a ~ a := sigma.mk 1 (conj_id a) lemma is_conj.symm (a b : A) : a ~ b → b ~ a := assume Pab, obtain x (Pconj : x ∘c b = a), from Pab, have Pxinv : x⁻¹ ∘c x ∘c b = x⁻¹ ∘c a, begin congruence, assumption end, sigma.mk x⁻¹ (inverse (conj_inv_cancel x b ▸ Pxinv)) lemma is_conj.trans (a b c : A) : a ~ b → b ~ c → a ~ c := assume Pab, assume Pbc, obtain x (Px : x ∘c b = a), from Pab, obtain y (Py : y ∘c c = b), from Pbc, sigma.mk (x*y) (calc x*y ∘c c = x ∘c y ∘c c : conj_compose ... = x ∘c b : Py ... = a : Px) definition inf_group.to_left_cancel_inf_semigroup [trans_instance] : left_cancel_inf_semigroup A := ⦃ left_cancel_inf_semigroup, s, mul_left_cancel := @mul_left_cancel A s ⦄ definition inf_group.to_right_cancel_inf_semigroup [trans_instance] : right_cancel_inf_semigroup A := ⦃ right_cancel_inf_semigroup, s, mul_right_cancel := @mul_right_cancel A s ⦄ definition one_unique {a : A} (H : Πb, a * b = b) : a = 1 := !mul_one⁻¹ ⬝ H 1 end inf_group structure ab_inf_group [class] (A : Type) extends inf_group A, comm_inf_monoid A /- additive inf_group -/ definition add_inf_group [class] : Type → Type := inf_group definition add_inf_semigroup_of_add_inf_group [reducible] [trans_instance] (A : Type) [H : add_inf_group A] : add_inf_monoid A := @inf_group.to_inf_monoid A H definition has_neg_of_add_inf_group [reducible] [trans_instance] (A : Type) [H : add_inf_group A] : has_neg A := has_neg.mk (@inf_group.inv A H) section add_inf_group variables [s : add_inf_group A] include s theorem add.left_inv (a : A) : -a + a = 0 := @inf_group.mul_left_inv A s a theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := by rewrite [-add.assoc, add.left_inv, zero_add] theorem neg_add_cancel_right (a b : A) : a + -b + b = a := by rewrite [add.assoc, add.left_inv, add_zero] theorem neg_eq_of_add_eq_zero {a b : A} (H : a + b = 0) : -a = b := by rewrite [-add_zero (-a), -H, neg_add_cancel_left] theorem neg_zero : -0 = (0 : A) := neg_eq_of_add_eq_zero (zero_add 0) theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add.left_inv a) theorem eq_neg_of_add_eq_zero {a b : A} (H : a + b = 0) : a = -b := by rewrite [-neg_eq_of_add_eq_zero H, neg_neg] theorem neg.inj {a b : A} (H : -a = -b) : a = b := calc a = -(-a) : neg_neg ... = b : neg_eq_of_add_eq_zero (H⁻¹ ▸ (add.left_inv _)) theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b := iff.intro (assume H, neg.inj H) (assume H, ap _ H) theorem eq_of_neg_eq_neg {a b : A} : -a = -b → a = b := iff.mp !neg_eq_neg_iff_eq theorem neg_eq_zero_iff_eq_zero (a : A) : -a = 0 ↔ a = 0 := neg_zero ▸ !neg_eq_neg_iff_eq theorem eq_zero_of_neg_eq_zero {a : A} : -a = 0 → a = 0 := iff.mp !neg_eq_zero_iff_eq_zero theorem eq_neg_of_eq_neg {a b : A} (H : a = -b) : b = -a := H⁻¹ ▸ (neg_neg b)⁻¹ theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a := iff.intro !eq_neg_of_eq_neg !eq_neg_of_eq_neg theorem add.right_inv (a : A) : a + -a = 0 := calc a + -a = -(-a) + -a : neg_neg ... = 0 : add.left_inv theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b := by rewrite [-add.assoc, add.right_inv, zero_add] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := by rewrite [add.assoc, add.right_inv, add_zero] theorem neg_add_rev (a b : A) : -(a + b) = -b + -a := neg_eq_of_add_eq_zero begin rewrite [add.assoc, add_neg_cancel_left, add.right_inv] end -- TODO: delete these in favor of sub rules? theorem eq_add_neg_of_add_eq {a b c : A} (H : a + c = b) : a = b + -c := H ▸ !add_neg_cancel_right⁻¹ theorem eq_neg_add_of_add_eq {a b c : A} (H : b + a = c) : a = -b + c := H ▸ !neg_add_cancel_left⁻¹ theorem neg_add_eq_of_eq_add {a b c : A} (H : b = a + c) : -a + b = c := H⁻¹ ▸ !neg_add_cancel_left theorem add_neg_eq_of_eq_add {a b c : A} (H : a = c + b) : a + -b = c := H⁻¹ ▸ !add_neg_cancel_right theorem eq_add_of_add_neg_eq {a b c : A} (H : a + -c = b) : a = b + c := !neg_neg ▸ (eq_add_neg_of_add_eq H) theorem eq_add_of_neg_add_eq {a b c : A} (H : -b + a = c) : a = b + c := !neg_neg ▸ (eq_neg_add_of_add_eq H) theorem add_eq_of_eq_neg_add {a b c : A} (H : b = -a + c) : a + b = c := !neg_neg ▸ (neg_add_eq_of_eq_add H) theorem add_eq_of_eq_add_neg {a b c : A} (H : a = c + -b) : a + b = c := !neg_neg ▸ (add_neg_eq_of_eq_add H) theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c := iff.intro eq_neg_add_of_add_eq add_eq_of_eq_neg_add theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b := iff.intro eq_add_neg_of_add_eq add_eq_of_eq_add_neg theorem add_left_cancel {a b c : A} (H : a + b = a + c) : b = c := calc b = -a + (a + b) : !neg_add_cancel_left⁻¹ ... = -a + (a + c) : H ... = c : neg_add_cancel_left theorem add_right_cancel {a b c : A} (H : a + b = c + b) : a = c := calc a = (a + b) + -b : !add_neg_cancel_right⁻¹ ... = (c + b) + -b : H ... = c : add_neg_cancel_right definition add_inf_group.to_add_left_cancel_inf_semigroup [reducible] [trans_instance] : add_left_cancel_inf_semigroup A := @inf_group.to_left_cancel_inf_semigroup A s definition add_inf_group.to_add_right_cancel_inf_semigroup [reducible] [trans_instance] : add_right_cancel_inf_semigroup A := @inf_group.to_right_cancel_inf_semigroup A s theorem add_neg_eq_neg_add_rev {a b : A} : a + -b = -(b + -a) := by rewrite [neg_add_rev, neg_neg] /- sub -/ -- TODO: derive corresponding facts for div in a field protected definition algebra.sub [reducible] (a b : A) : A := a + -b definition add_inf_group_has_sub [instance] : has_sub A := has_sub.mk algebra.sub theorem sub_eq_add_neg (a b : A) : a - b = a + -b := rfl theorem sub_self (a : A) : a - a = 0 := !add.right_inv theorem sub_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right theorem add_sub_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right theorem eq_of_sub_eq_zero {a b : A} (H : a - b = 0) : a = b := calc a = (a - b) + b : !sub_add_cancel⁻¹ ... = 0 + b : H ... = b : zero_add theorem eq_iff_sub_eq_zero (a b : A) : a = b ↔ a - b = 0 := iff.intro (assume H, H ▸ !sub_self) (assume H, eq_of_sub_eq_zero H) theorem zero_sub (a : A) : 0 - a = -a := !zero_add theorem sub_zero (a : A) : a - 0 = a := by rewrite [sub_eq_add_neg, neg_zero, add_zero] theorem sub_neg_eq_add (a b : A) : a - (-b) = a + b := by change a + -(-b) = a + b; rewrite neg_neg theorem neg_sub (a b : A) : -(a - b) = b - a := neg_eq_of_add_eq_zero (calc a - b + (b - a) = a - b + b - a : by krewrite -add.assoc ... = a - a : sub_add_cancel ... = 0 : sub_self) theorem add_sub (a b c : A) : a + (b - c) = a + b - c := !add.assoc⁻¹ theorem sub_add_eq_sub_sub_swap (a b c : A) : a - (b + c) = a - c - b := calc a - (b + c) = a + (-c - b) : by rewrite [sub_eq_add_neg, neg_add_rev] ... = a - c - b : by krewrite -add.assoc theorem sub_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b := iff.intro (assume H, eq_add_of_add_neg_eq H) (assume H, add_neg_eq_of_eq_add H) theorem eq_sub_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b := iff.intro (assume H, add_eq_of_eq_add_neg H) (assume H, eq_add_neg_of_add_eq H) theorem eq_iff_eq_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d := calc a = b ↔ a - b = 0 : eq_iff_sub_eq_zero ... = (c - d = 0) : H ... ↔ c = d : iff.symm (eq_iff_sub_eq_zero c d) theorem eq_sub_of_add_eq {a b c : A} (H : a + c = b) : a = b - c := !eq_add_neg_of_add_eq H theorem sub_eq_of_eq_add {a b c : A} (H : a = c + b) : a - b = c := !add_neg_eq_of_eq_add H theorem eq_add_of_sub_eq {a b c : A} (H : a - c = b) : a = b + c := eq_add_of_add_neg_eq H theorem add_eq_of_eq_sub {a b c : A} (H : a = c - b) : a + b = c := add_eq_of_eq_add_neg H definition zero_unique {a : A} (H : Πb, a + b = b) : a = 0 := !add_zero⁻¹ ⬝ H 0 end add_inf_group definition add_ab_inf_group [class] : Type → Type := ab_inf_group definition add_inf_group_of_add_ab_inf_group [reducible] [trans_instance] (A : Type) [H : add_ab_inf_group A] : add_inf_group A := @ab_inf_group.to_inf_group A H definition add_comm_inf_monoid_of_add_ab_inf_group [reducible] [trans_instance] (A : Type) [H : add_ab_inf_group A] : add_comm_inf_monoid A := @ab_inf_group.to_comm_inf_monoid A H section add_ab_inf_group variable [s : add_ab_inf_group A] include s theorem sub_add_eq_sub_sub (a b c : A) : a - (b + c) = a - b - c := !add.comm ▸ !sub_add_eq_sub_sub_swap theorem neg_add_eq_sub (a b : A) : -a + b = b - a := !add.comm theorem neg_add (a b : A) : -(a + b) = -a + -b := add.comm (-b) (-a) ▸ neg_add_rev a b theorem sub_add_eq_add_sub (a b c : A) : a - b + c = a + c - b := !add.right_comm theorem sub_sub (a b c : A) : a - b - c = a - (b + c) := by rewrite [▸ a + -b + -c = _, add.assoc, -neg_add] theorem add_sub_add_left_eq_sub (a b c : A) : (c + a) - (c + b) = a - b := by rewrite [sub_add_eq_sub_sub, (add.comm c a), add_sub_cancel] theorem eq_sub_of_add_eq' {a b c : A} (H : c + a = b) : a = b - c := !eq_sub_of_add_eq (!add.comm ▸ H) theorem sub_eq_of_eq_add' {a b c : A} (H : a = b + c) : a - b = c := !sub_eq_of_eq_add (!add.comm ▸ H) theorem eq_add_of_sub_eq' {a b c : A} (H : a - b = c) : a = b + c := !add.comm ▸ eq_add_of_sub_eq H theorem add_eq_of_eq_sub' {a b c : A} (H : b = c - a) : a + b = c := !add.comm ▸ add_eq_of_eq_sub H theorem sub_sub_self (a b : A) : a - (a - b) = b := by rewrite [sub_eq_add_neg, neg_sub, add.comm, sub_add_cancel] theorem add_sub_comm (a b c d : A) : a + b - (c + d) = (a - c) + (b - d) := by rewrite [sub_add_eq_sub_sub, -sub_add_eq_add_sub a c b, add_sub] theorem sub_eq_sub_add_sub (a b c : A) : a - b = c - b + (a - c) := by rewrite [add_sub, sub_add_cancel] ⬝ !add.comm theorem neg_neg_sub_neg (a b : A) : - (-a - -b) = a - b := by rewrite [neg_sub, sub_neg_eq_add, neg_add_eq_sub] end add_ab_inf_group definition inf_group_of_add_inf_group (A : Type) [G : add_inf_group A] : inf_group A := ⦃inf_group, mul := has_add.add, mul_assoc := add.assoc, one := !has_zero.zero, one_mul := zero_add, mul_one := add_zero, inv := has_neg.neg, mul_left_inv := add.left_inv ⦄ namespace norm_num definition add1 [s : has_add A] [s' : has_one A] (a : A) : A := add a one theorem add_comm_four [s : add_comm_inf_semigroup A] (a b : A) : a + a + (b + b) = (a + b) + (a + b) := by rewrite [-add.assoc at {1}, add.comm, {a + b}add.comm at {1}, *add.assoc] theorem add_comm_middle [s : add_comm_inf_semigroup A] (a b c : A) : a + b + c = a + c + b := by rewrite [add.assoc, add.comm b, -add.assoc] theorem bit0_add_bit0 [s : add_comm_inf_semigroup A] (a b : A) : bit0 a + bit0 b = bit0 (a + b) := !add_comm_four theorem bit0_add_bit0_helper [s : add_comm_inf_semigroup A] (a b t : A) (H : a + b = t) : bit0 a + bit0 b = bit0 t := by rewrite -H; apply bit0_add_bit0 theorem bit1_add_bit0 [s : add_comm_inf_semigroup A] [s' : has_one A] (a b : A) : bit1 a + bit0 b = bit1 (a + b) := begin rewrite [↑bit0, ↑bit1, add_comm_middle], congruence, apply add_comm_four end theorem bit1_add_bit0_helper [s : add_comm_inf_semigroup A] [s' : has_one A] (a b t : A) (H : a + b = t) : bit1 a + bit0 b = bit1 t := by rewrite -H; apply bit1_add_bit0 theorem bit0_add_bit1 [s : add_comm_inf_semigroup A] [s' : has_one A] (a b : A) : bit0 a + bit1 b = bit1 (a + b) := by rewrite [{bit0 a + bit1 b}add.comm,{a + b}add.comm]; exact bit1_add_bit0 b a theorem bit0_add_bit1_helper [s : add_comm_inf_semigroup A] [s' : has_one A] (a b t : A) (H : a + b = t) : bit0 a + bit1 b = bit1 t := by rewrite -H; apply bit0_add_bit1 theorem bit1_add_bit1 [s : add_comm_inf_semigroup A] [s' : has_one A] (a b : A) : bit1 a + bit1 b = bit0 (add1 (a + b)) := begin rewrite ↑[bit0, bit1, add1, add.assoc], rewrite [*add.assoc, {_ + (b + 1)}add.comm, {_ + (b + 1 + _)}add.comm, {_ + (b + 1 + _ + _)}add.comm, *add.assoc, {1 + a}add.comm, -{b + (a + 1)}add.assoc, {b + a}add.comm, *add.assoc] end theorem bit1_add_bit1_helper [s : add_comm_inf_semigroup A] [s' : has_one A] (a b t s: A) (H : (a + b) = t) (H2 : add1 t = s) : bit1 a + bit1 b = bit0 s := begin rewrite [-H2, -H], apply bit1_add_bit1 end theorem bin_add_zero [s : add_inf_monoid A] (a : A) : a + zero = a := !add_zero theorem bin_zero_add [s : add_inf_monoid A] (a : A) : zero + a = a := !zero_add theorem one_add_bit0 [s : add_comm_inf_semigroup A] [s' : has_one A] (a : A) : one + bit0 a = bit1 a := begin rewrite ↑[bit0, bit1], rewrite add.comm end theorem bit0_add_one [s : has_add A] [s' : has_one A] (a : A) : bit0 a + one = bit1 a := rfl theorem bit1_add_one [s : has_add A] [s' : has_one A] (a : A) : bit1 a + one = add1 (bit1 a) := rfl theorem bit1_add_one_helper [s : has_add A] [s' : has_one A] (a t : A) (H : add1 (bit1 a) = t) : bit1 a + one = t := by rewrite -H theorem one_add_bit1 [s : add_comm_inf_semigroup A] [s' : has_one A] (a : A) : one + bit1 a = add1 (bit1 a) := !add.comm theorem one_add_bit1_helper [s : add_comm_inf_semigroup A] [s' : has_one A] (a t : A) (H : add1 (bit1 a) = t) : one + bit1 a = t := by rewrite -H; apply one_add_bit1 theorem add1_bit0 [s : has_add A] [s' : has_one A] (a : A) : add1 (bit0 a) = bit1 a := rfl theorem add1_bit1 [s : add_comm_inf_semigroup A] [s' : has_one A] (a : A) : add1 (bit1 a) = bit0 (add1 a) := begin rewrite ↑[add1, bit1, bit0], rewrite [add.assoc, add_comm_four] end theorem add1_bit1_helper [s : add_comm_inf_semigroup A] [s' : has_one A] (a t : A) (H : add1 a = t) : add1 (bit1 a) = bit0 t := by rewrite -H; apply add1_bit1 theorem add1_one [s : has_add A] [s' : has_one A] : add1 (one : A) = bit0 one := rfl theorem add1_zero [s : add_inf_monoid A] [s' : has_one A] : add1 (zero : A) = one := begin rewrite [↑add1, zero_add] end theorem one_add_one [s : has_add A] [s' : has_one A] : (one : A) + one = bit0 one := rfl theorem subst_into_sum [s : has_add A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rewrite [prl, prr, prt] theorem neg_zero_helper [s : add_inf_group A] (a : A) (H : a = 0) : - a = 0 := by rewrite [H, neg_zero] end norm_num end algebra open algebra attribute [simp] zero_add add_zero one_mul mul_one at simplifier.unit attribute [simp] neg_neg sub_eq_add_neg at simplifier.neg attribute [simp] add.assoc add.comm add.left_comm mul.left_comm mul.comm mul.assoc at simplifier.ac
7e6d99cc4374ef29457d875a64c16e8730701f21
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/geometry/euclidean/circumcenter.lean
4af9103976beb0770ef4e0b1e2024109362ef84b
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,254
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 geometry.euclidean.basic import linear_algebra.affine_space.finite_dimensional import tactic.derive_fintype /-! # Circumcenter and circumradius This file proves some lemmas on points equidistant from a set of points, and defines the circumradius and circumcenter of a simplex. There are also some definitions for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. ## Main definitions * `circumcenter` and `circumradius` are the circumcenter and circumradius of a simplex. ## References * https://en.wikipedia.org/wiki/Circumscribed_circle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace euclidean_geometry open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V open affine_subspace /-- `p` is equidistant from two points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 p2 : P} (p3 : P) (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : dist p1 p3 = dist p2 p3 ↔ dist p1 (orthogonal_projection s p3) = dist p2 (orthogonal_projection s p3) := begin rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, ←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp1, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p3 hp2], simp end /-- `p` is equidistant from a set of points in `s` if and only if its `orthogonal_projection` is. -/ lemma dist_set_eq_iff_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : (set.pairwise ps (λ p1 p2, dist p1 p = dist p2 p) ↔ (set.pairwise ps (λ p1 p2, dist p1 (orthogonal_projection s p) = dist p2 (orthogonal_projection s p)))) := ⟨λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).1 (h p1 hp1 p2 hp2 hne), λ h p1 hp1 p2 hp2 hne, (dist_eq_iff_dist_orthogonal_projection_eq p (hps hp1) (hps hp2)).2 (h p1 hp1 p2 hp2 hne)⟩ /-- There exists `r` such that `p` has distance `r` from all the points of a set of points in `s` if and only if there exists (possibly different) `r` such that its `orthogonal_projection` has that distance from all the points in that set. -/ lemma exists_dist_eq_iff_exists_dist_orthogonal_projection_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {ps : set P} (hps : ps ⊆ s) (p : P) : (∃ r, ∀ p1 ∈ ps, dist p1 p = r) ↔ ∃ r, ∀ p1 ∈ ps, dist p1 ↑(orthogonal_projection s p) = r := begin have h := dist_set_eq_iff_dist_orthogonal_projection_eq hps p, simp_rw set.pairwise_eq_iff_exists_eq at h, exact h end /-- The induction step for the existence and uniqueness of the circumcenter. Given a nonempty set of points in a nonempty affine subspace whose direction is complete, such that there is a unique (circumcenter, circumradius) pair for those points in that subspace, and a point `p` not in that subspace, there is a unique (circumcenter, circumradius) pair for the set with `p` added, in the span of the subspace with `p` added. -/ lemma exists_unique_dist_eq_of_insert {s : affine_subspace ℝ P} [complete_space s.direction] {ps : set P} (hnps : ps.nonempty) {p : P} (hps : ps ⊆ s) (hp : p ∉ s) (hu : ∃! cccr : (P × ℝ), cccr.fst ∈ s ∧ ∀ p1 ∈ ps, dist p1 cccr.fst = cccr.snd) : ∃! cccr₂ : (P × ℝ), cccr₂.fst ∈ affine_span ℝ (insert p (s : set P)) ∧ ∀ p1 ∈ insert p ps, dist p1 cccr₂.fst = cccr₂.snd := begin haveI : nonempty s := set.nonempty.to_subtype (hnps.mono hps), rcases hu with ⟨⟨cc, cr⟩, ⟨hcc, hcr⟩, hcccru⟩, simp only [prod.fst, prod.snd] at hcc hcr hcccru, let x := dist cc (orthogonal_projection s p), let y := dist p (orthogonal_projection s p), have hy0 : y ≠ 0 := dist_orthogonal_projection_ne_zero_of_not_mem hp, let ycc₂ := (x * x + y * y - cr * cr) / (2 * y), let cc₂ := (ycc₂ / y) • (p -ᵥ orthogonal_projection s p : V) +ᵥ cc, let cr₂ := real.sqrt (cr * cr + ycc₂ * ycc₂), use (cc₂, cr₂), simp only [prod.fst, prod.snd], have hpo : p = (1 : ℝ) • (p -ᵥ orthogonal_projection s p : V) +ᵥ orthogonal_projection s p, { simp }, split, { split, { refine vadd_mem_of_mem_direction _ (mem_affine_span ℝ (set.mem_insert_of_mem _ hcc)), rw direction_affine_span, exact submodule.smul_mem _ _ (vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (orthogonal_projection_mem _))) }, { intros p1 hp1, rw [←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))], cases hp1, { rw hp1, rw [hpo, dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), ←dist_eq_norm_vsub V p, dist_comm _ cc], field_simp [hy0], ring }, { rw [dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp1), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc, subtype.coe_mk, hcr _ hp1, dist_eq_norm_vsub V cc₂ cc, vadd_vsub, norm_smul, ←dist_eq_norm_vsub V, real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg, div_mul_cancel _ hy0, abs_mul_abs_self] } } }, { rintros ⟨cc₃, cr₃⟩ ⟨hcc₃, hcr₃⟩, simp only [prod.fst, prod.snd] at hcc₃ hcr₃, obtain ⟨t₃, cc₃', hcc₃', hcc₃''⟩ : ∃ (r : ℝ) (p0 : P) (hp0 : p0 ∈ s), cc₃ = r • (p -ᵥ ↑((orthogonal_projection s) p)) +ᵥ p0, { rwa mem_affine_span_insert_iff (orthogonal_projection_mem p) at hcc₃ }, have hcr₃' : ∃ r, ∀ p1 ∈ ps, dist p1 cc₃ = r := ⟨cr₃, λ p1 hp1, hcr₃ p1 (set.mem_insert_of_mem _ hp1)⟩, rw [exists_dist_eq_iff_exists_dist_orthogonal_projection_eq hps cc₃, hcc₃'', orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃'] at hcr₃', cases hcr₃' with cr₃' hcr₃', have hu := hcccru (cc₃', cr₃'), simp only [prod.fst, prod.snd] at hu, replace hu := hu ⟨hcc₃', hcr₃'⟩, rw prod.ext_iff at hu, simp only [prod.fst, prod.snd] at hu, cases hu with hucc hucr, substs hucc hucr, have hcr₃val : cr₃ = real.sqrt (cr₃' * cr₃' + (t₃ * y) * (t₃ * y)), { cases hnps with p0 hp0, have h' : ↑(⟨cc₃', hcc₃'⟩ : s) = cc₃' := rfl, rw [←hcr₃ p0 (set.mem_insert_of_mem _ hp0), hcc₃'', ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)), dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq _ (hps hp0), orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hcc₃', h', hcr p0 hp0, dist_eq_norm_vsub V _ cc₃', vadd_vsub, norm_smul, ←dist_eq_norm_vsub V p, real.norm_eq_abs, ←mul_assoc, mul_comm _ (|t₃|), ←mul_assoc, abs_mul_abs_self], ring }, replace hcr₃ := hcr₃ p (set.mem_insert _ _), rw [hpo, hcc₃'', hcr₃val, ←mul_self_inj_of_nonneg dist_nonneg (real.sqrt_nonneg _), dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd (orthogonal_projection_mem p) hcc₃' _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s p), dist_comm, ←dist_eq_norm_vsub V p, real.mul_self_sqrt (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _))] at hcr₃, change x * x + _ * (y * y) = _ at hcr₃, rw [(show x * x + (1 - t₃) * (1 - t₃) * (y * y) = x * x + y * y - 2 * y * (t₃ * y) + t₃ * y * (t₃ * y), by ring), add_left_inj] at hcr₃, have ht₃ : t₃ = ycc₂ / y, { field_simp [←hcr₃, hy0], ring }, subst ht₃, change cc₃ = cc₂ at hcc₃'', congr', rw hcr₃val, congr' 2, field_simp [hy0], ring } end /-- Given a finite nonempty affinely independent family of points, there is a unique (circumcenter, circumradius) pair for those points in the affine subspace they span. -/ lemma _root_.affine_independent.exists_unique_dist_eq {ι : Type*} [hne : nonempty ι] [fintype ι] {p : ι → P} (ha : affine_independent ℝ p) : ∃! cccr : (P × ℝ), cccr.fst ∈ affine_span ℝ (set.range p) ∧ ∀ i, dist (p i) cccr.fst = cccr.snd := begin unfreezingI { induction hn : fintype.card ι with m hm generalizing ι }, { exfalso, have h := fintype.card_pos_iff.2 hne, rw hn at h, exact lt_irrefl 0 h }, { cases m, { rw fintype.card_eq_one_iff at hn, cases hn with i hi, haveI : unique ι := ⟨⟨i⟩, hi⟩, use (p i, 0), simp only [prod.fst, prod.snd, set.range_unique, affine_subspace.mem_affine_span_singleton], split, { simp_rw [hi (default ι)], use rfl, intro i1, rw hi i1, exact dist_self _ }, { rintros ⟨cc, cr⟩, simp only [prod.fst, prod.snd], rintros ⟨rfl, hdist⟩, rw hi (default ι), congr', rw ←hdist (default ι), exact dist_self _ } }, { have i := hne.some, let ι2 := {x // x ≠ i}, have hc : fintype.card ι2 = m + 1, { rw fintype.card_of_subtype (finset.univ.filter (λ x, x ≠ i)), { rw finset.filter_not, simp_rw eq_comm, rw [finset.filter_eq, if_pos (finset.mem_univ _), finset.card_sdiff (finset.subset_univ _), finset.card_singleton, finset.card_univ, hn], simp }, { simp } }, haveI : nonempty ι2 := fintype.card_pos_iff.1 (hc.symm ▸ nat.zero_lt_succ _), have ha2 : affine_independent ℝ (λ i2 : ι2, p i2) := ha.subtype _, replace hm := hm ha2 hc, have hr : set.range p = insert (p i) (set.range (λ i2 : ι2, p i2)), { change _ = insert _ (set.range (λ i2 : {x | x ≠ i}, p i2)), rw [←set.image_eq_range, ←set.image_univ, ←set.image_insert_eq], congr' with j, simp [classical.em] }, change ∃! (cccr : P × ℝ), (_ ∧ ∀ i2, (λ q, dist q cccr.fst = cccr.snd) (p i2)), conv { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, dsimp only, rw hr, change ∃! (cccr : P × ℝ), (_ ∧ ∀ (i2 : ι2), (λ q, dist q cccr.fst = cccr.snd) (p i2)) at hm, conv at hm { congr, funext, conv { congr, skip, rw ←set.forall_range_iff } }, rw ←affine_span_insert_affine_span, refine exists_unique_dist_eq_of_insert (set.range_nonempty _) (subset_span_points ℝ _) _ hm, convert ha.not_mem_affine_span_diff i set.univ, change set.range (λ i2 : {x | x ≠ i}, p i2) = _, rw ←set.image_eq_range, congr' with j, simp, refl } } end end euclidean_geometry namespace affine namespace simplex open finset affine_subspace euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The pair (circumcenter, circumradius) of a simplex. -/ def circumcenter_circumradius {n : ℕ} (s : simplex ℝ P n) : (P × ℝ) := s.independent.exists_unique_dist_eq.some /-- The property satisfied by the (circumcenter, circumradius) pair. -/ lemma circumcenter_circumradius_unique_dist_eq {n : ℕ} (s : simplex ℝ P n) : (s.circumcenter_circumradius.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) s.circumcenter_circumradius.fst = s.circumcenter_circumradius.snd) ∧ (∀ cccr : (P × ℝ), (cccr.fst ∈ affine_span ℝ (set.range s.points) ∧ ∀ i, dist (s.points i) cccr.fst = cccr.snd) → cccr = s.circumcenter_circumradius) := s.independent.exists_unique_dist_eq.some_spec /-- The circumcenter of a simplex. -/ def circumcenter {n : ℕ} (s : simplex ℝ P n) : P := s.circumcenter_circumradius.fst /-- The circumradius of a simplex. -/ def circumradius {n : ℕ} (s : simplex ℝ P n) : ℝ := s.circumcenter_circumradius.snd /-- The circumcenter lies in the affine span. -/ lemma circumcenter_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.circumcenter ∈ affine_span ℝ (set.range s.points) := s.circumcenter_circumradius_unique_dist_eq.1.1 /-- All points have distance from the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist (s.points i) s.circumcenter = s.circumradius := s.circumcenter_circumradius_unique_dist_eq.1.2 /-- All points have distance to the circumcenter equal to the circumradius. -/ @[simp] lemma dist_circumcenter_eq_circumradius' {n : ℕ} (s : simplex ℝ P n) : ∀ i, dist s.circumcenter (s.points i) = s.circumradius := begin intro i, rw dist_comm, exact dist_circumcenter_eq_circumradius _ _ end /-- Given a point in the affine span from which all the points are equidistant, that point is the circumcenter. -/ lemma eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : p = s.circumcenter := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.1 end /-- Given a point in the affine span from which all the points are equidistant, that distance is the circumradius. -/ lemma eq_circumradius_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hp : p ∈ affine_span ℝ (set.range s.points)) {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : r = s.circumradius := begin have h := s.circumcenter_circumradius_unique_dist_eq.2 (p, r), simp only [hp, hr, forall_const, eq_self_iff_true, and_self, prod.ext_iff] at h, exact h.2 end /-- The circumradius is non-negative. -/ lemma circumradius_nonneg {n : ℕ} (s : simplex ℝ P n) : 0 ≤ s.circumradius := s.dist_circumcenter_eq_circumradius 0 ▸ dist_nonneg /-- The circumradius of a simplex with at least two points is positive. -/ lemma circumradius_pos {n : ℕ} (s : simplex ℝ P (n + 1)) : 0 < s.circumradius := begin refine lt_of_le_of_ne s.circumradius_nonneg _, intro h, have hr := s.dist_circumcenter_eq_circumradius, simp_rw [←h, dist_eq_zero] at hr, have h01 := s.independent.injective.ne (dec_trivial : (0 : fin (n + 2)) ≠ 1), simpa [hr] using h01 end /-- The circumcenter of a 0-simplex equals its unique point. -/ lemma circumcenter_eq_point (s : simplex ℝ P 0) (i : fin 1) : s.circumcenter = s.points i := begin have h := s.circumcenter_mem_affine_span, rw [set.range_unique, mem_affine_span_singleton] at h, rw h, congr end /-- The circumcenter of a 1-simplex equals its centroid. -/ lemma circumcenter_eq_centroid (s : simplex ℝ P 1) : s.circumcenter = finset.univ.centroid ℝ s.points := begin have hr : set.pairwise set.univ (λ i j : fin 2, dist (s.points i) (finset.univ.centroid ℝ s.points) = dist (s.points j) (finset.univ.centroid ℝ s.points)), { intros i hi j hj hij, rw [finset.centroid_insert_singleton_fin, dist_eq_norm_vsub V (s.points i), dist_eq_norm_vsub V (s.points j), vsub_vadd_eq_vsub_sub, vsub_vadd_eq_vsub_sub, ←one_smul ℝ (s.points i -ᵥ s.points 0), ←one_smul ℝ (s.points j -ᵥ s.points 0)], fin_cases i; fin_cases j; simp [-one_smul, ←sub_smul]; norm_num }, rw set.pairwise_eq_iff_exists_eq at hr, cases hr with r hr, exact (s.eq_circumcenter_of_dist_eq (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (finset.card_fin 2)) (λ i, hr i (set.mem_univ _))).symm end /-- If there exists a distance that a point has from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_exists_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} (hr : ∃ r, ∀ i, dist (s.points i) p = r) : ↑(orthogonal_projection (affine_span ℝ (set.range s.points)) p) = s.circumcenter := begin change ∃ r : ℝ, ∀ i, (λ x, dist x p = r) (s.points i) at hr, conv at hr { congr, funext, rw ←set.forall_range_iff }, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq (subset_affine_span ℝ _) p at hr, cases hr with r hr, exact s.eq_circumcenter_of_dist_eq (orthogonal_projection_mem p) (λ i, hr _ (set.mem_range_self i)), end /-- If a point has the same distance from all vertices of a simplex, the orthogonal projection of that point onto the subspace spanned by that simplex is its circumcenter. -/ lemma orthogonal_projection_eq_circumcenter_of_dist_eq {n : ℕ} (s : simplex ℝ P n) {p : P} {r : ℝ} (hr : ∀ i, dist (s.points i) p = r) : ↑(orthogonal_projection (affine_span ℝ (set.range s.points)) p) = s.circumcenter := s.orthogonal_projection_eq_circumcenter_of_exists_dist_eq ⟨r, hr⟩ /-- The orthogonal projection of the circumcenter onto a face is the circumcenter of that face. -/ lemma orthogonal_projection_circumcenter {n : ℕ} (s : simplex ℝ P n) {fs : finset (fin (n + 1))} {m : ℕ} (h : fs.card = m + 1) : ↑(orthogonal_projection (affine_span ℝ (set.range (s.face h).points)) s.circumcenter) = (s.face h).circumcenter := begin have hr : ∃ r, ∀ i, dist ((s.face h).points i) s.circumcenter = r, { use s.circumradius, simp [face_points] }, exact orthogonal_projection_eq_circumcenter_of_exists_dist_eq _ hr end /-- Two simplices with the same points have the same circumcenter. -/ lemma circumcenter_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.circumcenter = s₂.circumcenter := begin have hs : s₁.circumcenter ∈ affine_span ℝ (set.range s₂.points) := h ▸ s₁.circumcenter_mem_affine_span, have hr : ∀ i, dist (s₂.points i) s₁.circumcenter = s₁.circumradius, { intro i, have hi : s₂.points i ∈ set.range s₂.points := set.mem_range_self _, rw [←h, set.mem_range] at hi, rcases hi with ⟨j, hj⟩, rw [←hj, s₁.dist_circumcenter_eq_circumradius j] }, exact s₂.eq_circumcenter_of_dist_eq hs hr end omit V /-- An index type for the vertices of a simplex plus its circumcenter. This is for use in calculations where it is convenient to work with affine combinations of vertices together with the circumcenter. (An equivalent form sometimes used in the literature is placing the circumcenter at the origin and working with vectors for the vertices.) -/ @[derive fintype] inductive points_with_circumcenter_index (n : ℕ) | point_index : fin (n + 1) → points_with_circumcenter_index | circumcenter_index : points_with_circumcenter_index open points_with_circumcenter_index instance points_with_circumcenter_index_inhabited (n : ℕ) : inhabited (points_with_circumcenter_index n) := ⟨circumcenter_index⟩ /-- `point_index` as an embedding. -/ def point_index_embedding (n : ℕ) : fin (n + 1) ↪ points_with_circumcenter_index n := ⟨λ i, point_index i, λ _ _ h, by injection h⟩ /-- The sum of a function over `points_with_circumcenter_index`. -/ lemma sum_points_with_circumcenter {α : Type*} [add_comm_monoid α] {n : ℕ} (f : points_with_circumcenter_index n → α) : ∑ i, f i = (∑ (i : fin (n + 1)), f (point_index i)) + f circumcenter_index := begin have h : univ = insert circumcenter_index (univ.map (point_index_embedding n)), { ext x, refine ⟨λ h, _, λ _, mem_univ _⟩, cases x with i, { exact mem_insert_of_mem (mem_map_of_mem _ (mem_univ i)) }, { exact mem_insert_self _ _ } }, change _ = ∑ i, f (point_index_embedding n i) + _, rw [add_comm, h, ←sum_map, sum_insert], simp_rw [mem_map, not_exists], intros x hx h, injection h end include V /-- The vertices of a simplex plus its circumcenter. -/ def points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : points_with_circumcenter_index n → P | (point_index i) := s.points i | circumcenter_index := s.circumcenter /-- `points_with_circumcenter`, applied to a `point_index` value, equals `points` applied to that value. -/ @[simp] lemma points_with_circumcenter_point {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points_with_circumcenter (point_index i) = s.points i := rfl /-- `points_with_circumcenter`, applied to `circumcenter_index`, equals the circumcenter. -/ @[simp] lemma points_with_circumcenter_eq_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.points_with_circumcenter circumcenter_index = s.circumcenter := rfl omit V /-- The weights for a single vertex of a simplex, in terms of `points_with_circumcenter`. -/ def point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index j) := if j = i then 1 else 0 | circumcenter_index := 0 /-- `point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_point_weights_with_circumcenter {n : ℕ} (i : fin (n + 1)) : ∑ j, point_weights_with_circumcenter i j = 1 := begin convert sum_ite_eq' univ (point_index i) (function.const _ (1 : ℝ)), { ext j, cases j ; simp [point_weights_with_circumcenter] }, { simp } end include V /-- A single vertex, in terms of `points_with_circumcenter`. -/ lemma point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (i : fin (n + 1)) : s.points i = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (point_weights_with_circumcenter i) := begin rw ←points_with_circumcenter_point, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) (by simp [point_weights_with_circumcenter]) _, intros i hi hn, cases i, { have h : i_1 ≠ i := λ h, hn (h ▸ rfl), simp [point_weights_with_circumcenter, h] }, { refl } end omit V /-- The weights for the centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ def centroid_weights_with_circumcenter {n : ℕ} (fs : finset (fin (n + 1))) : points_with_circumcenter_index n → ℝ | (point_index i) := if i ∈ fs then ((card fs : ℝ) ⁻¹) else 0 | circumcenter_index := 0 /-- `centroid_weights_with_circumcenter` sums to 1, if the `finset` is nonempty. -/ @[simp] lemma sum_centroid_weights_with_circumcenter {n : ℕ} {fs : finset (fin (n + 1))} (h : fs.nonempty) : ∑ i, centroid_weights_with_circumcenter fs i = 1 := begin simp_rw [sum_points_with_circumcenter, centroid_weights_with_circumcenter, add_zero, ←fs.sum_centroid_weights_eq_one_of_nonempty ℝ h, set.sum_indicator_subset _ fs.subset_univ], rcongr end include V /-- The centroid of some vertices of a simplex, in terms of `points_with_circumcenter`. -/ lemma centroid_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) (fs : finset (fin (n + 1))) : fs.centroid ℝ s.points = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (centroid_weights_with_circumcenter fs) := begin simp_rw [centroid_def, affine_combination_apply, weighted_vsub_of_point_apply, sum_points_with_circumcenter, centroid_weights_with_circumcenter, points_with_circumcenter_point, zero_smul, add_zero, centroid_weights, set.sum_indicator_subset_of_eq_zero (function.const (fin (n + 1)) ((card fs : ℝ)⁻¹)) (λ i wi, wi • (s.points i -ᵥ classical.choice add_torsor.nonempty)) fs.subset_univ (λ i, zero_smul ℝ _), set.indicator_apply], congr, funext, congr' 2 end omit V /-- The weights for the circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ def circumcenter_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index n → ℝ | (point_index i) := 0 | circumcenter_index := 1 /-- `circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_circumcenter_weights_with_circumcenter (n : ℕ) : ∑ i, circumcenter_weights_with_circumcenter n i = 1 := begin convert sum_ite_eq' univ circumcenter_index (function.const _ (1 : ℝ)), { ext ⟨j⟩ ; simp [circumcenter_weights_with_circumcenter] }, { simp } end include V /-- The circumcenter of a simplex, in terms of `points_with_circumcenter`. -/ lemma circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (circumcenter_weights_with_circumcenter n) := begin rw ←points_with_circumcenter_eq_circumcenter, symmetry, refine affine_combination_of_eq_one_of_eq_zero _ _ _ (mem_univ _) rfl _, rintros ⟨i⟩ hi hn ; tauto end omit V /-- The weights for the reflection of the circumcenter in an edge of a simplex. This definition is only valid with `i₁ ≠ i₂`. -/ def reflection_circumcenter_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 1)) : points_with_circumcenter_index n → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then 1 else 0 | circumcenter_index := -1 /-- `reflection_circumcenter_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_reflection_circumcenter_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : ∑ i, reflection_circumcenter_weights_with_circumcenter i₁ i₂ i = 1 := begin simp_rw [sum_points_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, sum_ite, sum_const, filter_or, filter_eq'], rw card_union_eq, { simp }, { simpa only [if_true, mem_univ, disjoint_singleton] using h } end include V /-- The reflection of the circumcenter of a simplex in an edge, in terms of `points_with_circumcenter`. -/ lemma reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P n) {i₁ i₂ : fin (n + 1)} (h : i₁ ≠ i₂) : reflection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter = (univ : finset (points_with_circumcenter_index n)).affine_combination s.points_with_circumcenter (reflection_circumcenter_weights_with_circumcenter i₁ i₂) := begin have hc : card ({i₁, i₂} : finset (fin (n + 1))) = 2, { simp [h] }, have h_faces : ↑(orthogonal_projection (affine_span ℝ (s.points '' {i₁, i₂})) s.circumcenter) = ↑(orthogonal_projection (affine_span ℝ (set.range (s.face hc).points)) s.circumcenter), { apply eq_orthogonal_projection_of_eq_subspace, simp }, rw [euclidean_geometry.reflection_apply, h_faces, s.orthogonal_projection_circumcenter hc, circumcenter_eq_centroid, s.face_centroid_eq_centroid hc, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, ←@vsub_eq_zero_iff_eq V, affine_combination_vsub, weighted_vsub_vadd_affine_combination, affine_combination_vsub, weighted_vsub_apply, sum_points_with_circumcenter], simp_rw [pi.sub_apply, pi.add_apply, pi.sub_apply, sub_smul, add_smul, sub_smul, centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter, ite_smul, zero_smul, sub_zero, apply_ite2 (+), add_zero, ←add_smul, hc, zero_sub, neg_smul, sub_self, add_zero], convert sum_const_zero, norm_num end end simplex end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Given a nonempty affine subspace, whose direction is complete, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_complete {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [complete_space s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := begin split, { rintro ⟨c, hcr⟩, rw exists_dist_eq_iff_exists_dist_orthogonal_projection_eq h c at hcr, exact ⟨orthogonal_projection s c, orthogonal_projection_mem _, hcr⟩ }, { exact λ ⟨c, hc, hd⟩, ⟨c, hd⟩ } end /-- Given a nonempty affine subspace, whose direction is finite-dimensional, that contains a set of points, those points are cospherical if and only if they are equidistant from some point in that subspace. -/ lemma cospherical_iff_exists_mem_of_finite_dimensional {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] [finite_dimensional ℝ s.direction] : cospherical ps ↔ ∃ (center ∈ s) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := cospherical_iff_exists_mem_of_complete h /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use r, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumradius_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumradius. -/ lemma circumradius_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumradius. -/ lemma exists_circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ r : ℝ, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumradius = r := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumradius_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumradius. -/ lemma circumradius_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumradius = sx₂.circumradius := begin rcases exists_circumradius_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin rw cospherical_iff_exists_mem_of_finite_dimensional h at hc, rcases hc with ⟨c, hc, r, hcr⟩, use c, intros sx hsxps, have hsx : affine_span ℝ (set.range sx.points) = s, { refine sx.independent.affine_span_eq_of_le_of_card_eq_finrank_add_one (span_points_subset_coe_of_subset_coe (hsxps.trans h)) _, simp [hd] }, have hc : c ∈ affine_span ℝ (set.range sx.points) := hsx.symm ▸ hc, exact (sx.eq_circumcenter_of_dist_eq hc (λ i, hcr (sx.points i) (hsxps (set.mem_range_self i)))).symm end /-- Two n-simplices among cospherical points in an n-dimensional subspace have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical_subset {s : affine_subspace ℝ P} {ps : set P} (h : ps ⊆ s) [nonempty s] {n : ℕ} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical_subset h hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- All n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma exists_circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) : ∃ c : P, ∀ sx : simplex ℝ P n, set.range sx.points ⊆ ps → sx.circumcenter = c := begin haveI : nonempty (⊤ : affine_subspace ℝ P) := set.univ.nonempty, rw [←finrank_top, ←direction_top ℝ V P] at hd, refine exists_circumcenter_eq_of_cospherical_subset _ hd hc, exact set.subset_univ _ end /-- Two n-simplices among cospherical points in n-space have the same circumcenter. -/ lemma circumcenter_eq_of_cospherical {ps : set P} {n : ℕ} [finite_dimensional ℝ V] (hd : finrank ℝ V = n) (hc : cospherical ps) {sx₁ sx₂ : simplex ℝ P n} (hsx₁ : set.range sx₁.points ⊆ ps) (hsx₂ : set.range sx₂.points ⊆ ps) : sx₁.circumcenter = sx₂.circumcenter := begin rcases exists_circumcenter_eq_of_cospherical hd hc with ⟨r, hr⟩, rw [hr sx₁ hsx₁, hr sx₂ hsx₂] end /-- Suppose all distances from `p₁` and `p₂` to the points of a simplex are equal, and that `p₁` and `p₂` lie in the affine span of `p` with the vertices of that simplex. Then `p₁` and `p₂` are equal or reflections of each other in the affine span of the vertices of the simplex. -/ lemma eq_or_eq_reflection_of_dist_eq {n : ℕ} {s : simplex ℝ P n} {p p₁ p₂ : P} {r : ℝ} (hp₁ : p₁ ∈ affine_span ℝ (insert p (set.range s.points))) (hp₂ : p₂ ∈ affine_span ℝ (insert p (set.range s.points))) (h₁ : ∀ i, dist (s.points i) p₁ = r) (h₂ : ∀ i, dist (s.points i) p₂ = r) : p₁ = p₂ ∨ p₁ = reflection (affine_span ℝ (set.range s.points)) p₂ := begin let span_s := affine_span ℝ (set.range s.points), have h₁' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₁, have h₂' := s.orthogonal_projection_eq_circumcenter_of_dist_eq h₂, rw [←affine_span_insert_affine_span, mem_affine_span_insert_iff (orthogonal_projection_mem p)] at hp₁ hp₂, obtain ⟨r₁, p₁o, hp₁o, hp₁⟩ := hp₁, obtain ⟨r₂, p₂o, hp₂o, hp₂⟩ := hp₂, obtain rfl : ↑(orthogonal_projection span_s p₁) = p₁o, { have := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hp₁o, rw ← hp₁ at this, rw this, refl }, rw h₁' at hp₁, obtain rfl : ↑(orthogonal_projection span_s p₂) = p₂o, { have := orthogonal_projection_vadd_smul_vsub_orthogonal_projection _ _ hp₂o, rw ← hp₂ at this, rw this, refl }, rw h₂' at hp₂, have h : s.points 0 ∈ span_s := mem_affine_span ℝ (set.mem_range_self _), have hd₁ : dist p₁ s.circumcenter * dist p₁ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₁ 0, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₁ h], simp only [h₁', dist_comm p₁, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius] }, have hd₂ : dist p₂ s.circumcenter * dist p₂ s.circumcenter = r * r - s.circumradius * s.circumradius, { rw [dist_comm, ←h₂ 0, dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq p₂ h], simp only [h₂', dist_comm p₂, add_sub_cancel', simplex.dist_circumcenter_eq_circumradius] }, rw [←hd₂, hp₁, hp₂, dist_eq_norm_vsub V _ s.circumcenter, dist_eq_norm_vsub V _ s.circumcenter, vadd_vsub, vadd_vsub, ←real_inner_self_eq_norm_sq, ←real_inner_self_eq_norm_sq, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right, real_inner_smul_right, ←mul_assoc, ←mul_assoc] at hd₁, by_cases hp : p = orthogonal_projection span_s p, { rw [hp₁, hp₂, ←hp], simp only [true_or, eq_self_iff_true, smul_zero, vsub_self] }, { have hz : ⟪p -ᵥ orthogonal_projection span_s p, p -ᵥ orthogonal_projection span_s p⟫ ≠ 0, by simpa only [ne.def, vsub_eq_zero_iff_eq, inner_self_eq_zero] using hp, rw [mul_left_inj' hz, mul_self_eq_mul_self_iff] at hd₁, rw [hp₁, hp₂], cases hd₁, { left, rw hd₁ }, { right, rw [hd₁, reflection_vadd_smul_vsub_orthogonal_projection p r₂ s.circumcenter_mem_affine_span, neg_smul] } } end end euclidean_geometry
028c04ba1e056696ae4a606b657d774b282f250e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/perm/cycle/type.lean
afc73b7b01826245528753580efcbea0b78caf59
[ "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
28,045
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.gcd_monoid.multiset import combinatorics.partition import group_theory.perm.cycle.basic import ring_theory.int.basic import tactic.linarith /-! # Cycle Types In this file we define the cycle type of a permutation. ## Main definitions - `σ.cycle_type` where `σ` is a permutation of a `fintype` - `σ.partition` where `σ` is a permutation of a `fintype` ## Main results - `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card` - `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ` - `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same cycle type. - `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of a finite group `G` there exists an element of order `p` in `G`. This is known as Cauchy's theorem. -/ namespace equiv.perm open equiv list multiset variables {α : Type*} [fintype α] section cycle_type variables [decidable_eq α] /-- The cycle type of a permutation -/ def cycle_type (σ : perm α) : multiset ℕ := σ.cycle_factors_finset.1.map (finset.card ∘ support) lemma cycle_type_def (σ : perm α) : σ.cycle_type = σ.cycle_factors_finset.1.map (finset.card ∘ support) := rfl lemma cycle_type_eq' {σ : perm α} (s : finset (perm α)) (h1 : ∀ f : perm α, f ∈ s → f.is_cycle) (h2 : (s : set (perm α)).pairwise disjoint) (h0 : s.noncomm_prod id (h2.imp $ λ _ _, disjoint.commute) = σ) : σ.cycle_type = s.1.map (finset.card ∘ support) := begin rw cycle_type_def, congr, rw cycle_factors_finset_eq_finset, exact ⟨h1, h2, h0⟩ end lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ) (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) : σ.cycle_type = l.map (finset.card ∘ support) := begin have hl : l.nodup := nodup_of_pairwise_disjoint_cycles h1 h2, rw cycle_type_eq' l.to_finset, { simp [list.dedup_eq_self.mpr hl] }, { simpa using h1 }, { simpa [hl] using h0 }, { simpa [list.dedup_eq_self.mpr hl] using h2.forall disjoint.symmetric } end lemma cycle_type_one : (1 : perm α).cycle_type = 0 := cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 := by simp [cycle_type_def, cycle_factors_finset_eq_empty_iff] lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 := by rw [card_eq_zero, cycle_type_eq_zero] lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n := begin simp only [cycle_type_def, ←finset.mem_def, function.comp_app, multiset.mem_map, mem_cycle_factors_finset_iff] at h, obtain ⟨_, ⟨hc, -⟩, rfl⟩ := h, exact hc.two_le_card_support end lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n := two_le_of_mem_cycle_type h lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] := cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ) (pairwise_singleton disjoint σ) lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle := begin rw card_eq_one, simp_rw [cycle_type_def, multiset.map_eq_singleton, ←finset.singleton_val, finset.val_inj, cycle_factors_finset_eq_singleton_iff], split, { rintro ⟨_, _, ⟨h, -⟩, -⟩, exact h }, { intro h, use [σ.support.card, σ], simp [h] } end lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) : (σ * τ).cycle_type = σ.cycle_type + τ.cycle_type := begin rw [cycle_type_def, cycle_type_def, cycle_type_def, h.cycle_factors_finset_mul_eq_union, ←multiset.map_add, finset.union_val, multiset.add_eq_union_iff_disjoint.mpr _], rw [←finset.disjoint_val], exact h.disjoint_cycle_factors_finset end lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type := cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl (λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv]) (λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm, disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm) (λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)]) lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type := begin revert τ, apply cycle_induction_on _ σ, { intro, simp }, { intros σ hσ τ, rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] }, { intros σ τ hd hc hσ hτ π, rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ], intro a, apply (hd (π⁻¹ a)).imp _ _; { intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } } end lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card := cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ (by rw [cycle_type_one, sum_zero, support_one, finset.card_empty]) (λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul]) lemma sign_of_cycle_type' (σ : perm α) : sign σ = (σ.cycle_type.map (λ n, -(-1 : ℤˣ) ^ n)).prod := cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : ℤˣ) ^ n)).prod) σ (by rw [sign_one, cycle_type_one, multiset.map_zero, prod_zero]) (λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod, list.map_singleton, list.prod_singleton]) (λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, multiset.map_add, prod_add]) lemma sign_of_cycle_type (f : perm α) : sign f = (-1 : ℤˣ)^(f.cycle_type.sum + f.cycle_type.card) := cycle_induction_on (λ f : perm α, sign f = (-1 : ℤˣ)^(f.cycle_type.sum + f.cycle_type.card)) f ( -- base_one by rw [equiv.perm.cycle_type_one, sign_one, multiset.sum_zero, multiset.card_zero, pow_zero] ) ( -- base_cycles λ f hf, by rw [equiv.perm.is_cycle.cycle_type hf, hf.sign, coe_sum, list.sum_cons, sum_nil, add_zero, coe_card, length_singleton, pow_add, pow_one, mul_comm, neg_mul, one_mul] ) ( -- induction_disjoint λ f g hfg hf Pf Pg, by rw [equiv.perm.disjoint.cycle_type hfg, multiset.sum_add, multiset.card_add,← add_assoc, add_comm f.cycle_type.sum g.cycle_type.sum, add_assoc g.cycle_type.sum _ _, add_comm g.cycle_type.sum _, add_assoc, pow_add, ← Pf, ← Pg, equiv.perm.sign_mul]) lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ := cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ (by rw [cycle_type_one, lcm_zero, order_of_one]) (λ σ hσ, by rw [hσ.cycle_type, coe_singleton, lcm_singleton, order_of_is_cycle hσ, normalize_eq]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, lcm_eq_nat_lcm, hστ.order_of, hσ, hτ]) lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ := begin rw ← lcm_cycle_type, exact dvd_lcm h, end lemma order_of_cycle_of_dvd_order_of (f : perm α) (x : α) : order_of (cycle_of f x) ∣ order_of f := begin by_cases hx : f x = x, { rw ←cycle_of_eq_one_iff at hx, simp [hx] }, { refine dvd_of_mem_cycle_type _, rw [cycle_type, multiset.mem_map], refine ⟨f.cycle_of x, _, _⟩, { rwa [←finset.mem_def, cycle_of_mem_cycle_factors_finset_iff, mem_support] }, { simp [order_of_is_cycle (is_cycle_cycle_of _ hx)] } } end lemma two_dvd_card_support {σ : perm α} (hσ : σ ^ 2 = 1) : 2 ∣ σ.support.card := (congr_arg (has_dvd.dvd 2) σ.sum_cycle_type).mp (multiset.dvd_sum (λ n hn, by rw le_antisymm (nat.le_of_dvd zero_lt_two $ (dvd_of_mem_cycle_type hn).trans $ order_of_dvd_of_pow_eq_one hσ) (two_le_of_mem_cycle_type hn))) lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) : ∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) := begin rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp (hσ.eq_one_or_self_of_dvd n (dvd_of_mem_cycle_type hn)) (one_lt_of_mem_cycle_type hn).ne'), use σ.cycle_type.card - 1, rw tsub_add_cancel_of_le, rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero], intro H, rw [H, order_of_one] at hσ, exact hσ.ne_one rfl, end lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime) (h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle := begin obtain ⟨n, hn⟩ := cycle_type_prime_order h1, rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right (order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, le_zero_iff] at h2, rw [←card_cycle_type_eq_one, hn, card_repeat, h2], end lemma cycle_type_le_of_mem_cycle_factors_finset {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : f.cycle_type ≤ g.cycle_type := begin rw mem_cycle_factors_finset_iff at hf, rw [cycle_type_def, cycle_type_def, hf.left.cycle_factors_finset_eq_singleton], refine map_le_map _, simpa [←finset.mem_def, mem_cycle_factors_finset_iff] using hf end lemma cycle_type_mul_mem_cycle_factors_finset_eq_sub {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : (g * f⁻¹).cycle_type = g.cycle_type - f.cycle_type := begin suffices : (g * f⁻¹).cycle_type + f.cycle_type = g.cycle_type - f.cycle_type + f.cycle_type, { rw tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf) at this, simp [←this] }, simp [←(disjoint_mul_inv_of_mem_cycle_factors_finset hf).cycle_type, tsub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf)] end theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ := begin revert τ, apply cycle_induction_on _ σ, { intros τ h, rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h, rw h }, { intros σ hσ τ hστ, have hτ := card_cycle_type_eq_one.2 hσ, rw [hστ, card_cycle_type_eq_one] at hτ, apply hσ.is_conj hτ, rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ, simp only [and_true, eq_self_iff_true] at hστ, exact hστ }, { intros σ τ hστ hσ h1 h2 π hπ, rw [hστ.cycle_type] at hπ, { have h : σ.support.card ∈ map (finset.card ∘ perm.support) π.cycle_factors_finset.val, { simp [←cycle_type_def, ←hπ, hσ.cycle_type] }, obtain ⟨σ', hσ'l, hσ'⟩ := multiset.mem_map.mp h, have key : is_conj (σ' * (π * σ'⁻¹)) π, { rw is_conj_iff, use σ'⁻¹, simp [mul_assoc] }, refine is_conj.trans _ key, have hs : σ.cycle_type = σ'.cycle_type, { rw [←finset.mem_def, mem_cycle_factors_finset_iff] at hσ'l, rw [hσ.cycle_type, ←hσ', hσ'l.left.cycle_type] }, refine hστ.is_conj_mul (h1 hs) (h2 _) _, { rw [cycle_type_mul_mem_cycle_factors_finset_eq_sub, ←hπ, add_comm, hs, add_tsub_cancel_right], rwa finset.mem_def }, { exact (disjoint_mul_inv_of_mem_cycle_factors_finset hσ'l).symm } } } end theorem is_conj_iff_cycle_type_eq {σ τ : perm α} : is_conj σ τ ↔ σ.cycle_type = τ.cycle_type := ⟨λ h, begin obtain ⟨π, rfl⟩ := is_conj_iff.1 h, rw cycle_type_conj, end, is_conj_of_cycle_type_eq⟩ @[simp] lemma cycle_type_extend_domain {β : Type*} [fintype β] [decidable_eq β] {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} : cycle_type (g.extend_domain f) = cycle_type g := begin apply cycle_induction_on _ g, { rw [extend_domain_one, cycle_type_one, cycle_type_one] }, { intros σ hσ, rw [(hσ.extend_domain f).cycle_type, hσ.cycle_type, card_support_extend_domain] }, { intros σ τ hd hc hσ hτ, rw [hd.cycle_type, ← extend_domain_mul, (hd.extend_domain f).cycle_type, hσ, hτ] } end lemma cycle_type_of_subtype {p : α → Prop} [decidable_pred p] {g : perm (subtype p)}: cycle_type (g.of_subtype) = cycle_type g := cycle_type_extend_domain (equiv.refl (subtype p)) lemma mem_cycle_type_iff {n : ℕ} {σ : perm α} : n ∈ cycle_type σ ↔ ∃ c τ : perm α, σ = c * τ ∧ disjoint c τ ∧ is_cycle c ∧ c.support.card = n := begin split, { intro h, obtain ⟨l, rfl, hlc, hld⟩ := trunc_cycle_factors σ, rw cycle_type_eq _ rfl hlc hld at h, obtain ⟨c, cl, rfl⟩ := list.exists_of_mem_map h, rw (list.perm_cons_erase cl).pairwise_iff (λ _ _ hd, _) at hld, swap, { exact hd.symm }, refine ⟨c, (l.erase c).prod, _, _, hlc _ cl, rfl⟩, { rw [← list.prod_cons, (list.perm_cons_erase cl).symm.prod_eq' (hld.imp (λ _ _, disjoint.commute))] }, { exact disjoint_prod_right _ (λ g, list.rel_of_pairwise_cons hld) } }, { rintros ⟨c, t, rfl, hd, hc, rfl⟩, simp [hd.cycle_type, hc.cycle_type] } end lemma le_card_support_of_mem_cycle_type {n : ℕ} {σ : perm α} (h : n ∈ cycle_type σ) : n ≤ σ.support.card := (le_sum_of_mem h).trans (le_of_eq σ.sum_cycle_type) lemma cycle_type_of_card_le_mem_cycle_type_add_two {n : ℕ} {g : perm α} (hn2 : fintype.card α < n + 2) (hng : n ∈ g.cycle_type) : g.cycle_type = {n} := begin obtain ⟨c, g', rfl, hd, hc, rfl⟩ := mem_cycle_type_iff.1 hng, by_cases g'1 : g' = 1, { rw [hd.cycle_type, hc.cycle_type, coe_singleton, g'1, cycle_type_one, add_zero] }, contrapose! hn2, apply le_trans _ (c * g').support.card_le_univ, rw [hd.card_support_mul], exact add_le_add_left (two_le_card_support_of_ne_one g'1) _, end end cycle_type lemma card_compl_support_modeq [decidable_eq α] {p n : ℕ} [hp : fact p.prime] {σ : perm α} (hσ : σ ^ p ^ n = 1) : σ.supportᶜ.card ≡ fintype.card α [MOD p] := begin rw [nat.modeq_iff_dvd' σ.supportᶜ.card_le_univ, ←finset.card_compl, compl_compl], refine (congr_arg _ σ.sum_cycle_type).mp (multiset.dvd_sum (λ k hk, _)), obtain ⟨m, -, hm⟩ := (nat.dvd_prime_pow hp.out).mp (order_of_dvd_of_pow_eq_one hσ), obtain ⟨l, -, rfl⟩ := (nat.dvd_prime_pow hp.out).mp ((congr_arg _ hm).mp (dvd_of_mem_cycle_type hk)), exact dvd_pow_self _ (λ h, (one_lt_of_mem_cycle_type hk).ne $ by rw [h, pow_zero]), end lemma exists_fixed_point_of_prime {p n : ℕ} [hp : fact p.prime] (hα : ¬ p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) : ∃ a : α, σ a = a := begin classical, contrapose! hα, simp_rw ← mem_support at hα, exact nat.modeq_zero_iff_dvd.mp ((congr_arg _ (finset.card_eq_zero.mpr (compl_eq_bot.mpr (finset.eq_univ_iff_forall.mpr hα)))).mp (card_compl_support_modeq hσ).symm), end lemma exists_fixed_point_of_prime' {p n : ℕ} [hp : fact p.prime] (hα : p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) {a : α} (ha : σ a = a) : ∃ b : α, σ b = b ∧ b ≠ a := begin classical, have h : ∀ b : α, b ∈ σ.supportᶜ ↔ σ b = b := λ b, by rw [finset.mem_compl, mem_support, not_not], obtain ⟨b, hb1, hb2⟩ := finset.exists_ne_of_one_lt_card (lt_of_lt_of_le hp.out.one_lt (nat.le_of_dvd (finset.card_pos.mpr ⟨a, (h a).mpr ha⟩) (nat.modeq_zero_iff_dvd.mp ((card_compl_support_modeq hσ).trans (nat.modeq_zero_iff_dvd.mpr hα))))) a, exact ⟨b, (h b).mp hb1, hb2⟩, end lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime) (h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle := begin classical, exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2), end lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime) (h2 : order_of σ = fintype.card α) : σ.is_cycle := is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1) begin classical, rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)], exact one_lt_two, end section cauchy variables (G : Type*) [group G] (n : ℕ) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one : set (vector G n) := {v | v.to_list.prod = 1} namespace vectors_prod_eq_one lemma mem_iff {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma zero_eq : vectors_prod_eq_one G 0 = {vector.nil} := set.eq_singleton_iff_unique_mem.mpr ⟨eq.refl (1 : G), λ v hv, v.eq_nil⟩ lemma one_eq : vectors_prod_eq_one G 1 = {vector.nil.cons 1} := begin simp_rw [set.eq_singleton_iff_unique_mem, mem_iff, vector.to_list_singleton, list.prod_singleton, vector.head_cons], exact ⟨rfl, λ v hv, v.cons_head_tail.symm.trans (congr_arg2 vector.cons hv v.tail.eq_nil)⟩, end instance zero_unique : unique (vectors_prod_eq_one G 0) := by { rw zero_eq, exact set.unique_singleton vector.nil } instance one_unique : unique (vectors_prod_eq_one G 1) := by { rw one_eq, exact set.unique_singleton (vector.nil.cons 1) } /-- Given a vector `v` of length `n`, make a vector of length `n + 1` whose product is `1`, by appending the inverse of the product of `v`. -/ @[simps] def vector_equiv : vector G n ≃ vectors_prod_eq_one G (n + 1) := { to_fun := λ v, ⟨v.to_list.prod⁻¹ ::ᵥ v, by rw [mem_iff, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩, inv_fun := λ v, v.1.tail, left_inv := λ v, v.tail_cons v.to_list.prod⁻¹, right_inv := λ v, subtype.ext ((congr_arg2 vector.cons (eq_inv_of_mul_eq_one_left (by { rw [←list.prod_cons, ←vector.to_list_cons, v.1.cons_head_tail], exact v.2 })).symm rfl).trans v.1.cons_head_tail) } /-- Given a vector `v` of length `n` whose product is 1, make a vector of length `n - 1`, by deleting the last entry of `v`. -/ def equiv_vector : vectors_prod_eq_one G n ≃ vector G (n - 1) := ((vector_equiv G (n - 1)).trans (if hn : n = 0 then (show vectors_prod_eq_one G (n - 1 + 1) ≃ vectors_prod_eq_one G n, by { rw hn, apply equiv_of_unique }) else by rw tsub_add_cancel_of_le (nat.pos_of_ne_zero hn).nat_succ_le)).symm instance [fintype G] : fintype (vectors_prod_eq_one G n) := fintype.of_equiv (vector G (n - 1)) (equiv_vector G n).symm lemma card [fintype G] : fintype.card (vectors_prod_eq_one G n) = fintype.card G ^ (n - 1) := (fintype.card_congr (equiv_vector G n)).trans (card_vector (n - 1)) variables {G n} {g : G} (v : vectors_prod_eq_one G n) (j k : ℕ) /-- Rotate a vector whose product is 1. -/ def rotate : vectors_prod_eq_one G n := ⟨⟨_, (v.1.1.length_rotate k).trans v.1.2⟩, list.prod_rotate_eq_one_of_prod_eq_one v.2 k⟩ lemma rotate_zero : rotate v 0 = v := subtype.ext (subtype.ext v.1.1.rotate_zero) lemma rotate_rotate : rotate (rotate v j) k = rotate v (j + k) := subtype.ext (subtype.ext (v.1.1.rotate_rotate j k)) lemma rotate_length : rotate v n = v := subtype.ext (subtype.ext ((congr_arg _ v.1.2.symm).trans v.1.1.rotate_length)) end vectors_prod_eq_one /-- For every prime `p` dividing the order of a finite group `G` there exists an element of order `p` in `G`. This is known as Cauchy's theorem. -/ lemma _root_.exists_prime_order_of_dvd_card {G : Type*} [group G] [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ fintype.card G) : ∃ x : G, order_of x = p := begin have hp' : p - 1 ≠ 0 := mt tsub_eq_zero_iff_le.mp (not_le_of_lt hp.out.one_lt), have Scard := calc p ∣ fintype.card G ^ (p - 1) : hdvd.trans (dvd_pow (dvd_refl _) hp') ... = fintype.card (vectors_prod_eq_one G p) : (vectors_prod_eq_one.card G p).symm, let f : ℕ → vectors_prod_eq_one G p → vectors_prod_eq_one G p := λ k v, vectors_prod_eq_one.rotate v k, have hf1 : ∀ v, f 0 v = v := vectors_prod_eq_one.rotate_zero, have hf2 : ∀ j k v, f k (f j v) = f (j + k) v := λ j k v, vectors_prod_eq_one.rotate_rotate v j k, have hf3 : ∀ v, f p v = v := vectors_prod_eq_one.rotate_length, let σ := equiv.mk (f 1) (f (p - 1)) (λ s, by rw [hf2, add_tsub_cancel_of_le hp.out.one_lt.le, hf3]) (λ s, by rw [hf2, tsub_add_cancel_of_le hp.out.one_lt.le, hf3]), have hσ : ∀ k v, (σ ^ k) v = f k v := λ k v, nat.rec (hf1 v).symm (λ k hk, eq.trans (by exact congr_arg σ hk) (hf2 k 1 v)) k, replace hσ : σ ^ (p ^ 1) = 1 := perm.ext (λ v, by rw [pow_one, hσ, hf3, one_apply]), let v₀ : vectors_prod_eq_one G p := ⟨vector.repeat 1 p, (list.prod_repeat 1 p).trans (one_pow p)⟩, have hv₀ : σ v₀ = v₀ := subtype.ext (subtype.ext (list.rotate_repeat (1 : G) p 1)), obtain ⟨v, hv1, hv2⟩ := exists_fixed_point_of_prime' Scard hσ hv₀, refine exists_imp_exists (λ g hg, order_of_eq_prime _ (λ hg', hv2 _)) (list.rotate_one_eq_self_iff_eq_repeat.mp (subtype.ext_iff.mp (subtype.ext_iff.mp hv1))), { rw [←list.prod_repeat, ←v.1.2, ←hg, (show v.val.val.prod = 1, from v.2)] }, { rw [subtype.ext_iff_val, subtype.ext_iff_val, hg, hg', v.1.2], refl }, end /-- For every prime `p` dividing the order of a finite additive group `G` there exists an element of order `p` in `G`. This is the additive version of Cauchy's theorem. -/ lemma _root_.exists_prime_add_order_of_dvd_card {G : Type*} [add_group G] [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ fintype.card G) : ∃ x : G, add_order_of x = p := @exists_prime_order_of_dvd_card (multiplicative G) _ _ _ _ hdvd attribute [to_additive exists_prime_add_order_of_dvd_card] exists_prime_order_of_dvd_card end cauchy lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)} [d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime) (h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) : H = ⊤ := begin haveI : fact (fintype.card α).prime := ⟨h0⟩, obtain ⟨σ, hσ⟩ := exists_prime_order_of_dvd_card (fintype.card α) h1, have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ, have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1, have hσ3 : (σ : perm α).support = ⊤ := finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1), have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3, rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff], exact ⟨subtype.mem σ, h2⟩, end section partition variables [decidable_eq α] /-- The partition corresponding to a permutation -/ def partition (σ : perm α) : (fintype.card α).partition := { parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card), parts_pos := λ n hn, begin cases mem_add.mp hn with hn hn, { exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) }, { exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) }, end, parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_one, add_tsub_cancel_of_le σ.support.card_le_univ] } lemma parts_partition {σ : perm α} : σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl lemma filter_parts_partition_eq_cycle_type {σ : perm α} : (partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type := begin rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type), multiset.filter_eq_nil.2 (λ a h, _), add_zero], rw multiset.eq_of_mem_repeat h, dec_trivial end lemma partition_eq_of_is_conj {σ τ : perm α} : is_conj σ τ ↔ σ.partition = τ.partition := begin rw [is_conj_iff_cycle_type_eq], refine ⟨λ h, _, λ h, _⟩, { rw [nat.partition.ext_iff, parts_partition, parts_partition, ← sum_cycle_type, ← sum_cycle_type, h] }, { rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] } end end partition /-! ### 3-cycles -/ /-- A three-cycle is a cycle of length 3. -/ def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3} namespace is_three_cycle variables [decidable_eq α] {σ : perm α} lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 := by rw [←sum_cycle_type, h.cycle_type, multiset.sum_singleton] lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle := begin refine ⟨λ h, _, is_three_cycle.card_support⟩, by_cases h0 : σ.cycle_type = 0, { rw [←sum_cycle_type, h0, sum_zero] at h, exact (ne_of_lt zero_lt_three h).elim }, obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0, by_cases h1 : σ.cycle_type.erase n = 0, { rw [←sum_cycle_type, ←cons_erase hn, h1, cons_zero, multiset.sum_singleton] at h, rw [is_three_cycle, ←cons_erase hn, h1, h, ←cons_zero] }, obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1, rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h, -- TODO: linarith [...] should solve this directly have : ∀ {k}, 2 ≤ m → 2 ≤ n → n + (m + k) = 3 → false, { intros, linarith }, cases this (two_le_of_mem_cycle_type (mem_of_mem_erase hm)) (two_le_of_mem_cycle_type hn) h, end lemma is_cycle (h : is_three_cycle σ) : is_cycle σ := by rw [←card_cycle_type_eq_one, h.cycle_type, card_singleton] lemma sign (h : is_three_cycle σ) : sign σ = 1 := begin rw [equiv.perm.sign_of_cycle_type, h.cycle_type], refl, end lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) := by rwa [is_three_cycle, cycle_type_inv] @[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f := ⟨by { rw ← inv_inv f, apply inv }, inv⟩ lemma order_of {g : perm α} (ht : is_three_cycle g) : order_of g = 3 := by rw [←lcm_cycle_type, ht.cycle_type, multiset.lcm_singleton, normalize_eq] lemma is_three_cycle_sq {g : perm α} (ht : is_three_cycle g) : is_three_cycle (g * g) := begin rw [←pow_two, ←card_support_eq_three_iff, support_pow_coprime, ht.card_support], rw [ht.order_of, nat.coprime_iff_gcd_eq_one], norm_num, end end is_three_cycle section variable [decidable_eq α] lemma is_three_cycle_swap_mul_swap_same {a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) : is_three_cycle (swap a b * swap a c) := begin suffices h : support (swap a b * swap a c) = {a, b, c}, { rw [←card_support_eq_three_iff, h], simp [ab, ac, bc] }, apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _), { simp [ab, ac, bc] }, { simp only [finset.mem_insert, finset.mem_singleton] at hx, rw mem_support, simp only [perm.coe_mul, function.comp_app, ne.def], obtain rfl | rfl | rfl := hx, { rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm], exact ac.symm }, { rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right], exact ab }, { rw [swap_apply_right, swap_apply_left], exact bc } } end open subgroup lemma swap_mul_swap_same_mem_closure_three_cycles {a b c : α} (ab : a ≠ b) (ac : a ≠ c) : (swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } := begin by_cases bc : b = c, { subst bc, simp [one_mem] }, exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc) end lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α} (hσ : is_swap σ) (hτ : is_swap τ) : σ * τ ∈ closure {σ : perm α | is_three_cycle σ } := begin obtain ⟨a, b, ab, rfl⟩ := hσ, obtain ⟨c, d, cd, rfl⟩ := hτ, by_cases ac : a = c, { subst ac, exact swap_mul_swap_same_mem_closure_three_cycles ab cd }, have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d), { simp [swap_comm c a, mul_assoc] }, rw h', exact mul_mem (swap_mul_swap_same_mem_closure_three_cycles ab ac) (swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd), end end end equiv.perm
99c626400f586229e068578d13508e7193792386
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/algebra/big_operators/basic.lean
f9530ed6c022a2133d15885e348aecd63951f239
[ "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
51,283
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 data.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : (∏ x in s, f x) = s.fold (*) 1 f := rfl end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [semiring β] [semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [semiring β] [semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s @[to_additive] lemma monoid_hom.coe_prod [monoid β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ @[simp, to_additive] lemma monoid_hom.finset_prod_apply [monoid β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : (∑ x in s, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bUnion_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bUnion s t), from (disjoint_bUnion_right _ _ _).mpr this, by simp only [bUnion_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bUnion, prod_bUnion], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Πa, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λa, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Πa, finset (σ a)) (f : Πa, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = ∏ x in s.filter (λc', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : (∏ x in s, g (f x)) = g (∏ x in s, f x) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λx, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λx, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) : (∑ x in range (n + 1), f x) = f n + (∑ x in range n, f x) := by rw [range_succ, sum_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (∏ x in range (n + 1), f x) = f n * (∏ x in range n, f x) := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[to_additive] lemma prod_range_zero (f : ℕ → β) : (∏ k in range 0, f k) = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (∏ k in range 1, f k) = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (∑ k in range 1, f k) = f 0 := @prod_range_one (multiplicative δ) _ f attribute [to_additive finset.sum_range_one] prod_range_one open multiset lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, intros a s ih, simp only [prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := begin classical, induction s using finset.induction with x hx s hs, simpa, rw finset.prod_insert, swap, assumption, apply p_mul, apply p_s, simp, apply hs, intros a ha, apply p_s, simp [ha], end /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub (additive M) _ f n @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by simpa only [← div_eq_mul_inv] using @sum_range_sub' (additive M) _ f n /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b | 0 := rfl | (n+1) := by simp lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : (∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) -- `to_additive` fails on this lemma, so we prove it manually below lemma prod_flip {n : ℕ} (f : ℕ → β) : (∏ r in range (n + 1), f (n - r)) = (∏ k in range (n + 1), f k) := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n), mul_comm], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : f i * (∏ x in s \ {i}, f x) = ∏ x in s, f x := by { convert s.prod_inter_mul_prod_diff {i} f, simp [h] } /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum. -/ lemma eq_of_card_le_one_of_sum_eq [add_comm_monoid γ] {s : finset α} (hc : s.card ≤ 1) {f : α → γ} {b : γ} (h : ∑ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw sum_singleton at h, exact h } end attribute [to_additive eq_of_card_le_one_of_sum_eq] eq_of_card_le_one_of_prod_eq /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, apply prod_subset sdiff_subset_self, intros x hx hnx, rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [← mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n •ℕ (f x)) = n •ℕ ((∑ x in s, f x)) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card •ℕ b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] @[norm_cast] lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s @[norm_cast] lemma sum_int_cast [add_comm_group β] [has_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := (int.cast_add_hom β).map_sum f s lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card •ℕ (f b) := @prod_comp _ (multiplicative β) _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (∑ i in range (n + 1), f i) = (∑ i in range n, f (i + 1)) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) : (∑ i in range (n + 1), f (n - i)) = (∑ i in range (n + 1), f i) := @prod_flip (multiplicative β) _ _ _ attribute [to_additive] prod_flip section opposite open opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵒᵖ).symm.map_sum _ _ end opposite section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := (s.sum_hom (gsmul z)).symm @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := by simpa only [sub_eq_add_neg] using sum_add_distrib.trans (congr_arg _ sum_neg_distrib) section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by haveI := classical.dec_eq α; calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel' h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero end finset namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_smul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a •ℕ (a ::ₘ 0)) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s •ℕ (b ::ₘ 0)), { rw [singleton_coe, count_smul, ← singleton_coe, count_singleton, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_smul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_smul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) : ∃ (u : multiset α), s = k •ℕ u := begin use ∑ a in s.to_finset, (s.count a / k) •ℕ (a ::ₘ 0), have h₂ : ∑ (x : α) in s.to_finset, k •ℕ (count x s / k •ℕ (x ::ₘ 0)) = ∑ (x : α) in s.to_finset, count x s •ℕ (x ::ₘ 0), { refine congr_arg s.to_finset.sum _, apply funext, intro x, rw [← mul_nsmul, nat.mul_div_cancel' (h x)] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_smul_eq] end end multiset @[simp, norm_cast] lemma nat.coe_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.coe_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _
1d3a7f5f817b485c91b515d8e6d68cfba8faa3c4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/nontriviality.lean
a039590b5a7248bf604f18a163966761f7ffd19c
[ "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,031
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.nontrivial /-! # The `nontriviality` tactic. -/ namespace tactic /-- Tries to generate a `nontrivial α` instance by performing case analysis on `subsingleton_or_nontrivial α`, attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute, including `subsingleton.le` and `eq_iff_true_of_subsingleton`. -/ meta def nontriviality_by_elim (α : expr) (lems : interactive.parse simp_arg_list) : tactic unit := do alternative ← to_expr ``(subsingleton_or_nontrivial %%α), n ← get_unused_name "_inst", tactic.cases alternative [n, n], (solve1 $ do reset_instance_cache, apply_instance <|> interactive.simp none none ff lems [`nontriviality] (interactive.loc.ns [none])) <|> fail format!"Could not prove goal assuming `subsingleton {α}`", reset_instance_cache /-- Tries to generate a `nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt` and local hypotheses. -/ meta def nontriviality_by_assumption (α : expr) : tactic unit := do n ← get_unused_name "_inst", to_expr ``(nontrivial %%α) >>= assert n, apply_instance <|> `[solve_by_elim [nontrivial_of_ne, nontrivial_of_lt]], reset_instance_cache end tactic namespace tactic.interactive open tactic setup_tactic_parser /-- Attempts to generate a `nontrivial α` hypothesis. The tactic first looks for an instance using `apply_instance`. If the goal is an (in)equality, the type `α` is inferred from the goal. Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`. The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses, and use these to derive the `nontrivial` instance directly. Otherwise, it will perform a case split on `subsingleton α ∨ nontrivial α`, and attempt to discharge the `subsingleton` goal using `simp [lemmas] with nontriviality`, where `[lemmas]` is a list of additional `simp` lemmas that can be passed to `nontriviality` using the syntax `nontriviality α using [lemmas]`. ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. assumption, end ``` ``` example {R : Type} [comm_ring R] {r s : R} : r * s = s * r := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. apply mul_comm, end ``` ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 := begin nontriviality R, -- there is now a `nontrivial R` hypothesis available. dec_trivial end ``` ``` def myeq {α : Type} (a b : α) : Prop := a = b example {α : Type} (a b : α) (h : a = b) : myeq a b := begin success_if_fail { nontriviality α }, -- Fails nontriviality α using [myeq], -- There is now a `nontrivial α` hypothesis available assumption end ``` -/ meta def nontriviality (t : parse texpr?) (lems : parse (tk "using" *> simp_arg_list <|> pure [])) : tactic unit := do α ← match t with | some α := to_expr α | none := (do t ← mk_mvar, e ← to_expr ``(@eq %%t _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@has_le.le %%t _ _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@ne %%t _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@has_lt.lt %%t _ _ _), target >>= unify e, return t) <|> fail "The goal is not an (in)equality, so you'll need to specify the desired `nontrivial α` instance by invoking `nontriviality α`." end, nontriviality_by_assumption α <|> nontriviality_by_elim α lems add_tactic_doc { name := "nontriviality", category := doc_category.tactic, decl_names := [`tactic.interactive.nontriviality], tags := ["logic", "type class"] } end tactic.interactive
09be59e32f8ee8bf6014cee42a9a4760db056255
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/induction2.lean
b8f4136e6f0857d4e0910b795a20ea7bba4ca1ac
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
727
lean
import macros -- loads the λ, λ, obtain macros using Nat -- using the Nat namespace (it allows us to suppress the Nat:: prefix) axiom Induction : ∀ P : Nat → Bool, P 0 → (∀ n, P n → P (n + 1)) → ∀ n, P n. -- induction on n theorem Comm1 : ∀ n m, n + m = m + n := Induction _ -- I use a placeholder because I do not want to write the P (λ m, -- Base case calc 0 + m = m : add_zerol m ... = m + 0 : symm (add_zeror m)) (λ n iH m, -- Inductive case calc n + 1 + m = (n + m) + 1 : add_succl n m ... = (m + n) + 1 : { iH } -- Error is here ... = m + (n + 1) : symm (add_succr m n))
4a058e90f7f031a3196e4ac46038f1a925d330a4
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/logic/function/basic.lean
69a318a5d230c5406c1225293b8d4801baa4f945
[ "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
28,068
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import logic.basic import data.option.defs /-! # Miscellaneous function constructions and lemmas -/ universes u v w namespace function section variables {α β γ : Sort*} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `function.eval x : (Π x, β x) → β x`. -/ @[reducible] def eval {β : α → Sort*} (x : α) (f : Π x, β x) : β x := f x @[simp] lemma eval_apply {β : α → Sort*} (x : α) (f : Π x, β x) : eval x f = f x := rfl lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma const_def {y : β} : (λ x : α, y) = const α y := rfl @[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl @[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl lemma id_def : @id α = λ x, x := rfl lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext protected lemma bijective.injective {f : α → β} (hf : bijective f) : injective f := hf.1 protected lemma bijective.surjective {f : α → β} (hf : bijective f) : surjective f := hf.2 theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (assume h, hf h) lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt $ congr_arg f, hf.ne⟩ lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α := λ a b, decidable_of_iff _ I.eq_iff lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g := λ x y h, I $ show f (g x) = f (g y), from congr_arg f h lemma injective.of_comp_iff {f : α → β} (hf : injective f) (g : γ → α) : injective (f ∘ g) ↔ injective g := ⟨injective.of_comp, hf.comp⟩ lemma injective.of_comp_iff' (f : α → β) {g : γ → α} (hg : bijective g) : injective (f ∘ g) ↔ injective f := ⟨ λ h x y, let ⟨x', hx⟩ := hg.surjective x, ⟨y', hy⟩ := hg.surjective y in hx ▸ hy ▸ λ hf, h hf ▸ rfl, λ h, h.comp hg.injective⟩ lemma injective_of_subsingleton [subsingleton α] (f : α → β) : injective f := λ a b ab, subsingleton.elim _ _ lemma injective.dite (p : α → Prop) [decidable_pred p] {f : {a : α // p a} → β} {f' : {a : α // ¬ p a} → β} (hf : injective f) (hf' : injective f') (im_disj : ∀ {x x' : α} {hx : p x} {hx' : ¬ p x'}, f ⟨x, hx⟩ ≠ f' ⟨x', hx'⟩) : function.injective (λ x, if h : p x then f ⟨x, h⟩ else f' ⟨x, h⟩) := λ x₁ x₂ h, begin dsimp only at h, by_cases h₁ : p x₁; by_cases h₂ : p x₂, { rw [dif_pos h₁, dif_pos h₂] at h, injection (hf h), }, { rw [dif_pos h₁, dif_neg h₂] at h, exact (im_disj h).elim, }, { rw [dif_neg h₁, dif_pos h₂] at h, exact (im_disj h.symm).elim, }, { rw [dif_neg h₁, dif_neg h₂] at h, injection (hf' h), }, end lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f := λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩ lemma surjective.of_comp_iff (f : α → β) {g : γ → α} (hg : surjective g) : surjective (f ∘ g) ↔ surjective f := ⟨surjective.of_comp, λ h, h.comp hg⟩ lemma surjective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : surjective (f ∘ g) ↔ surjective g := ⟨λ h x, let ⟨x', hx'⟩ := h (f x) in ⟨x', hf.injective hx'⟩, hf.surjective.comp⟩ instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨λ h x, h (f x), λ h y, let ⟨x, hx⟩ := hf y in hx ▸ h x⟩ theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans $ forall_congr $ λ x, hf.forall theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans $ forall_congr $ λ x, hf.forall₂ theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨λ ⟨y, hy⟩, let ⟨x, hx⟩ := hf y in ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩, ⟨f x, hx⟩⟩ theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans $ exists_congr $ λ x, hf.exists theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans $ exists_congr $ λ x, hf.exists₂ lemma bijective_iff_exists_unique (f : α → β) : bijective f ↔ ∀ b : β, ∃! (a : α), f a = b := ⟨ λ hf b, let ⟨a, ha⟩ := hf.surjective b in ⟨a, ha, λ a' ha', hf.injective (ha'.trans ha.symm)⟩, λ he, ⟨ λ a a' h, unique_of_exists_unique (he (f a')) h rfl, λ b, exists_of_exists_unique (he b) ⟩⟩ /-- Shorthand for using projection notation with `function.bijective_iff_exists_unique`. -/ lemma bijective.exists_unique {f : α → β} (hf : bijective f) (b : β) : ∃! (a : α), f a = b := (bijective_iff_exists_unique f).mp hf b lemma bijective.of_comp_iff (f : α → β) {g : γ → α} (hg : bijective g) : bijective (f ∘ g) ↔ bijective f := and_congr (injective.of_comp_iff' _ hg) (surjective.of_comp_iff _ hg.surjective) lemma bijective.of_comp_iff' {f : α → β} (hf : bijective f) (g : γ → α) : function.bijective (f ∘ g) ↔ function.bijective g := and_congr (injective.of_comp_iff hf.injective _) (surjective.of_comp_iff' hf _) /-- **Cantor's diagonal argument** implies that there are no surjective functions from `α` to `set α`. -/ theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) /-- **Cantor's diagonal argument** implies that there are no injective functions from `set α` to `α`. -/ theorem cantor_injective {α : Type*} (f : (set α) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩) /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id := ⟨left_inverse.comp_eq_id, congr_fun⟩ theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id := ⟨right_inverse.comp_eq_id, congr_fun⟩ theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g := h theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g := h theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f := h.right_inverse.surjective theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) : injective f := h.left_inverse.injective theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ := calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id] ... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id] local attribute [instance, priority 10] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} include n local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ (x ∈ s) (y ∈ s), f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n := by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := (left_inverse_inv_fun hf).surjective lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf end inv_fun section inv_fun variables {α : Type u} [i : nonempty α] {β : Sort v} {f : α → β} include i lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, has_left_inverse.injective⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, has_right_inverse.surjective⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := (right_inverse_surj_inv h).injective lemma surjective_to_subsingleton [na : nonempty α] [subsingleton β] (f : α → β) : surjective f := λ y, let ⟨a⟩ := na in ⟨a, subsingleton.elim _ _⟩ end surj_inv section update variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α'] /-- Replacing the value of a function at a given point by a given value. -/ def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a /-- On non-dependent functions, `function.update` can be expressed as an `ite` -/ lemma update_apply {β : Sort*} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = if a = a' then b else f a := begin dunfold update, congr, funext, rw eq_rec_constant, end @[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v := dif_pos rfl lemma surjective_eval {α : Sort u} {β : α → Sort v} [h : Π a, nonempty (β a)] (a : α) : surjective (eval a : (Π a, β a) → β a) := λ b, ⟨@update _ _ (classical.dec_eq α) (λ a, (h a).some) a b, @update_same _ _ (classical.dec_eq α) _ _ _⟩ lemma update_injective (f : Πa, β a) (a' : α) : injective (update f a') := λ v v' h, have _ := congr_fun h a', by rwa [update_same, update_same] at this @[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a := dif_neg h lemma forall_update_iff (f : Π a, β a) {a : α} {b : β a} (p : Π a, β a → Prop) : (∀ x, p x (update f a b x)) ↔ p a b ∧ ∀ x ≠ a, p x (f x) := by { rw [← and_forall_ne a, update_same], simp { contextual := tt } } lemma exists_update_iff (f : Π a, β a) {a : α} {b : β a} (p : Π a, β a → Prop) : (∃ x, p x (update f a b x)) ↔ p a b ∨ ∃ x ≠ a, p x (f x) := by { rw [← not_forall_not, forall_update_iff f (λ a b, ¬p a b)], simp [not_and_distrib] } lemma update_eq_iff {a : α} {b : β a} {f g : Π a, β a} : update f a b = g ↔ b = g a ∧ ∀ x ≠ a, f x = g x := funext_iff.trans $ forall_update_iff _ (λ x y, y = g x) lemma eq_update_iff {a : α} {b : β a} {f g : Π a, β a} : g = update f a b ↔ g a = b ∧ ∀ x ≠ a, g x = f x := funext_iff.trans $ forall_update_iff _ (λ x y, g x = y) @[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f := update_eq_iff.2 ⟨rfl, λ _ _, rfl⟩ lemma update_comp_eq_of_forall_ne' {α'} (g : Π a, β a) {f : α' → α} {i : α} (a : β i) (h : ∀ x, f x ≠ i) : (λ j, (update g i a) (f j)) = (λ j, g (f j)) := funext $ λ x, update_noteq (h _) _ _ /-- Non-dependent version of `function.update_comp_eq_of_forall_ne'` -/ lemma update_comp_eq_of_forall_ne {α β : Sort*} (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ x, f x ≠ i) : (update g i a) ∘ f = g ∘ f := update_comp_eq_of_forall_ne' g a h lemma update_comp_eq_of_injective' (g : Π a, β a) {f : α' → α} (hf : function.injective f) (i : α') (a : β (f i)) : (λ j, update g (f i) a (f j)) = update (λ i, g (f i)) i a := eq_update_iff.2 ⟨update_same _ _ _, λ j hj, update_noteq (hf.ne hj) _ _⟩ /-- Non-dependent version of `function.update_comp_eq_of_injective'` -/ lemma update_comp_eq_of_injective {β : Sort*} (g : α' → β) {f : α → α'} (hf : function.injective f) (i : α) (a : β) : (function.update g (f i) a) ∘ f = function.update (g ∘ f) i a := update_comp_eq_of_injective' g hf i a lemma apply_update {ι : Sort*} [decidable_eq ι] {α β : ι → Sort*} (f : Π i, α i → β i) (g : Π i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (λ k, f k (g k)) i (f i v) j := begin by_cases h : j = i, { subst j, simp }, { simp [h] } end lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ (update g i v) = update (f ∘ g) i (f v) := funext $ apply_update _ _ _ _ theorem update_comm {α} [decidable_eq α] {β : α → Sort*} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) : update (update f a v) b w = update (update f b w) a v := begin funext c, simp only [update], by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]}, cases h (h₂.symm.trans h₁), end @[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*} {a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w := by {funext b, by_cases b = a; simp [update, h]} end update section extend noncomputable theory local attribute [instance, priority 10] classical.prop_decidable variables {α β γ : Type*} {f : α → β} /-- `extend f g e'` extends a function `g : α → γ` along a function `f : α → β` to a function `β → γ`, by using the values of `g` on the range of `f` and the values of an auxiliary function `e' : β → γ` elsewhere. Mostly useful when `f` is injective. -/ def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ := λ b, if h : ∃ a, f a = b then g (classical.some h) else e' b lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) [decidable (∃ a, f a = b)] : extend f g e' b = if h : ∃ a, f a = b then g (classical.some h) else e' b := by { unfold extend, congr } @[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := begin simp only [extend_def, dif_pos, exists_apply_eq_apply], exact congr_arg g (hf $ classical.some_spec (exists_apply_eq_apply f a)) end @[simp] lemma extend_apply' (g : α → γ) (e' : β → γ) (b : β) (hb : ¬∃ a, f a = b) : extend f g e' b = e' b := by simp [function.extend_def, hb] lemma extend_injective (hf : injective f) (e' : β → γ) : injective (λ g, extend f g e') := begin intros g₁ g₂ hg, refine funext (λ x, _), have H := congr_fun hg (f x), simp only [hf, extend_apply] at H, exact H end @[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext $ λ a, extend_apply hf g e' a end extend lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := rfl @[simp] lemma uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] lemma curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section bicomp variables {α β γ δ ε : Type*} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose an unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f `∘₂` g := bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) := rfl end bicomp section uncurry variables {α β γ δ : Type*} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Type*) (β : out_param Type*) (γ : out_param Type*) := (uncurry : α → (β → γ)) /-- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps.-/ add_decl_doc has_uncurry.uncurry notation `↿`:max x:max := has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ end uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) := funext_iff.symm namespace involutive variables {α : Sort u} {f : α → α} (h : involutive f) include h @[simp] lemma comp_self : f ∘ f = id := funext h protected lemma left_inverse : left_inverse f f := h protected lemma right_inverse : right_inverse f f := h protected lemma injective : injective f := h.left_inverse.injective protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩ protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected lemma ite_not (P : Prop) [decidable P] (x : α) : f (ite P x (f x)) = ite (¬ P) x (f x) := by rw [apply_ite f, h, ite_not] /-- An involution commutes across an equality. Compare to `function.injective.eq_iff`. -/ protected lemma eq_iff {x y : α} : f x = y ↔ x = f y := h.injective.eq_iff' (h y) end involutive /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ @[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop := ∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace injective2 variables {α β γ : Type*} (f : α → β → γ) protected lemma left (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ := (hf h).1 protected lemma right (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ := (hf h).2 lemma eq_iff (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ h, hf h, λ⟨h1, h2⟩, congr_arg2 f h1 h2⟩ end injective2 section sometimes local attribute [instance, priority 10] classical.prop_decidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [nonempty β] (f : α → β) : β := if h : nonempty α then f (classical.choice h) else classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa sometimes_eq end sometimes end function /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] : Πi, β i := λi, if i ∈ s then f i else g i /-! ### Bijectivity of `eq.rec`, `eq.mp`, `eq.mpr`, and `cast` -/ lemma eq_rec_on_bijective {α : Sort*} {C : α → Sort*} : ∀ {a a' : α} (h : a = a'), function.bijective (@eq.rec_on _ _ C _ h) | _ _ rfl := ⟨λ x y, id, λ x, ⟨x, rfl⟩⟩ lemma eq_mp_bijective {α β : Sort*} (h : α = β) : function.bijective (eq.mp h) := eq_rec_on_bijective h lemma eq_mpr_bijective {α β : Sort*} (h : α = β) : function.bijective (eq.mpr h) := eq_rec_on_bijective h.symm lemma cast_bijective {α β : Sort*} (h : α = β) : function.bijective (cast h) := eq_rec_on_bijective h /-! Note these lemmas apply to `Type*` not `Sort*`, as the latter interferes with `simp`, and is trivial anyway.-/ @[simp] lemma eq_rec_inj {α : Sort*} {a a' : α} (h : a = a') {C : α → Type*} (x y : C a) : (eq.rec x h : C a') = eq.rec y h ↔ x = y := (eq_rec_on_bijective h).injective.eq_iff @[simp] lemma cast_inj {α β : Type*} (h : α = β) {x y : α} : cast h x = cast h y ↔ x = y := (cast_bijective h).injective.eq_iff /-- A set of functions "separates points" if for each pair of distinct points there is a function taking different values on them. -/ def set.separates_points {α β : Type*} (A : set (α → β)) : Prop := ∀ ⦃x y : α⦄, x ≠ y → ∃ f ∈ A, (f x : β) ≠ f y lemma is_symm_op.flip_eq {α β} (op) [is_symm_op α β op] : flip op = op := funext $ λ a, funext $ λ b, (is_symm_op.symm_op a b).symm
2264a5da0efc236ec915fb289a30c82028ee61f8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/bicategory/functor.lean
753c00ca9eb49e9ee7b330c10e5171346c067b41
[ "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
19,514
lean
/- Copyright (c) 2022 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import category_theory.bicategory.basic /-! # Oplax functors and pseudofunctors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An oplax functor `F` between bicategories `B` and `C` consists of * a function between objects `F.obj : B ⟶ C`, * a family of functions between 1-morphisms `F.map : (a ⟶ b) → (F.obj a ⟶ F.obj b)`, * a family of functions between 2-morphisms `F.map₂ : (f ⟶ g) → (F.map f ⟶ F.map g)`, * a family of 2-morphisms `F.map_id a : F.map (𝟙 a) ⟶ 𝟙 (F.obj a)`, * a family of 2-morphisms `F.map_comp f g : F.map (f ≫ g) ⟶ F.map f ≫ F.map g`, and * certain consistency conditions on them. A pseudofunctor is an oplax functor whose `map_id` and `map_comp` are isomorphisms. We provide several constructors for pseudofunctors: * `pseudofunctor.mk` : the default constructor, which requires `map₂_whisker_left` and `map₂_whisker_right` instead of naturality of `map_comp`. * `pseudofunctor.mk_of_oplax` : construct a pseudofunctor from an oplax functor whose `map_id` and `map_comp` are isomorphisms. This constructor uses `iso` to describe isomorphisms. * `pseudofunctor.mk_of_oplax'` : similar to `mk_of_oplax`, but uses `is_iso` to describe isomorphisms. The additional constructors are useful when constructing a pseudofunctor where the construction of the oplax functor associated with it is already done. For example, the composition of pseudofunctors can be defined by using the composition of oplax functors as follows: ```lean def pseudofunctor.comp (F : pseudofunctor B C) (G : pseudofunctor C D) : pseudofunctor B D := mk_of_oplax ((F : oplax_functor B C).comp G) { map_id_iso := λ a, (G.map_functor _ _).map_iso (F.map_id a) ≪≫ G.map_id (F.obj a), map_comp_iso := λ a b c f g, (G.map_functor _ _).map_iso (F.map_comp f g) ≪≫ G.map_comp (F.map f) (F.map g) } ``` although the composition of pseudofunctors in this file is defined by using the default constructor because `obviously` is smart enough. Similarly, the composition is also defined by using `mk_of_oplax'` after giving appropriate instances for `is_iso`. The former constructor `mk_of_oplax` requires isomorphisms as data type `iso`, and so it is useful if you don't want to forget the definitions of the inverses. On the other hand, the latter constructor `mk_of_oplax'` is useful if you want to use propositional type class `is_iso`. ## Main definitions * `category_theory.oplax_functor B C` : an oplax functor between bicategories `B` and `C` * `category_theory.oplax_functor.comp F G` : the composition of oplax functors * `category_theory.pseudofunctor B C` : a pseudofunctor between bicategories `B` and `C` * `category_theory.pseudofunctor.comp F G` : the composition of pseudofunctors ## Future work There are two types of functors between bicategories, called lax and oplax functors, depending on the directions of `map_id` and `map_comp`. We may need both in mathlib in the future, but for now we only define oplax functors. -/ set_option old_structure_cmd true namespace category_theory open category bicategory open_locale bicategory universes w₁ w₂ w₃ v₁ v₂ v₃ u₁ u₂ u₃ section variables {B : Type u₁} [quiver.{v₁+1} B] [∀ a b : B, quiver.{w₁+1} (a ⟶ b)] variables {C : Type u₂} [quiver.{v₂+1} C] [∀ a b : C, quiver.{w₂+1} (a ⟶ b)] variables {D : Type u₃} [quiver.{v₃+1} D] [∀ a b : D, quiver.{w₃+1} (a ⟶ b)] /-- A prelax functor between bicategories consists of functions between objects, 1-morphisms, and 2-morphisms. This structure will be extended to define `oplax_functor`. -/ structure prelax_functor (B : Type u₁) [quiver.{v₁+1} B] [∀ a b : B, quiver.{w₁+1} (a ⟶ b)] (C : Type u₂) [quiver.{v₂+1} C] [∀ a b : C, quiver.{w₂+1} (a ⟶ b)] extends prefunctor B C := (map₂ {a b : B} {f g : a ⟶ b} : (f ⟶ g) → (map f ⟶ map g)) /-- The prefunctor between the underlying quivers. -/ add_decl_doc prelax_functor.to_prefunctor namespace prelax_functor instance has_coe_to_prefunctor : has_coe (prelax_functor B C) (prefunctor B C) := ⟨to_prefunctor⟩ variables (F : prelax_functor B C) @[simp] lemma to_prefunctor_eq_coe : F.to_prefunctor = F := rfl @[simp] lemma to_prefunctor_obj : (F : prefunctor B C).obj = F.obj := rfl @[simp] lemma to_prefunctor_map : @prefunctor.map B _ C _ F = @map _ _ _ _ _ _ F := rfl /-- The identity prelax functor. -/ @[simps] def id (B : Type u₁) [quiver.{v₁+1} B] [∀ a b : B, quiver.{w₁+1} (a ⟶ b)] : prelax_functor B B := { map₂ := λ a b f g η, η, .. prefunctor.id B } instance : inhabited (prelax_functor B B) := ⟨prelax_functor.id B⟩ /-- Composition of prelax functors. -/ @[simps] def comp (F : prelax_functor B C) (G : prelax_functor C D) : prelax_functor B D := { map₂ := λ a b f g η, G.map₂ (F.map₂ η), .. (F : prefunctor B C).comp ↑G } end prelax_functor end section variables {B : Type u₁} [bicategory.{w₁ v₁} B] {C : Type u₂} [bicategory.{w₂ v₂} C] variables {D : Type u₃} [bicategory.{w₃ v₃} D] /-- This auxiliary definition states that oplax functors preserve the associators modulo some adjustments of domains and codomains of 2-morphisms. -/ /- We use this auxiliary definition instead of writing it directly in the definition of oplax functors because doing so will cause a timeout. -/ @[simp] def oplax_functor.map₂_associator_aux (obj : B → C) (map : Π {X Y : B}, (X ⟶ Y) → (obj X ⟶ obj Y)) (map₂ : Π {a b : B} {f g : a ⟶ b}, (f ⟶ g) → (map f ⟶ map g)) (map_comp : Π {a b c : B} (f : a ⟶ b) (g : b ⟶ c), map (f ≫ g) ⟶ map f ≫ map g) {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : Prop := map₂ (α_ f g h).hom ≫ map_comp f (g ≫ h) ≫ map f ◁ map_comp g h = map_comp (f ≫ g) h ≫ map_comp f g ▷ map h ≫ (α_ (map f) (map g) (map h)).hom /-- An oplax functor `F` between bicategories `B` and `C` consists of a function between objects `F.obj`, a function between 1-morphisms `F.map`, and a function between 2-morphisms `F.map₂`. Unlike functors between categories, `F.map` do not need to strictly commute with the composition, and do not need to strictly preserve the identity. Instead, there are specified 2-morphisms `F.map (𝟙 a) ⟶ 𝟙 (F.obj a)` and `F.map (f ≫ g) ⟶ F.map f ≫ F.map g`. `F.map₂` strictly commute with compositions and preserve the identity. They also preserve the associator, the left unitor, and the right unitor modulo some adjustments of domains and codomains of 2-morphisms. -/ structure oplax_functor (B : Type u₁) [bicategory.{w₁ v₁} B] (C : Type u₂) [bicategory.{w₂ v₂} C] extends prelax_functor B C := (map_id (a : B) : map (𝟙 a) ⟶ 𝟙 (obj a)) (map_comp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : map (f ≫ g) ⟶ map f ≫ map g) (map_comp_naturality_left' : ∀ {a b c : B} {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c), map₂ (η ▷ g) ≫ map_comp f' g = map_comp f g ≫ map₂ η ▷ map g . obviously) (map_comp_naturality_right' : ∀ {a b c : B} (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g'), map₂ (f ◁ η) ≫ map_comp f g' = map_comp f g ≫ map f ◁ map₂ η . obviously) (map₂_id' : ∀ {a b : B} (f : a ⟶ b), map₂ (𝟙 f) = 𝟙 (map f) . obviously) (map₂_comp' : ∀ {a b : B} {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h), map₂ (η ≫ θ) = map₂ η ≫ map₂ θ . obviously) (map₂_associator' : ∀ {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d), oplax_functor.map₂_associator_aux obj (λ _ _, map) (λ a b f g, map₂) (λ a b c, map_comp) f g h . obviously) (map₂_left_unitor' : ∀ {a b : B} (f : a ⟶ b), map₂ (λ_ f).hom = map_comp (𝟙 a) f ≫ map_id a ▷ map f ≫ (λ_ (map f)).hom . obviously) (map₂_right_unitor' : ∀ {a b : B} (f : a ⟶ b), map₂ (ρ_ f).hom = map_comp f (𝟙 b) ≫ map f ◁ map_id b ≫ (ρ_ (map f)).hom . obviously) namespace oplax_functor restate_axiom map_comp_naturality_left' restate_axiom map_comp_naturality_right' restate_axiom map₂_id' restate_axiom map₂_comp' restate_axiom map₂_associator' restate_axiom map₂_left_unitor' restate_axiom map₂_right_unitor' attribute [simp] map_comp_naturality_left map_comp_naturality_right map₂_id map₂_associator attribute [reassoc] map_comp_naturality_left map_comp_naturality_right map₂_comp map₂_associator map₂_left_unitor map₂_right_unitor attribute [simp] map₂_comp map₂_left_unitor map₂_right_unitor section /-- The prelax functor between the underlying quivers. -/ add_decl_doc oplax_functor.to_prelax_functor instance has_coe_to_prelax : has_coe (oplax_functor B C) (prelax_functor B C) := ⟨to_prelax_functor⟩ variables (F : oplax_functor B C) @[simp] lemma to_prelax_eq_coe : F.to_prelax_functor = F := rfl @[simp] lemma to_prelax_functor_obj : (F : prelax_functor B C).obj = F.obj := rfl @[simp] lemma to_prelax_functor_map : @prelax_functor.map B _ _ C _ _ F = @map _ _ _ _ F := rfl @[simp] lemma to_prelax_functor_map₂ : @prelax_functor.map₂ B _ _ C _ _ F = @map₂ _ _ _ _ F := rfl /-- Function between 1-morphisms as a functor. -/ @[simps] def map_functor (a b : B) : (a ⟶ b) ⥤ (F.obj a ⟶ F.obj b) := { obj := λ f, F.map f, map := λ f g η, F.map₂ η } /-- The identity oplax functor. -/ @[simps] def id (B : Type u₁) [bicategory.{w₁ v₁} B] : oplax_functor B B := { map_id := λ a, 𝟙 (𝟙 a), map_comp := λ a b c f g, 𝟙 (f ≫ g), .. prelax_functor.id B } instance : inhabited (oplax_functor B B) := ⟨id B⟩ /-- Composition of oplax functors. -/ @[simps] def comp (F : oplax_functor B C) (G : oplax_functor C D) : oplax_functor B D := { map_id := λ a, (G.map_functor _ _).map (F.map_id a) ≫ G.map_id (F.obj a), map_comp := λ a b c f g, (G.map_functor _ _).map (F.map_comp f g) ≫ G.map_comp (F.map f) (F.map g), map_comp_naturality_left' := λ a b c f f' η g, by { dsimp, rw [←map₂_comp_assoc, map_comp_naturality_left, map₂_comp_assoc, map_comp_naturality_left, assoc] }, map_comp_naturality_right' := λ a b c f g g' η, by { dsimp, rw [←map₂_comp_assoc, map_comp_naturality_right, map₂_comp_assoc, map_comp_naturality_right, assoc] }, map₂_associator' := λ a b c d f g h, by { dsimp, simp only [map₂_associator, ←map₂_comp_assoc, ←map_comp_naturality_right_assoc, whisker_left_comp, assoc], simp only [map₂_associator, map₂_comp, map_comp_naturality_left_assoc, comp_whisker_right, assoc] }, map₂_left_unitor' := λ a b f, by { dsimp, simp only [map₂_left_unitor, map₂_comp, map_comp_naturality_left_assoc, comp_whisker_right, assoc] }, map₂_right_unitor' := λ a b f, by { dsimp, simp only [map₂_right_unitor, map₂_comp, map_comp_naturality_right_assoc, whisker_left_comp, assoc] }, .. (F : prelax_functor B C).comp ↑G } /-- A structure on an oplax functor that promotes an oplax functor to a pseudofunctor. See `pseudofunctor.mk_of_oplax`. -/ @[nolint has_nonempty_instance] structure pseudo_core (F : oplax_functor B C) := (map_id_iso (a : B) : F.map (𝟙 a) ≅ 𝟙 (F.obj a)) (map_comp_iso {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : F.map (f ≫ g) ≅ F.map f ≫ F.map g) (map_id_iso_hom' : ∀ {a : B}, (map_id_iso a).hom = F.map_id a . obviously) (map_comp_iso_hom' : ∀ {a b c : B} (f : a ⟶ b) (g : b ⟶ c), (map_comp_iso f g).hom = F.map_comp f g . obviously) restate_axiom pseudo_core.map_id_iso_hom' restate_axiom pseudo_core.map_comp_iso_hom' attribute [simp] pseudo_core.map_id_iso_hom pseudo_core.map_comp_iso_hom end end oplax_functor /-- This auxiliary definition states that pseudofunctors preserve the associators modulo some adjustments of domains and codomains of 2-morphisms. -/ /- We use this auxiliary definition instead of writing it directly in the definition of pseudofunctors because doing so will cause a timeout. -/ @[simp] def pseudofunctor.map₂_associator_aux (obj : B → C) (map : Π {X Y : B}, (X ⟶ Y) → (obj X ⟶ obj Y)) (map₂ : Π {a b : B} {f g : a ⟶ b}, (f ⟶ g) → (map f ⟶ map g)) (map_comp : Π {a b c : B} (f : a ⟶ b) (g : b ⟶ c), map (f ≫ g) ≅ map f ≫ map g) {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : Prop := map₂ (α_ f g h).hom = (map_comp (f ≫ g) h).hom ≫ (map_comp f g).hom ▷ map h ≫ (α_ (map f) (map g) (map h)).hom ≫ map f ◁ (map_comp g h).inv ≫ (map_comp f (g ≫ h)).inv /-- A pseudofunctor `F` between bicategories `B` and `C` consists of a function between objects `F.obj`, a function between 1-morphisms `F.map`, and a function between 2-morphisms `F.map₂`. Unlike functors between categories, `F.map` do not need to strictly commute with the compositions, and do not need to strictly preserve the identity. Instead, there are specified 2-isomorphisms `F.map (𝟙 a) ≅ 𝟙 (F.obj a)` and `F.map (f ≫ g) ≅ F.map f ≫ F.map g`. `F.map₂` strictly commute with compositions and preserve the identity. They also preserve the associator, the left unitor, and the right unitor modulo some adjustments of domains and codomains of 2-morphisms. -/ structure pseudofunctor (B : Type u₁) [bicategory.{w₁ v₁} B] (C : Type u₂) [bicategory.{w₂ v₂} C] extends prelax_functor B C := (map_id (a : B) : map (𝟙 a) ≅ 𝟙 (obj a)) (map_comp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : map (f ≫ g) ≅ map f ≫ map g) (map₂_id' : ∀ {a b : B} (f : a ⟶ b), map₂ (𝟙 f) = 𝟙 (map f) . obviously) (map₂_comp' : ∀ {a b : B} {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h), map₂ (η ≫ θ) = map₂ η ≫ map₂ θ . obviously) (map₂_whisker_left' : ∀ {a b c : B} (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h), map₂ (f ◁ η) = (map_comp f g).hom ≫ map f ◁ map₂ η ≫ (map_comp f h).inv . obviously) (map₂_whisker_right' : ∀ {a b c : B} {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c), map₂ (η ▷ h) = (map_comp f h).hom ≫ map₂ η ▷ map h ≫ (map_comp g h).inv . obviously) (map₂_associator' : ∀ {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d), pseudofunctor.map₂_associator_aux obj (λ a b, map) (λ a b f g, map₂) (λ a b c, map_comp) f g h . obviously) (map₂_left_unitor' : ∀ {a b : B} (f : a ⟶ b), map₂ (λ_ f).hom = (map_comp (𝟙 a) f).hom ≫ (map_id a).hom ▷ map f ≫ (λ_ (map f)).hom . obviously) (map₂_right_unitor' : ∀ {a b : B} (f : a ⟶ b), map₂ (ρ_ f).hom = (map_comp f (𝟙 b)).hom ≫ map f ◁ (map_id b).hom ≫ (ρ_ (map f)).hom . obviously) namespace pseudofunctor restate_axiom map₂_id' restate_axiom map₂_comp' restate_axiom map₂_whisker_left' restate_axiom map₂_whisker_right' restate_axiom map₂_associator' restate_axiom map₂_left_unitor' restate_axiom map₂_right_unitor' attribute [reassoc] map₂_comp map₂_whisker_left map₂_whisker_right map₂_associator map₂_left_unitor map₂_right_unitor attribute [simp] map₂_id map₂_comp map₂_whisker_left map₂_whisker_right map₂_associator map₂_left_unitor map₂_right_unitor section open iso /-- The prelax functor between the underlying quivers. -/ add_decl_doc pseudofunctor.to_prelax_functor instance has_coe_to_prelax_functor : has_coe (pseudofunctor B C) (prelax_functor B C) := ⟨to_prelax_functor⟩ variables (F : pseudofunctor B C) @[simp] lemma to_prelax_functor_eq_coe : F.to_prelax_functor = F := rfl @[simp] lemma to_prelax_functor_obj : (F : prelax_functor B C).obj = F.obj := rfl @[simp] lemma to_prelax_functor_map : @prelax_functor.map B _ _ C _ _ F = @map _ _ _ _ F := rfl @[simp] lemma to_prelax_functor_map₂ : @prelax_functor.map₂ B _ _ C _ _ F = @map₂ _ _ _ _ F := rfl /-- The oplax functor associated with a pseudofunctor. -/ def to_oplax : oplax_functor B C := { map_id := λ a, (F.map_id a).hom, map_comp := λ a b c f g, (F.map_comp f g).hom, .. (F : prelax_functor B C) } instance has_coe_to_oplax : has_coe (pseudofunctor B C) (oplax_functor B C) := ⟨to_oplax⟩ @[simp] lemma to_oplax_eq_coe : F.to_oplax = F := rfl @[simp] lemma to_oplax_obj : (F : oplax_functor B C).obj = F.obj := rfl @[simp] lemma to_oplax_map : @oplax_functor.map B _ C _ F = @map _ _ _ _ F := rfl @[simp] lemma to_oplax_map₂ : @oplax_functor.map₂ B _ C _ F = @map₂ _ _ _ _ F := rfl @[simp] lemma to_oplax_map_id (a : B) : (F : oplax_functor B C).map_id a = (F.map_id a).hom := rfl @[simp] lemma to_oplax_map_comp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : (F : oplax_functor B C).map_comp f g = (F.map_comp f g).hom := rfl /-- Function on 1-morphisms as a functor. -/ @[simps] def map_functor (a b : B) : (a ⟶ b) ⥤ (F.obj a ⟶ F.obj b) := (F : oplax_functor B C).map_functor a b /-- The identity pseudofunctor. -/ @[simps] def id (B : Type u₁) [bicategory.{w₁ v₁} B] : pseudofunctor B B := { map_id := λ a, iso.refl (𝟙 a), map_comp := λ a b c f g, iso.refl (f ≫ g), .. prelax_functor.id B } instance : inhabited (pseudofunctor B B) := ⟨id B⟩ /-- Composition of pseudofunctors. -/ @[simps] def comp (F : pseudofunctor B C) (G : pseudofunctor C D) : pseudofunctor B D := { map_id := λ a, (G.map_functor _ _).map_iso (F.map_id a) ≪≫ G.map_id (F.obj a), map_comp := λ a b c f g, (G.map_functor _ _).map_iso (F.map_comp f g) ≪≫ G.map_comp (F.map f) (F.map g), .. (F : prelax_functor B C).comp ↑G } /-- Construct a pseudofunctor from an oplax functor whose `map_id` and `map_comp` are isomorphisms. -/ @[simps] def mk_of_oplax (F : oplax_functor B C) (F' : F.pseudo_core) : pseudofunctor B C := { map_id := F'.map_id_iso, map_comp := λ _ _ _, F'.map_comp_iso, map₂_whisker_left' := λ a b c f g h η, by { dsimp, rw [F'.map_comp_iso_hom f g, ←F.map_comp_naturality_right_assoc, ←F'.map_comp_iso_hom f h, hom_inv_id, comp_id] }, map₂_whisker_right' := λ a b c f g η h, by { dsimp, rw [F'.map_comp_iso_hom f h, ←F.map_comp_naturality_left_assoc, ←F'.map_comp_iso_hom g h, hom_inv_id, comp_id] }, map₂_associator' := λ a b c d f g h, by { dsimp, rw [F'.map_comp_iso_hom (f ≫ g) h, F'.map_comp_iso_hom f g, ←F.map₂_associator_assoc, ←F'.map_comp_iso_hom f (g ≫ h), ←F'.map_comp_iso_hom g h, hom_inv_whisker_left_assoc, hom_inv_id, comp_id] }, .. (F : prelax_functor B C) } /-- Construct a pseudofunctor from an oplax functor whose `map_id` and `map_comp` are isomorphisms. -/ @[simps] noncomputable def mk_of_oplax' (F : oplax_functor B C) [∀ a, is_iso (F.map_id a)] [∀ {a b c} (f : a ⟶ b) (g : b ⟶ c), is_iso (F.map_comp f g)] : pseudofunctor B C := { map_id := λ a, as_iso (F.map_id a), map_comp := λ a b c f g, as_iso (F.map_comp f g), map₂_whisker_left' := λ a b c f g h η, by { dsimp, rw [←assoc, is_iso.eq_comp_inv, F.map_comp_naturality_right] }, map₂_whisker_right' := λ a b c f g η h, by { dsimp, rw [←assoc, is_iso.eq_comp_inv, F.map_comp_naturality_left] }, map₂_associator' := λ a b c d f g h, by { dsimp, simp only [←assoc], rw [is_iso.eq_comp_inv, ←inv_whisker_left, is_iso.eq_comp_inv], simp only [assoc, F.map₂_associator] }, .. (F : prelax_functor B C) } end end pseudofunctor end end category_theory
1f71027b7c8c2eb4369710eb36cb13d1e506499e
9dc8cecdf3c4634764a18254e94d43da07142918
/src/set_theory/cardinal/basic.lean
e7b7eefa30b7c762bf5ec6bbbe1d1566b83c804c
[ "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
67,498
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import data.fintype.card import data.finsupp.defs import data.nat.part_enat import data.set.countable import logic.small import order.conditionally_complete_lattice import order.succ_pred.basic import set_theory.cardinal.schroeder_bernstein /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α × β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.aleph_0` or `ℵ₀` is the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.aleph_0.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.sum` is the sum of an indexed family of cardinals, i.e. the cardinality of the corresponding sigma type. * `cardinal.prod` is the product of an indexed family of cardinals, i.e. the cardinality of the corresponding pi type. * `cardinal.powerlt a b` or `a ^< b` is defined as the supremum of `a ^ c` for `c < b`. ## Main instances * Cardinals form a `canonically_ordered_comm_semiring` with the aforementioned sum and product. * Cardinals form a `succ_order`. Use `order.succ c` for the smallest cardinal greater than `c`. * The less than relation on cardinals forms a well-order. * Cardinals form a `conditionally_complete_linear_order_bot`. Bounded sets for cardinals in universe `u` are precisely the sets indexed by some type in universe `u`, see `cardinal.bdd_above_iff_small`. One can use `Sup` for the cardinal supremum, and `Inf` for the minimum of a set of cardinals. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr (name := cardinal.pow) ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, aleph, Cantor's theorem, König's theorem, Konig's theorem -/ open function set order open_locale big_operators classical noncomputable theory universes u v w variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λ α β, nonempty (α ≃ β), iseqv := ⟨λ α, ⟨equiv.refl α⟩, λ α β ⟨e⟩, ⟨e.symm⟩, λ α β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "prefix (name := cardinal.mk) `#` := cardinal.mk" in cardinal instance can_lift_cardinal_Type : can_lift cardinal.{u} (Type u) := ⟨mk, λ c, true, λ c _, quot.induction_on c $ λ α, ⟨α, rfl⟩⟩ @[elab_as_eliminator] lemma induction_on {p : cardinal → Prop} (c : cardinal) (h : ∀ α, p (#α)) : p c := quotient.induction_on c h @[elab_as_eliminator] lemma induction_on₂ {p : cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (h : ∀ α β, p (#α) (#β)) : p c₁ c₂ := quotient.induction_on₂ c₁ c₂ h @[elab_as_eliminator] lemma induction_on₃ {p : cardinal → cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (c₃ : cardinal) (h : ∀ α β γ, p (#α) (#β) (#γ)) : p c₁ c₂ c₃ := quotient.induction_on₃ c₁ c₂ c₃ h protected lemma eq : #α = #β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (#α) := rfl @[simp] theorem mk_out (c : cardinal) : #(c.out) = c := quotient.out_eq _ /-- The representative of the cardinal of a type is equivalent ot the original type. -/ def out_mk_equiv {α : Type v} : (#α).out ≃ α := nonempty.some $ cardinal.eq.mp (by simp) lemma mk_congr (e : α ≃ β) : # α = # β := quot.sound ⟨e⟩ alias mk_congr ← _root_.equiv.cardinal_eq /-- Lift a function between `Type*`s to a function between `cardinal`s. -/ def map (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) : cardinal.{u} → cardinal.{v} := quotient.map f (λ α β ⟨e⟩, ⟨hf α β e⟩) @[simp] lemma map_mk (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) (α : Type u) : map f hf (#α) = #(f α) := rfl /-- Lift a binary operation `Type* → Type* → Type*` to a binary operation on `cardinal`s. -/ def map₂ (f : Type u → Type v → Type w) (hf : ∀ α β γ δ, α ≃ β → γ ≃ δ → f α γ ≃ f β δ) : cardinal.{u} → cardinal.{v} → cardinal.{w} := quotient.map₂ f $ λ α β ⟨e₁⟩ γ δ ⟨e₂⟩, ⟨hf α β γ δ e₁ e₂⟩ /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{v} → cardinal.{max v u}` -/ def lift (c : cardinal.{v}) : cardinal.{max v u} := map ulift (λ α β e, equiv.ulift.trans $ e.trans equiv.ulift.symm) c @[simp] theorem mk_ulift (α) : #(ulift.{v u} α) = lift.{v} (#α) := rfl /-- `lift.{(max u v) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much easier to understand what's happening when using this lemma. -/ @[simp] theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α, (equiv.ulift.trans equiv.ulift.symm).cardinal_eq /-- `lift.{(max v u) u}` equals `lift.{v u}`. Using `set_option pp.universes true` will make it much easier to understand what's happening when using this lemma. -/ @[simp] theorem lift_umax' : lift.{(max v u) u} = lift.{v u} := lift_umax /-- A cardinal lifted to a lower or equal universe equals itself. -/ @[simp] theorem lift_id' (a : cardinal.{max u v}) : lift.{u} a = a := induction_on a $ λ α, mk_congr equiv.ulift /-- A cardinal lifted to the same universe equals itself. -/ @[simp] theorem lift_id (a : cardinal) : lift.{u u} a = a := lift_id'.{u u} a /-- A cardinal lifted to the zero universe equals itself. -/ @[simp] theorem lift_uzero (a : cardinal.{u}) : lift.{0} a = a := lift_id'.{0 u} a @[simp] theorem lift_lift (a : cardinal) : lift.{w} (lift.{v} a) = lift.{max v w} a := induction_on a $ λ α, (equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm).cardinal_eq /-- We define the order on cardinal numbers by `#α ≤ #β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λ q₁ q₂, quotient.lift_on₂ q₁ q₂ (λ α β, nonempty $ α ↪ β) $ λ α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨λ ⟨e⟩, ⟨e.congr e₁ e₂⟩, λ ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ instance : partial_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by { rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩, exact quotient.sound (e₁.antisymm e₂) } } theorem le_def (α β : Type u) : #α ≤ #β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : #α ≤ #β := ⟨⟨f, hf⟩⟩ theorem _root_.function.embedding.cardinal_le {α β : Type u} (f : α ↪ β) : #α ≤ #β := ⟨f⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : #β ≤ #α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ #α ↔ ∃ p : set α, #p = c := ⟨induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, (equiv.of_injective f hf).cardinal_eq.symm⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem mk_subtype_le {α : Type u} (p : α → Prop) : #(subtype p) ≤ #α := ⟨embedding.subtype p⟩ theorem mk_set_le (s : set α) : #s ≤ #α := mk_subtype_le s theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } theorem lift_mk_le {α : Type u} {β : Type v} : lift.{max v w} (#α) ≤ lift.{max u w} (#β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ /-- A variant of `cardinal.lift_mk_le` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_le' {α : Type u} {β : Type v} : lift.{v} (#α) ≤ lift.{u} (#β) ↔ nonempty (α ↪ β) := lift_mk_le.{u v 0} theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{max v w} (#α) = lift.{max u w} (#β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ /-- A variant of `cardinal.lift_mk_eq` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_eq' {α : Type u} {β : Type v} : lift.{v} (#α) = lift.{u} (#β) ↔ nonempty (α ≃ β) := lift_mk_eq.{u v 0} @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := induction_on₂ a b $ λ α β, by { rw ← lift_umax, exact lift_mk_le } /-- `cardinal.lift` as an `order_embedding`. -/ @[simps { fully_applied := ff }] def lift_order_embedding : cardinal.{v} ↪o cardinal.{max v u} := order_embedding.of_map_le_iff lift (λ _ _, lift_le) theorem lift_injective : injective lift.{u v} := lift_order_embedding.injective @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := lift_injective.eq_iff @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := lift_order_embedding.lt_iff_lt theorem lift_strict_mono : strict_mono lift := λ a b, lift_lt.2 theorem lift_monotone : monotone lift := lift_strict_mono.monotone instance : has_zero cardinal.{u} := ⟨#pempty⟩ instance : inhabited cardinal.{u} := ⟨0⟩ lemma mk_eq_zero (α : Type u) [is_empty α] : #α = 0 := (equiv.equiv_pempty α).cardinal_eq @[simp] theorem lift_zero : lift 0 = 0 := mk_congr (equiv.equiv_pempty _) @[simp] theorem lift_eq_zero {a : cardinal.{v}} : lift.{u} a = 0 ↔ a = 0 := lift_injective.eq_iff' lift_zero lemma mk_eq_zero_iff {α : Type u} : #α = 0 ↔ is_empty α := ⟨λ e, let ⟨h⟩ := quotient.exact e in h.is_empty, @mk_eq_zero α⟩ theorem mk_ne_zero_iff {α : Type u} : #α ≠ 0 ↔ nonempty α := (not_iff_not.2 mk_eq_zero_iff).trans not_is_empty_iff @[simp] lemma mk_ne_zero (α : Type u) [nonempty α] : #α ≠ 0 := mk_ne_zero_iff.2 ‹_› instance : has_one cardinal.{u} := ⟨#punit⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, mk_ne_zero _⟩⟩ lemma mk_eq_one (α : Type u) [unique α] : #α = 1 := (equiv.equiv_punit α).cardinal_eq theorem le_one_iff_subsingleton {α : Type u} : #α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨map₂ sum $ λ α β γ δ, equiv.sum_congr⟩ theorem add_def (α β : Type u) : #α + #β = #(α ⊕ β) := rfl instance : has_nat_cast cardinal.{u} := ⟨nat.unary_cast⟩ @[simp] lemma mk_sum (α : Type u) (β : Type v) : #(α ⊕ β) = lift.{v u} (#α) + lift.{u v} (#β) := mk_congr ((equiv.ulift).symm.sum_congr (equiv.ulift).symm) @[simp] theorem mk_option {α : Type u} : #(option α) = #α + 1 := (equiv.option_equiv_sum_punit α).cardinal_eq @[simp] lemma mk_psum (α : Type u) (β : Type v) : #(psum α β) = lift.{v} (#α) + lift.{u} (#β) := (mk_congr (equiv.psum_equiv_sum α β)).trans (mk_sum α β) @[simp] lemma mk_fintype (α : Type u) [fintype α] : #α = fintype.card α := begin refine fintype.induction_empty_option _ _ _ α, { introsI α β h e hα, letI := fintype.of_equiv β e.symm, rwa [mk_congr e, fintype.card_congr e] at hα }, { refl }, { introsI α h hα, simp [hα], refl } end instance : has_mul cardinal.{u} := ⟨map₂ prod $ λ α β γ δ, equiv.prod_congr⟩ theorem mul_def (α β : Type u) : #α * #β = #(α × β) := rfl @[simp] lemma mk_prod (α : Type u) (β : Type v) : #(α × β) = lift.{v u} (#α) * lift.{u v} (#β) := mk_congr (equiv.ulift.symm.prod_congr (equiv.ulift).symm) private theorem mul_comm' (a b : cardinal.{u}) : a * b = b * a := induction_on₂ a b $ λ α β, mk_congr $ equiv.prod_comm α β /-- The cardinal exponential. `#α ^ #β` is the cardinal of `β → α`. -/ instance : has_pow cardinal.{u} cardinal.{u} := ⟨map₂ (λ α β, β → α) (λ α β γ δ e₁ e₂, e₂.arrow_congr e₁)⟩ local infixr (name := cardinal.pow) ^ := @has_pow.pow cardinal cardinal cardinal.has_pow local infixr (name := cardinal.pow.nat) ` ^ℕ `:80 := @has_pow.pow cardinal ℕ monoid.has_pow theorem power_def (α β) : #α ^ #β = #(β → α) := rfl theorem mk_arrow (α : Type u) (β : Type v) : #(α → β) = lift.{u} (#β) ^ lift.{v} (#α) := mk_congr (equiv.ulift.symm.arrow_congr equiv.ulift.symm) @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := induction_on₂ a b $ λ α β, mk_congr $ equiv.ulift.trans (equiv.ulift.arrow_congr equiv.ulift).symm @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := induction_on a $ λ α, mk_congr $ equiv.pempty_arrow_equiv_punit α @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := induction_on a $ λ α, mk_congr $ equiv.punit_arrow_equiv α theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.sum_arrow_equiv_prod_arrow β γ α instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := λ a, induction_on a $ λ α, mk_congr $ equiv.empty_sum pempty α, add_zero := λ a, induction_on a $ λ α, mk_congr $ equiv.sum_empty α pempty, add_assoc := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.sum_assoc α β γ, add_comm := λ a b, induction_on₂ a b $ λ α β, mk_congr $ equiv.sum_comm α β, zero_mul := λ a, induction_on a $ λ α, mk_congr $ equiv.pempty_prod α, mul_zero := λ a, induction_on a $ λ α, mk_congr $ equiv.prod_pempty α, one_mul := λ a, induction_on a $ λ α, mk_congr $ equiv.punit_prod α, mul_one := λ a, induction_on a $ λ α, mk_congr $ equiv.prod_punit α, mul_assoc := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.prod_assoc α β γ, mul_comm := mul_comm', left_distrib := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.prod_sum_distrib α β γ, right_distrib := λ a b c, induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.sum_prod_distrib α β γ, npow := λ n c, c ^ n, npow_zero' := @power_zero, npow_succ' := λ n c, show c ^ (n + 1) = c * c ^ n, by rw [power_add, power_one, mul_comm'] } theorem power_bit0 (a b : cardinal) : a ^ (bit0 b) = a ^ b * a ^ b := power_add theorem power_bit1 (a b : cardinal) : a ^ (bit1 b) = a ^ b * a ^ b * a := by rw [bit1, ←power_bit0, power_add, power_one] @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := induction_on a $ λ α, (equiv.arrow_punit_equiv_punit α).cardinal_eq @[simp] theorem mk_bool : #bool = 2 := by simp @[simp] theorem mk_Prop : #(Prop) = 2 := by simp @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := induction_on a $ λ α heq, mk_eq_zero_iff.2 $ is_empty_pi.2 $ let ⟨a⟩ := mk_ne_zero_iff.1 heq in ⟨a, pempty.is_empty⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := induction_on₂ a b $ λ α β h, let ⟨a⟩ := mk_ne_zero_iff.1 h in mk_ne_zero_iff.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := induction_on₃ a b c $ λ α β γ, mk_congr $ equiv.arrow_prod_equiv_prod_arrow α β γ theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c := by { rw [mul_comm b c], exact induction_on₃ a b c (λ α β γ, mk_congr $ equiv.curry γ β α) } @[simp] lemma pow_cast_right (a : cardinal.{u}) (n : ℕ) : (a ^ (↑n : cardinal.{u})) = a ^ℕ n := rfl @[simp] theorem lift_one : lift 1 = 1 := mk_congr $ equiv.ulift.trans equiv.punit_equiv_punit @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := induction_on₂ a b $ λ α β, mk_congr $ equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := induction_on₂ a b $ λ α β, mk_congr $ equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm @[simp] theorem lift_bit0 (a : cardinal) : lift (bit0 a) = bit0 (lift a) := lift_add a a @[simp] theorem lift_bit1 (a : cardinal) : lift (bit1 a) = bit1 (lift a) := by simp [bit1] theorem lift_two : lift.{u v} 2 = 2 := by simp @[simp] theorem mk_set {α : Type u} : #(set α) = 2 ^ #α := by simp [set, mk_arrow] /-- A variant of `cardinal.mk_set` expressed in terms of a `set` instead of a `Type`. -/ @[simp] theorem mk_powerset {α : Type u} (s : set α) : #↥(𝒫 s) = 2 ^ #↥s := (mk_congr (equiv.set.powerset s)).trans mk_set theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp section order_properties open sum protected theorem zero_le : ∀ a : cardinal, 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩ private theorem add_le_add' : ∀ {a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ instance add_covariant_class : covariant_class cardinal cardinal (+) (≤) := ⟨λ a b c, add_le_add' le_rfl⟩ instance add_swap_covariant_class : covariant_class cardinal cardinal (swap (+)) (≤) := ⟨λ a b c h, add_le_add' h le_rfl⟩ instance : canonically_ordered_comm_semiring cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, add_le_add_left := λ a b, add_le_add_left, exists_add_of_le := λ a b, induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨#↥(range f)ᶜ, mk_congr this.symm⟩, le_self_add := λ a b, (add_zero a).ge.trans $ add_le_add_left (cardinal.zero_le _) _, eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, induction_on₂ a b $ λ α β, by simpa only [mul_def, mk_eq_zero_iff, is_empty_prod] using id, ..cardinal.comm_semiring, ..cardinal.partial_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀ {a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := mk_ne_zero_iff.1 hα in ⟨@embedding.arrow_congr_left _ _ _ ⟨a⟩ e⟩ theorem self_le_power (a : cardinal) {b : cardinal} (hb : 1 ≤ b) : a ≤ a ^ b := begin rcases eq_or_ne a 0 with rfl|ha, { exact zero_le _ }, { convert power_le_power_left ha hb, exact power_one.symm } end /-- **Cantor's theorem** -/ theorem cantor (a : cardinal.{u}) : a < 2 ^ a := begin induction a using cardinal.induction_on with α, rw [← mk_set], refine ⟨⟨⟨singleton, λ a b, singleton_eq_singleton_iff.1⟩⟩, _⟩, rintro ⟨⟨f, hf⟩⟩, exact cantor_injective f hf end instance : no_max_order cardinal.{u} := { exists_gt := λ a, ⟨_, cantor a⟩, ..cardinal.partial_order } instance : canonically_linear_ordered_add_monoid cardinal.{u} := { le_total := by { rintros ⟨α⟩ ⟨β⟩, apply embedding.total }, decidable_le := classical.dec_rel _, ..(infer_instance : canonically_ordered_add_monoid cardinal), ..cardinal.partial_order } -- short-circuit type class inference instance : distrib_lattice cardinal.{u} := by apply_instance theorem one_lt_iff_nontrivial {α : Type u} : 1 < #α ↔ nontrivial α := by rw [← not_le, le_one_iff_subsingleton, ← not_nontrivial_iff_subsingleton, not_not] theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact (power_le_power_left ha h).trans (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := induction_on₃ a b c $ λ α β γ ⟨e⟩, ⟨embedding.arrow_congr_right e⟩ end order_properties protected theorem lt_wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, begin let ι := {c : cardinal // ¬ acc (<) c}, let f : ι → cardinal := subtype.val, haveI hι : nonempty ι := ⟨⟨_, h⟩⟩, obtain ⟨⟨c : cardinal, hc : ¬acc (<) c⟩, ⟨h_1 : Π j, (f ⟨c, hc⟩).out ↪ (f j).out⟩⟩ := embedding.min_injective (λ i, (f i).out), apply hc (acc.intro _ (λ j h', classical.by_contradiction (λ hj, h'.2 _))), have : #_ ≤ #_ := ⟨h_1 ⟨j, hj⟩⟩, simpa only [f, mk_out] using this end⟩ instance : has_well_founded cardinal.{u} := ⟨(<), cardinal.lt_wf⟩ instance : well_founded_lt cardinal.{u} := ⟨cardinal.lt_wf⟩ instance wo : @is_well_order cardinal.{u} (<) := { } instance : conditionally_complete_linear_order_bot cardinal := is_well_order.conditionally_complete_linear_order_bot _ @[simp] theorem Inf_empty : Inf (∅ : set cardinal.{u}) = 0 := dif_neg not_nonempty_empty /-- Note that the successor of `c` is not the same as `c + 1` except in the case of finite `c`. -/ instance : succ_order cardinal := succ_order.of_succ_le_iff (λ c, Inf {c' | c < c'}) (λ a b, ⟨lt_of_lt_of_le $ Inf_mem $ exists_gt a, cInf_le'⟩) theorem succ_def (c : cardinal) : succ c = Inf {c' | c < c'} := rfl theorem add_one_le_succ (c : cardinal.{u}) : c + 1 ≤ succ c := begin refine (le_cInf_iff'' (exists_gt c)).2 (λ b hlt, _), rcases ⟨b, c⟩ with ⟨⟨β⟩, ⟨γ⟩⟩, cases le_of_lt hlt with f, have : ¬ surjective f := λ hn, (not_le_of_lt hlt) (mk_le_of_surjective hn), simp only [surjective, not_forall] at this, rcases this with ⟨b, hb⟩, calc #γ + 1 = #(option γ) : mk_option.symm ... ≤ #β : (f.option_elim b hb).cardinal_le end lemma succ_pos : ∀ c : cardinal, 0 < succ c := bot_lt_succ lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := (succ_pos _).ne' /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem mk_sigma {ι} (f : ι → Type*) : #(Σ i, f i) = sum (λ i, #(f i)) := mk_congr $ equiv.sigma_congr_right $ λ i, out_mk_equiv.symm @[simp] theorem sum_const (ι : Type u) (a : cardinal.{v}) : sum (λ i : ι, a) = lift.{v} (#ι) * lift.{u} a := induction_on a $ λ α, mk_congr $ calc (Σ i : ι, quotient.out (#α)) ≃ ι × quotient.out (#α) : equiv.sigma_equiv_prod _ _ ... ≃ ulift ι × ulift α : equiv.ulift.symm.prod_congr (out_mk_equiv.trans equiv.ulift.symm) theorem sum_const' (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = #ι * a := by simp @[simp] theorem sum_add_distrib {ι} (f g : ι → cardinal) : sum (f + g) = sum f + sum g := by simpa only [mk_sigma, mk_sum, mk_out, lift_id] using mk_congr (equiv.sigma_sum_distrib (quotient.out ∘ f) (quotient.out ∘ g)) @[simp] theorem sum_add_distrib' {ι} (f g : ι → cardinal) : cardinal.sum (λ i, f i + g i) = sum f + sum g := sum_add_distrib f g @[simp] theorem lift_sum {ι : Type u} (f : ι → cardinal.{v}) : cardinal.lift.{w} (cardinal.sum f) = cardinal.sum (λ i, cardinal.lift.{w} (f i)) := equiv.cardinal_eq $ equiv.ulift.trans $ equiv.sigma_congr_right $ λ a, nonempty.some $ by rw [←lift_mk_eq, mk_out, mk_out, lift_lift] theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ lemma mk_le_mk_mul_of_mk_preimage_le {c : cardinal} (f : α → β) (hf : ∀ b : β, #(f ⁻¹' {b}) ≤ c) : #α ≤ #β * c := by simpa only [←mk_congr (@equiv.sigma_fiber_equiv α β f), mk_sigma, ←sum_const'] using sum_le_sum _ _ hf /-- The range of an indexed cardinal function, whose outputs live in a higher universe than the inputs, is always bounded above. -/ theorem bdd_above_range {ι : Type u} (f : ι → cardinal.{max u v}) : bdd_above (set.range f) := ⟨_, by { rintros a ⟨i, rfl⟩, exact le_sum f i }⟩ instance (a : cardinal.{u}) : small.{u} (set.Iic a) := begin rw ←mk_out a, apply @small_of_surjective (set a.out) (Iic (#a.out)) _ (λ x, ⟨#x, mk_set_le x⟩), rintro ⟨x, hx⟩, simpa using le_mk_iff_exists_set.1 hx end instance (a : cardinal.{u}) : small.{u} (set.Iio a) := small_subset Iio_subset_Iic_self /-- A set of cardinals is bounded above iff it's small, i.e. it corresponds to an usual ZFC set. -/ theorem bdd_above_iff_small {s : set cardinal.{u}} : bdd_above s ↔ small.{u} s := ⟨λ ⟨a, ha⟩, @small_subset _ (Iic a) s (λ x h, ha h) _, begin rintro ⟨ι, ⟨e⟩⟩, suffices : range (λ x : ι, (e.symm x).1) = s, { rw ←this, apply bdd_above_range.{u u} }, ext x, refine ⟨_, λ hx, ⟨e ⟨x, hx⟩, _⟩⟩, { rintro ⟨a, rfl⟩, exact (e.symm a).prop }, { simp_rw [subtype.val_eq_coe, equiv.symm_apply_apply], refl } end⟩ theorem bdd_above_of_small (s : set cardinal.{u}) [h : small.{u} s] : bdd_above s := bdd_above_iff_small.2 h theorem bdd_above_image (f : cardinal.{u} → cardinal.{max u v}) {s : set cardinal.{u}} (hs : bdd_above s) : bdd_above (f '' s) := by { rw bdd_above_iff_small at hs ⊢, exactI small_lift _ } theorem bdd_above_range_comp {ι : Type u} {f : ι → cardinal.{v}} (hf : bdd_above (range f)) (g : cardinal.{v} → cardinal.{max v w}) : bdd_above (range (g ∘ f)) := by { rw range_comp, exact bdd_above_image g hf } theorem supr_le_sum {ι} (f : ι → cardinal) : supr f ≤ sum f := csupr_le' $ le_sum _ theorem sum_le_supr_lift {ι : Type u} (f : ι → cardinal.{max u v}) : sum f ≤ (#ι).lift * supr f := begin rw [←(supr f).lift_id, ←lift_umax, lift_umax.{(max u v) u}, ←sum_const], exact sum_le_sum _ _ (le_csupr $ bdd_above_range.{u v} f) end theorem sum_le_supr {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ #ι * supr f := by { rw ←lift_id (#ι), exact sum_le_supr_lift f } theorem sum_nat_eq_add_sum_succ (f : ℕ → cardinal.{u}) : cardinal.sum f = f 0 + cardinal.sum (λ i, f (i + 1)) := begin refine (equiv.sigma_nat_succ (λ i, quotient.out (f i))).cardinal_eq.trans _, simp only [mk_sum, mk_out, lift_id, mk_sigma], end /-- A variant of `csupr_of_empty` but with `0` on the RHS for convenience -/ @[simp] protected theorem supr_of_empty {ι} (f : ι → cardinal) [is_empty ι] : supr f = 0 := csupr_of_empty f @[simp] lemma lift_mk_shrink (α : Type u) [small.{v} α] : cardinal.lift.{max u w} (# (shrink.{v} α)) = cardinal.lift.{max v w} (# α) := lift_mk_eq.2 ⟨(equiv_shrink α).symm⟩ @[simp] lemma lift_mk_shrink' (α : Type u) [small.{v} α] : cardinal.lift.{u} (# (shrink.{v} α)) = cardinal.lift.{v} (# α) := lift_mk_shrink.{u v 0} α @[simp] lemma lift_mk_shrink'' (α : Type (max u v)) [small.{v} α] : cardinal.lift.{u} (# (shrink.{v} α)) = # α := by rw [← lift_umax', lift_mk_shrink.{(max u v) v 0} α, ← lift_umax, lift_id] /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := #(Π i, (f i).out) @[simp] theorem mk_pi {ι : Type u} (α : ι → Type v) : #(Π i, α i) = prod (λ i, #(α i)) := mk_congr $ equiv.Pi_congr_right $ λ i, out_mk_equiv.symm @[simp] theorem prod_const (ι : Type u) (a : cardinal.{v}) : prod (λ i : ι, a) = lift.{u} a ^ lift.{v} (#ι) := induction_on a $ λ α, mk_congr $ equiv.Pi_congr equiv.ulift.symm $ λ i, out_mk_equiv.trans equiv.ulift.symm theorem prod_const' (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ #ι := induction_on a $ λ α, (mk_pi _).symm theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ @[simp] theorem prod_eq_zero {ι} (f : ι → cardinal.{u}) : prod f = 0 ↔ ∃ i, f i = 0 := by { lift f to ι → Type u using λ _, trivial, simp only [mk_eq_zero_iff, ← mk_pi, is_empty_pi] } theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := by simp [prod_eq_zero] @[simp] theorem lift_prod {ι : Type u} (c : ι → cardinal.{v}) : lift.{w} (prod c) = prod (λ i, lift.{w} (c i)) := begin lift c to ι → Type v using λ _, trivial, simp only [← mk_pi, ← mk_ulift], exact mk_congr (equiv.ulift.trans $ equiv.Pi_congr_right $ λ i, equiv.ulift.symm) end lemma prod_eq_of_fintype {α : Type u} [fintype α] (f : α → cardinal.{v}) : prod f = cardinal.lift.{u} (∏ i, f i) := begin revert f, refine fintype.induction_empty_option _ _ _ α, { introsI α β hβ e h f, letI := fintype.of_equiv β e.symm, rw [←e.prod_comp f, ←h], exact mk_congr (e.Pi_congr_left _).symm }, { intro f, rw [fintype.univ_pempty, finset.prod_empty, lift_one, cardinal.prod, mk_eq_one] }, { intros α hα h f, rw [cardinal.prod, mk_congr equiv.pi_option_equiv_prod, mk_prod, lift_umax', mk_out, ←cardinal.prod, lift_prod, fintype.prod_option, lift_mul, ←h (λ a, f (some a))], simp only [lift_id] }, end @[simp] theorem lift_Inf (s : set cardinal) : lift (Inf s) = Inf (lift '' s) := begin rcases eq_empty_or_nonempty s with rfl | hs, { simp }, { exact lift_monotone.map_Inf hs } end @[simp] theorem lift_infi {ι} (f : ι → cardinal) : lift (infi f) = ⨅ i, lift (f i) := by { unfold infi, convert lift_Inf (range f), rw range_comp } theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := induction_on₂ a b $ λ α β, by rw [← lift_id (#β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨#(set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down h.le in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ_iff, ← lift_le, e] at h, exact h.not_lt (lt_succ _) end) (succ_le_of_lt $ lift_lt.2 $ lt_succ a) @[simp] theorem lift_umax_eq {a : cardinal.{u}} {b : cardinal.{v}} : lift.{max v w} a = lift.{max u w} b ↔ lift.{v} a = lift.{u} b := by rw [←lift_lift, ←lift_lift, lift_inj] @[simp] theorem lift_min {a b : cardinal} : lift (min a b) = min (lift a) (lift b) := lift_monotone.map_min @[simp] theorem lift_max {a b : cardinal} : lift (max a b) = max (lift a) (lift b) := lift_monotone.map_max /-- The lift of a supremum is the supremum of the lifts. -/ lemma lift_Sup {s : set cardinal} (hs : bdd_above s) : lift.{u} (Sup s) = Sup (lift.{u} '' s) := begin apply ((le_cSup_iff' (bdd_above_image _ hs)).2 (λ c hc, _)).antisymm (cSup_le' _), { by_contra h, obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.1 h).le, simp_rw lift_le at h hc, rw cSup_le_iff' hs at h, exact h (λ a ha, lift_le.1 $ hc (mem_image_of_mem _ ha)) }, { rintros i ⟨j, hj, rfl⟩, exact lift_le.2 (le_cSup hs hj) }, end /-- The lift of a supremum is the supremum of the lifts. -/ lemma lift_supr {ι : Type v} {f : ι → cardinal.{w}} (hf : bdd_above (range f)) : lift.{u} (supr f) = ⨆ i, lift.{u} (f i) := by rw [supr, supr, lift_Sup hf, ←range_comp] /-- To prove that the lift of a supremum is bounded by some cardinal `t`, it suffices to show that the lift of each cardinal is bounded by `t`. -/ lemma lift_supr_le {ι : Type v} {f : ι → cardinal.{w}} {t : cardinal} (hf : bdd_above (range f)) (w : ∀ i, lift.{u} (f i) ≤ t) : lift.{u} (supr f) ≤ t := by { rw lift_supr hf, exact csupr_le' w } @[simp] lemma lift_supr_le_iff {ι : Type v} {f : ι → cardinal.{w}} (hf : bdd_above (range f)) {t : cardinal} : lift.{u} (supr f) ≤ t ↔ ∀ i, lift.{u} (f i) ≤ t := by { rw lift_supr hf, exact csupr_le_iff' (bdd_above_range_comp hf _) } universes v' w' /-- To prove an inequality between the lifts to a common universe of two different supremums, it suffices to show that the lift of each cardinal from the smaller supremum if bounded by the lift of some cardinal from the larger supremum. -/ lemma lift_supr_le_lift_supr {ι : Type v} {ι' : Type v'} {f : ι → cardinal.{w}} {f' : ι' → cardinal.{w'}} (hf : bdd_above (range f)) (hf' : bdd_above (range f')) {g : ι → ι'} (h : ∀ i, lift.{w'} (f i) ≤ lift.{w} (f' (g i))) : lift.{w'} (supr f) ≤ lift.{w} (supr f') := begin rw [lift_supr hf, lift_supr hf'], exact csupr_mono' (bdd_above_range_comp hf' _) (λ i, ⟨_, h i⟩) end /-- A variant of `lift_supr_le_lift_supr` with universes specialized via `w = v` and `w' = v'`. This is sometimes necessary to avoid universe unification issues. -/ lemma lift_supr_le_lift_supr' {ι : Type v} {ι' : Type v'} {f : ι → cardinal.{v}} {f' : ι' → cardinal.{v'}} (hf : bdd_above (range f)) (hf' : bdd_above (range f')) (g : ι → ι') (h : ∀ i, lift.{v'} (f i) ≤ lift.{v} (f' (g i))) : lift.{v'} (supr f) ≤ lift.{v} (supr f') := lift_supr_le_lift_supr hf hf' h /-- `ℵ₀` is the smallest infinite cardinal. -/ def aleph_0 : cardinal.{u} := lift (#ℕ) localized "notation (name := cardinal.aleph_0) `ℵ₀` := cardinal.aleph_0" in cardinal lemma mk_nat : #ℕ = ℵ₀ := (lift_id _).symm theorem aleph_0_ne_zero : ℵ₀ ≠ 0 := mk_ne_zero _ theorem aleph_0_pos : 0 < ℵ₀ := pos_iff_ne_zero.2 aleph_0_ne_zero @[simp] theorem lift_aleph_0 : lift ℵ₀ = ℵ₀ := lift_lift _ @[simp] theorem aleph_0_le_lift {c : cardinal.{u}} : ℵ₀ ≤ lift.{v} c ↔ ℵ₀ ≤ c := by rw [←lift_aleph_0, lift_le] @[simp] theorem lift_le_aleph_0 {c : cardinal.{u}} : lift.{v} c ≤ ℵ₀ ↔ c ≤ ℵ₀ := by rw [←lift_aleph_0, lift_le] /-! ### Properties about the cast from `ℕ` -/ @[simp] theorem mk_fin (n : ℕ) : #(fin n) = n := by simp @[simp] theorem lift_nat_cast (n : ℕ) : lift.{u} (n : cardinal.{v}) = n := by induction n; simp * @[simp] lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{v} a = n ↔ a = n := lift_injective.eq_iff' (lift_nat_cast n) @[simp] lemma nat_eq_lift_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{v} a ↔ (n : cardinal) = a := by rw [←lift_nat_cast.{v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (#(fin n)) = n := by simp lemma mk_coe_finset {α : Type u} {s : finset α} : #s = ↑(finset.card s) := by simp lemma mk_finset_of_fintype [fintype α] : #(finset α) = 2 ^ℕ fintype.card α := by simp @[simp] lemma mk_finsupp_lift_of_fintype (α : Type u) (β : Type v) [fintype α] [has_zero β] : #(α →₀ β) = lift.{u} (#β) ^ℕ fintype.card α := by simpa using (@finsupp.equiv_fun_on_fintype α β _ _).cardinal_eq lemma mk_finsupp_of_fintype (α β : Type u) [fintype α] [has_zero β] : #(α →₀ β) = (#β) ^ℕ fintype.card α := by simp theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ #α := begin rw (_ : (s.card : cardinal) = #s), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.mk_fintype, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := begin rw [←lift_mk_fin, ←lift_mk_fin, lift_le], exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ end @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, ←not_le] instance : char_zero cardinal := ⟨strict_mono.injective $ λ m n, nat_cast_lt.2⟩ theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := nat.cast_inj lemma nat_cast_injective : injective (coe : ℕ → cardinal) := nat.cast_injective @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := (add_one_le_succ _).antisymm (succ_le_of_lt $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ (0 : cardinal) = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine le_of_lt_succ (lt_of_not_ge $ λ hn, _), rw [←cardinal.nat_succ, ←lift_mk_fin n.succ] at hn, cases hn with f, refine (H $ finset.univ.map f).not_lt _, rw [finset.card_map, ←fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := begin rw [←succ_le_iff, (by norm_cast : succ (1 : cardinal) = 2)] at hb, exact (cantor a).trans_le (power_le_power_right hb) end theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [←succ_zero, succ_le_iff] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_aleph_0 (n : ℕ) : (n : cardinal.{u}) < ℵ₀ := succ_le_iff.1 begin rw [←nat_succ, ←lift_mk_fin, aleph_0, lift_mk_le.{0 0 u}], exact ⟨⟨coe, λ a b, fin.ext⟩⟩ end @[simp] theorem one_lt_aleph_0 : 1 < ℵ₀ := by simpa using nat_lt_aleph_0 1 theorem one_le_aleph_0 : 1 ≤ ℵ₀ := one_lt_aleph_0.le theorem lt_aleph_0 {c : cardinal} : c < ℵ₀ ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : S.finite, { lift S to finset ℕ using this, simp }, contrapose! h', haveI := infinite.to_subtype h', exact ⟨infinite.nat_embedding S⟩ end, λ ⟨n, e⟩, e.symm ▸ nat_lt_aleph_0 _⟩ theorem aleph_0_le {c : cardinal} : ℵ₀ ≤ c ↔ ∀ n : ℕ, ↑n ≤ c := ⟨λ h n, (nat_lt_aleph_0 _).le.trans h, λ h, le_of_not_lt $ λ hn, begin rcases lt_aleph_0.1 hn with ⟨n, rfl⟩, exact (nat.lt_succ_self _).not_le (nat_cast_le.1 (h (n+1))) end⟩ theorem mk_eq_nat_iff {α : Type u} {n : ℕ} : #α = n ↔ nonempty (α ≃ fin n) := by rw [← lift_mk_fin, ← lift_uzero (#α), lift_mk_eq'] theorem lt_aleph_0_iff_finite {α : Type u} : #α < ℵ₀ ↔ finite α := by simp only [lt_aleph_0, mk_eq_nat_iff, finite_iff_exists_equiv_fin] theorem lt_aleph_0_iff_fintype {α : Type u} : #α < ℵ₀ ↔ nonempty (fintype α) := lt_aleph_0_iff_finite.trans (finite_iff_nonempty_fintype _) theorem lt_aleph_0_of_finite (α : Type u) [finite α] : #α < ℵ₀ := lt_aleph_0_iff_finite.2 ‹_› @[simp] theorem lt_aleph_0_iff_set_finite {S : set α} : #S < ℵ₀ ↔ S.finite := lt_aleph_0_iff_finite.trans finite_coe_iff alias lt_aleph_0_iff_set_finite ↔ _ _root_.set.finite.lt_aleph_0 @[simp] theorem lt_aleph_0_iff_subtype_finite {p : α → Prop} : #{x // p x} < ℵ₀ ↔ {x | p x}.finite := lt_aleph_0_iff_set_finite lemma mk_le_aleph_0_iff : #α ≤ ℵ₀ ↔ countable α := by rw [countable_iff_nonempty_embedding, aleph_0, ← lift_uzero (#α), lift_mk_le'] @[simp] lemma mk_le_aleph_0 [countable α] : #α ≤ ℵ₀ := mk_le_aleph_0_iff.mpr ‹_› @[simp] lemma le_aleph_0_iff_set_countable {s : set α} : #s ≤ ℵ₀ ↔ s.countable := by rw [mk_le_aleph_0_iff, countable_coe_iff] alias le_aleph_0_iff_set_countable ↔ _ _root_.set.countable.le_aleph_0 @[simp] lemma le_aleph_0_iff_subtype_countable {p : α → Prop} : #{x // p x} ≤ ℵ₀ ↔ {x | p x}.countable := le_aleph_0_iff_set_countable instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < ℵ₀, λ x hx, let ⟨n, hn⟩ := lt_aleph_0.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_aleph_0 {a b : cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a + b < ℵ₀ := match a, b, lt_aleph_0.1 ha, lt_aleph_0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_aleph_0 end lemma add_lt_aleph_0_iff {a b : cardinal} : a + b < ℵ₀ ↔ a < ℵ₀ ∧ b < ℵ₀ := ⟨λ h, ⟨(self_le_add_right _ _).trans_lt h, (self_le_add_left _ _).trans_lt h⟩, λ ⟨h1, h2⟩, add_lt_aleph_0 h1 h2⟩ lemma aleph_0_le_add_iff {a b : cardinal} : ℵ₀ ≤ a + b ↔ ℵ₀ ≤ a ∨ ℵ₀ ≤ b := by simp only [←not_lt, add_lt_aleph_0_iff, not_and_distrib] /-- See also `cardinal.nsmul_lt_aleph_0_iff_of_ne_zero` if you already have `n ≠ 0`. -/ lemma nsmul_lt_aleph_0_iff {n : ℕ} {a : cardinal} : n • a < ℵ₀ ↔ n = 0 ∨ a < ℵ₀ := begin cases n, { simpa using nat_lt_aleph_0 0 }, simp only [nat.succ_ne_zero, false_or], induction n with n ih, { simp }, rw [succ_nsmul, add_lt_aleph_0_iff, ih, and_self] end /-- See also `cardinal.nsmul_lt_aleph_0_iff` for a hypothesis-free version. -/ lemma nsmul_lt_aleph_0_iff_of_ne_zero {n : ℕ} {a : cardinal} (h : n ≠ 0) : n • a < ℵ₀ ↔ a < ℵ₀ := nsmul_lt_aleph_0_iff.trans $ or_iff_right h theorem mul_lt_aleph_0 {a b : cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a * b < ℵ₀ := match a, b, lt_aleph_0.1 ha, lt_aleph_0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_aleph_0 end lemma mul_lt_aleph_0_iff {a b : cardinal} : a * b < ℵ₀ ↔ a = 0 ∨ b = 0 ∨ a < ℵ₀ ∧ b < ℵ₀ := begin refine ⟨λ h, _, _⟩, { by_cases ha : a = 0, { exact or.inl ha }, right, by_cases hb : b = 0, { exact or.inl hb }, right, rw [←ne, ←one_le_iff_ne_zero] at ha hb, split, { rw ←mul_one a, refine (mul_le_mul' le_rfl hb).trans_lt h }, { rw ←one_mul b, refine (mul_le_mul' ha le_rfl).trans_lt h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_aleph_0, aleph_0_pos, zero_mul, mul_zero] end /-- See also `cardinal.aleph_0_le_mul_iff`. -/ lemma aleph_0_le_mul_iff {a b : cardinal} : ℵ₀ ≤ a * b ↔ a ≠ 0 ∧ b ≠ 0 ∧ (ℵ₀ ≤ a ∨ ℵ₀ ≤ b) := let h := (@mul_lt_aleph_0_iff a b).not in by rwa [not_lt, not_or_distrib, not_or_distrib, not_and_distrib, not_lt, not_lt] at h /-- See also `cardinal.aleph_0_le_mul_iff'`. -/ lemma aleph_0_le_mul_iff' {a b : cardinal.{u}} : ℵ₀ ≤ a * b ↔ a ≠ 0 ∧ ℵ₀ ≤ b ∨ ℵ₀ ≤ a ∧ b ≠ 0 := begin have : ∀ {a : cardinal.{u}}, ℵ₀ ≤ a → a ≠ 0, from λ a, ne_bot_of_le_ne_bot aleph_0_ne_zero, simp only [aleph_0_le_mul_iff, and_or_distrib_left, and_iff_right_of_imp this, @and.left_comm (a ≠ 0)], simp only [and.comm, or.comm] end lemma mul_lt_aleph_0_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < ℵ₀ ↔ a < ℵ₀ ∧ b < ℵ₀ := by simp [mul_lt_aleph_0_iff, ha, hb] theorem power_lt_aleph_0 {a b : cardinal} (ha : a < ℵ₀) (hb : b < ℵ₀) : a ^ b < ℵ₀ := match a, b, lt_aleph_0.1 ha, lt_aleph_0.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_aleph_0 end lemma eq_one_iff_unique {α : Type*} : #α = 1 ↔ subsingleton α ∧ nonempty α := calc #α = 1 ↔ #α ≤ 1 ∧ 1 ≤ #α : le_antisymm_iff ... ↔ subsingleton α ∧ nonempty α : le_one_iff_subsingleton.and (one_le_iff_ne_zero.trans mk_ne_zero_iff) theorem infinite_iff {α : Type u} : infinite α ↔ ℵ₀ ≤ #α := by rw [← not_lt, lt_aleph_0_iff_finite, not_finite_iff_infinite] @[simp] lemma aleph_0_le_mk (α : Type u) [infinite α] : ℵ₀ ≤ #α := infinite_iff.1 ‹_› lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ #α = ℵ₀ := ⟨λ ⟨h⟩, mk_congr ((@denumerable.eqv α h).trans equiv.ulift.symm), λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ @[simp] lemma mk_denumerable (α : Type u) [denumerable α] : #α = ℵ₀ := denumerable_iff.1 ⟨‹_›⟩ @[simp] lemma aleph_0_add_aleph_0 : ℵ₀ + ℵ₀ = ℵ₀ := mk_denumerable _ lemma aleph_0_mul_aleph_0 : ℵ₀ * ℵ₀ = ℵ₀ := mk_denumerable _ @[simp] lemma add_le_aleph_0 {c₁ c₂ : cardinal} : c₁ + c₂ ≤ ℵ₀ ↔ c₁ ≤ ℵ₀ ∧ c₂ ≤ ℵ₀ := ⟨λ h, ⟨le_self_add.trans h, le_add_self.trans h⟩, λ h, aleph_0_add_aleph_0 ▸ add_le_add h.1 h.2⟩ /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < aleph_0.{v} then classical.some (lt_aleph_0.1 h) else 0, begin have h : 0 < ℵ₀ := nat_lt_aleph_0 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_aleph_0.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_aleph_0 {c : cardinal} (h : c < ℵ₀) : c.to_nat = classical.some (lt_aleph_0.1 h) := dif_pos h lemma to_nat_apply_of_aleph_0_le {c : cardinal} (h : ℵ₀ ≤ c) : c.to_nat = 0 := dif_neg h.not_lt lemma cast_to_nat_of_lt_aleph_0 {c : cardinal} (h : c < ℵ₀) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_aleph_0 h, ← classical.some_spec (lt_aleph_0.1 h)] lemma cast_to_nat_of_aleph_0_le {c : cardinal} (h : ℵ₀ ≤ c) : ↑c.to_nat = (0 : cardinal) := by rw [to_nat_apply_of_aleph_0_le h, nat.cast_zero] lemma to_nat_le_iff_le_of_lt_aleph_0 {c d : cardinal} (hc : c < ℵ₀) (hd : d < ℵ₀) : c.to_nat ≤ d.to_nat ↔ c ≤ d := by rw [←nat_cast_le, cast_to_nat_of_lt_aleph_0 hc, cast_to_nat_of_lt_aleph_0 hd] lemma to_nat_lt_iff_lt_of_lt_aleph_0 {c d : cardinal} (hc : c < ℵ₀) (hd : d < ℵ₀) : c.to_nat < d.to_nat ↔ c < d := by rw [←nat_cast_lt, cast_to_nat_of_lt_aleph_0 hc, cast_to_nat_of_lt_aleph_0 hd] lemma to_nat_le_of_le_of_lt_aleph_0 {c d : cardinal} (hd : d < ℵ₀) (hcd : c ≤ d) : c.to_nat ≤ d.to_nat := (to_nat_le_iff_le_of_lt_aleph_0 (hcd.trans_lt hd) hd).mpr hcd lemma to_nat_lt_of_lt_of_lt_aleph_0 {c d : cardinal} (hd : d < ℵ₀) (hcd : c < d) : c.to_nat < d.to_nat := (to_nat_lt_iff_lt_of_lt_aleph_0 (hcd.trans hd) hd).mpr hcd @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_aleph_0 (nat_lt_aleph_0 n), ← nat_cast_inj], exact (classical.some_spec (lt_aleph_0.1 (nat_lt_aleph_0 n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (#α).to_nat = 0 := dif_neg (infinite_iff.1 h).not_lt @[simp] theorem aleph_0_to_nat : to_nat ℵ₀ = 0 := to_nat_apply_of_aleph_0_le le_rfl lemma mk_to_nat_eq_card [fintype α] : (#α).to_nat = fintype.card α := by simp @[simp] lemma zero_to_nat : to_nat 0 = 0 := by rw [←to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : to_nat 1 = 1 := by rw [←to_nat_cast 1, nat.cast_one] @[simp] lemma to_nat_eq_one {c : cardinal} : to_nat c = 1 ↔ c = 1 := ⟨λ h, (cast_to_nat_of_lt_aleph_0 (lt_of_not_ge (one_ne_zero ∘ h.symm.trans ∘ to_nat_apply_of_aleph_0_le))).symm.trans ((congr_arg coe h).trans nat.cast_one), λ h, (congr_arg to_nat h).trans one_to_nat⟩ lemma to_nat_eq_one_iff_unique {α : Type*} : (#α).to_nat = 1 ↔ subsingleton α ∧ nonempty α := to_nat_eq_one.trans eq_one_iff_unique @[simp] lemma to_nat_lift (c : cardinal.{v}) : (lift.{u v} c).to_nat = c.to_nat := begin apply nat_cast_injective, cases lt_or_ge c ℵ₀ with hc hc, { rw [cast_to_nat_of_lt_aleph_0, ←lift_nat_cast, cast_to_nat_of_lt_aleph_0 hc], rwa [←lift_aleph_0, lift_lt] }, { rw [cast_to_nat_of_aleph_0_le, ←lift_nat_cast, cast_to_nat_of_aleph_0_le hc, lift_zero], rwa [←lift_aleph_0, lift_le] }, end lemma to_nat_congr {β : Type v} (e : α ≃ β) : (#α).to_nat = (#β).to_nat := by rw [←to_nat_lift, lift_mk_eq.mpr ⟨e⟩, to_nat_lift] @[simp] lemma to_nat_mul (x y : cardinal) : (x * y).to_nat = x.to_nat * y.to_nat := begin rcases eq_or_ne x 0 with rfl | hx1, { rw [zero_mul, zero_to_nat, zero_mul] }, rcases eq_or_ne y 0 with rfl | hy1, { rw [mul_zero, zero_to_nat, mul_zero] }, cases lt_or_le x ℵ₀ with hx2 hx2, { cases lt_or_le y ℵ₀ with hy2 hy2, { lift x to ℕ using hx2, lift y to ℕ using hy2, rw [← nat.cast_mul, to_nat_cast, to_nat_cast, to_nat_cast] }, { rw [to_nat_apply_of_aleph_0_le hy2, mul_zero, to_nat_apply_of_aleph_0_le], exact aleph_0_le_mul_iff'.2 (or.inl ⟨hx1, hy2⟩) } }, { rw [to_nat_apply_of_aleph_0_le hx2, zero_mul, to_nat_apply_of_aleph_0_le], exact aleph_0_le_mul_iff'.2 (or.inr ⟨hx2, hy1⟩) }, end /-- `cardinal.to_nat` as a `monoid_with_zero_hom`. -/ @[simps] def to_nat_hom : cardinal →*₀ ℕ := { to_fun := to_nat, map_zero' := zero_to_nat, map_one' := one_to_nat, map_mul' := to_nat_mul } lemma to_nat_finset_prod (s : finset α) (f : α → cardinal) : to_nat (∏ i in s, f i) = ∏ i in s, to_nat (f i) := map_prod to_nat_hom _ _ @[simp] lemma to_nat_add_of_lt_aleph_0 {a : cardinal.{u}} {b : cardinal.{v}} (ha : a < ℵ₀) (hb : b < ℵ₀) : ((lift.{v u} a) + (lift.{u v} b)).to_nat = a.to_nat + b.to_nat := begin apply cardinal.nat_cast_injective, replace ha : (lift.{v u} a) < ℵ₀ := by { rw ←lift_aleph_0, exact lift_lt.2 ha }, replace hb : (lift.{u v} b) < ℵ₀ := by { rw ←lift_aleph_0, exact lift_lt.2 hb }, rw [nat.cast_add, ←to_nat_lift.{v u} a, ←to_nat_lift.{u v} b, cast_to_nat_of_lt_aleph_0 ha, cast_to_nat_of_lt_aleph_0 hb, cast_to_nat_of_lt_aleph_0 (add_lt_aleph_0 ha hb)] end /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ def to_part_enat : cardinal →+ part_enat := { to_fun := λ c, if c < ℵ₀ then c.to_nat else ⊤, map_zero' := by simp [if_pos (zero_lt_one.trans one_lt_aleph_0)], map_add' := λ x y, begin by_cases hx : x < ℵ₀, { obtain ⟨x0, rfl⟩ := lt_aleph_0.1 hx, by_cases hy : y < ℵ₀, { obtain ⟨y0, rfl⟩ := lt_aleph_0.1 hy, simp only [add_lt_aleph_0 hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, nat.cast_add] }, { rw [if_neg hy, if_neg, part_enat.add_top], contrapose! hy, apply le_add_self.trans_lt hy } }, { rw [if_neg hx, if_neg, part_enat.top_add], contrapose! hx, apply le_self_add.trans_lt hx }, end } lemma to_part_enat_apply_of_lt_aleph_0 {c : cardinal} (h : c < ℵ₀) : c.to_part_enat = c.to_nat := if_pos h lemma to_part_enat_apply_of_aleph_0_le {c : cardinal} (h : ℵ₀ ≤ c) : c.to_part_enat = ⊤ := if_neg h.not_lt @[simp] lemma to_part_enat_cast (n : ℕ) : cardinal.to_part_enat n = n := by rw [to_part_enat_apply_of_lt_aleph_0 (nat_lt_aleph_0 n), to_nat_cast] @[simp] lemma mk_to_part_enat_of_infinite [h : infinite α] : (#α).to_part_enat = ⊤ := to_part_enat_apply_of_aleph_0_le (infinite_iff.1 h) @[simp] theorem aleph_0_to_part_enat : to_part_enat ℵ₀ = ⊤ := to_part_enat_apply_of_aleph_0_le le_rfl lemma to_part_enat_surjective : surjective to_part_enat := λ x, part_enat.cases_on x ⟨ℵ₀, to_part_enat_apply_of_aleph_0_le le_rfl⟩ $ λ n, ⟨n, to_part_enat_cast n⟩ lemma mk_to_part_enat_eq_coe_card [fintype α] : (#α).to_part_enat = fintype.card α := by simp lemma mk_int : #ℤ = ℵ₀ := mk_denumerable ℤ lemma mk_pnat : #ℕ+ = ℵ₀ := mk_denumerable ℕ+ /-- **König's theorem** -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin haveI : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ mk_ne_zero_iff.1 _⟩, rw mk_out, exact (H i).ne_bot }, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { intro i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, (H i).not_le _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : #empty = 0 := mk_eq_zero _ @[simp] theorem mk_pempty : #pempty = 0 := mk_eq_zero _ @[simp] theorem mk_punit : #punit = 1 := mk_eq_one punit theorem mk_unit : #unit = 1 := mk_punit @[simp] theorem mk_singleton {α : Type u} (x : α) : #({x} : set α) = 1 := mk_eq_one _ @[simp] theorem mk_plift_true : #(plift true) = 1 := mk_eq_one _ @[simp] theorem mk_plift_false : #(plift false) = 0 := mk_eq_zero _ @[simp] theorem mk_vector (α : Type u) (n : ℕ) : #(vector α n) = (#α) ^ℕ n := (mk_congr (equiv.vector_equiv_fin α n)).trans $ by simp theorem mk_list_eq_sum_pow (α : Type u) : #(list α) = sum (λ n : ℕ, (#α) ^ℕ n) := calc #(list α) = #(Σ n, vector α n) : mk_congr (equiv.sigma_fiber_equiv list.length).symm ... = sum (λ n : ℕ, (#α) ^ℕ n) : by simp theorem mk_quot_le {α : Type u} {r : α → α → Prop} : #(quot r) ≤ #α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : #(quotient s) ≤ #α := mk_quot_le theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : #(subtype p) ≤ #(subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : #(∅ : set α) = 0 := mk_eq_zero _ lemma mk_emptyc_iff {α : Type u} {s : set α} : #s = 0 ↔ s = ∅ := begin split, { intro h, rw mk_eq_zero_iff at h, exact eq_empty_iff_forall_not_mem.2 (λ x hx, h.elim' ⟨x, hx⟩) }, { rintro rfl, exact mk_emptyc _ } end @[simp] theorem mk_univ {α : Type u} : #(@univ α) = #α := mk_congr (equiv.set.univ α) theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : #(f '' s) ≤ #s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{u} (#(f '' s)) ≤ lift.{v} (#s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : #(range f) ≤ #α := mk_le_of_surjective surjective_onto_range theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} : lift.{u} (#(range f)) ≤ lift.{v} (#α) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩ lemma mk_range_eq (f : α → β) (h : injective f) : #(range f) = #α := mk_congr ((equiv.of_injective f h).symm) lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{u} (#(range f)) = lift.{v} (#α) := lift_mk_eq'.mpr ⟨(equiv.of_injective f hf).symm⟩ lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{max u w} (# (range f)) = lift.{max v w} (# α) := lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : #(f '' s) = #s := mk_congr ((equiv.set.image f s hf).symm) theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : #(⋃ i, f i) ≤ sum (λ i, #(f i)) := calc #(⋃ i, f i) ≤ #(Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, #(f i)) : mk_sigma _ theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : #(⋃ i, f i) = sum (λ i, #(f i)) := calc #(⋃ i, f i) = #(Σ i, f i) : mk_congr (set.Union_eq_sigma_of_disjoint h) ... = sum (λi, #(f i)) : mk_sigma _ lemma mk_Union_le {α ι : Type u} (f : ι → set α) : #(⋃ i, f i) ≤ #ι * ⨆ i, #(f i) := mk_Union_le_sum_mk.trans (sum_le_supr _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : #(⋃₀ A) ≤ #A * ⨆ s : A, #s := by { rw sUnion_eq_Union, apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : #(⋃ x ∈ s, A x) ≤ #s * ⨆ x : s, #(A x.1) := by { rw bUnion_eq_Union, apply mk_Union_le } lemma finset_card_lt_aleph_0 (s : finset α) : #(↑s : set α) < ℵ₀ := lt_aleph_0_of_finite _ theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} : #s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n := begin split, { intro h, lift s to finset α using lt_aleph_0_iff_set_finite.1 (h.symm ▸ nat_lt_aleph_0 n), simpa using h }, { rintro ⟨t, rfl, rfl⟩, exact mk_coe_finset } end theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : #(S ∪ T : set α) + #(S ∩ T : set α) = #S + #T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : #(S ∪ T : set α) ≤ #S + #T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (#(S ∪ T : set α)) (#(S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : #(S ∪ T : set α) = #S + #T := quot.sound ⟨equiv.set.union H⟩ theorem mk_insert {α : Type u} {s : set α} {a : α} (h : a ∉ s) : #(insert a s : set α) = #s + 1 := by { rw [← union_singleton, mk_union_of_disjoint, mk_singleton], simpa } lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := mk_congr (equiv.set.sum_compl s) lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : #s ≤ #t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀ x, p x → q x) : #{x // p x} ≤ #{x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_union_le_aleph_0 {α} {P Q : set α} : #((P ∪ Q : set α)) ≤ ℵ₀ ↔ #P ≤ ℵ₀ ∧ #Q ≤ ℵ₀ := by simp lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{u} (#(f '' s)) = lift.{v} (#s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{u} (#(f '' s)) = lift.{v} (#s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : #(f '' s) = #s := mk_congr ((equiv.set.image_of_inj_on f s h).symm) lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : #{a : α // p (e a)} = #{b : β // p b} := mk_congr (equiv.subtype_equiv_of_subtype e) lemma mk_sep (s : set α) (t : α → Prop) : #({ x ∈ s | t x } : set α) = #{ x : s | t x.1 } := mk_congr (equiv.set.sep s t) lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{v} (#(f ⁻¹' s)) ≤ lift.{u} (#s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{u} (#s) ≤ lift.{v} (#(f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{v} (#(f ⁻¹' s)) = lift.{u} (#s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : #(f ⁻¹' s) ≤ #s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : #s ≤ #(f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : #(f ⁻¹' s) = #s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{u} (#t) ≤ lift.{v} (#({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : #t ≤ #({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ #s ↔ ∃ p : set α, p ⊆ s ∧ #p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end lemma two_le_iff : (2 : cardinal) ≤ #α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ_iff, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ #α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end lemma exists_not_mem_of_length_le {α : Type*} (l : list α) (h : ↑l.length < # α) : ∃ (z : α), z ∉ l := begin contrapose! h, calc # α = # (set.univ : set α) : mk_univ.symm ... ≤ # l.to_finset : mk_le_mk_of_subset (λ x _, list.mem_to_finset.mpr (h x)) ... = l.to_finset.card : cardinal.mk_coe_finset ... ≤ l.length : cardinal.nat_cast_le.mpr (list.to_finset_card_le l), end lemma three_le {α : Type*} (h : 3 ≤ # α) (x : α) (y : α) : ∃ (z : α), z ≠ x ∧ z ≠ y := begin have : ↑(3 : ℕ) ≤ # α, simpa using h, have : ↑(2 : ℕ) < # α, rwa [← succ_le_iff, ← cardinal.nat_succ], have := exists_not_mem_of_length_le [x, y] this, simpa [not_or_distrib] using this, end /-- The function `a ^< b`, defined as the supremum of `a ^ c` for `c < b`. -/ def powerlt (a b : cardinal.{u}) : cardinal.{u} := ⨆ c : Iio b, a ^ c infix ` ^< `:80 := powerlt lemma le_powerlt {b c : cardinal.{u}} (a) (h : c < b) : a ^ c ≤ a ^< b := begin apply @le_csupr _ _ _ (λ y : Iio b, a ^ y) _ ⟨c, h⟩, rw ←image_eq_range, exact bdd_above_image.{u u} _ bdd_above_Iio end lemma powerlt_le {a b c : cardinal.{u}} : a ^< b ≤ c ↔ ∀ x < b, a ^ x ≤ c := begin rw [powerlt, csupr_le_iff'], { simp }, { rw ←image_eq_range, exact bdd_above_image.{u u} _ bdd_above_Iio } end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := powerlt_le.2 $ λ x hx, le_powerlt a $ hx.trans_le h lemma powerlt_mono_left (a) : monotone (λ c, a ^< c) := λ b c, powerlt_le_powerlt_left lemma powerlt_succ {a b : cardinal} (h : a ≠ 0) : a ^< (succ b) = a ^ b := (powerlt_le.2 $ λ c h', power_le_power_left h $ le_of_lt_succ h').antisymm $ le_powerlt a (lt_succ b) lemma powerlt_min {a b c : cardinal} : a ^< min b c = min (a ^< b) (a ^< c) := (powerlt_mono_left a).map_min lemma powerlt_max {a b c : cardinal} : a ^< max b c = max (a ^< b) (a ^< c) := (powerlt_mono_left a).map_max lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply (powerlt_le.2 (λ c hc, zero_power_le _)).antisymm, rw ←power_zero, exact le_powerlt 0 (pos_iff_ne_zero.2 h) end @[simp] lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := begin convert cardinal.supr_of_empty _, exact subtype.is_empty_of_false (λ x, (cardinal.zero_le _).not_lt), end end cardinal
93921dd43a90463d4daa2b810e0644accd639844
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/limits/shapes/finite_products.lean
4ae891118b8fb94bd69ba9714353ca76332e198c
[ "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,746
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.products import category_theory.limits.shapes.finite_limits import category_theory.discrete_category import data.fintype universes v u open category_theory namespace category_theory.limits variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 class has_finite_products := (has_limits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_limits_of_shape.{v} (discrete J) C) class has_finite_coproducts := (has_colimits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_colimits_of_shape.{v} (discrete J) C) attribute [instance] has_finite_products.has_limits_of_shape has_finite_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance has_finite_products_of_has_products [has_products.{v} C] : has_finite_products.{v} C := { has_limits_of_shape := λ J _, by apply_instance } @[priority 100] -- see Note [lower instance priority] instance has_finite_coproducts_of_has_coproducts [has_coproducts.{v} C] : has_finite_coproducts.{v} C := { has_colimits_of_shape := λ J _, by apply_instance } @[priority 100] -- see Note [lower instance priority] instance has_finite_products_of_has_finite_limits [has_finite_limits.{v} C] : has_finite_products.{v} C := { has_limits_of_shape := λ J _ _, by { resetI, apply_instance } } @[priority 100] -- see Note [lower instance priority] instance has_finite_coproducts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_finite_coproducts.{v} C := { has_colimits_of_shape := λ J _ _, by { resetI, apply_instance } } end category_theory.limits
ffb06042464c2a401d0fd320b2a4e2ef0d8b6c77
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.14.lean
66543bf25b5bd69b999a3163d39d6a609e85ffcc
[]
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
211
lean
import standard namespace hide -- BEGIN definition dite (c : Prop) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A := decidable.rec_on H (λ Hc : c, t Hc) (λ Hnc : ¬ c, e Hnc) -- END end hide
58c8f06aa033c58ef4de9bdd912ea1421e1e1ec1
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/instances/nnreal.lean
27f38c343a2be9e5b55da1257328f6739ae6bd47
[ "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
7,790
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.algebra.infinite_sum import topology.algebra.group_with_zero /-! # Topology on `ℝ≥0` The natural topology on `ℝ≥0` (the one induced from `ℝ`), and a basic API. ## Main definitions Instances for the following typeclasses are defined: * `topological_space ℝ≥0` * `topological_semiring ℝ≥0` * `second_countable_topology ℝ≥0` * `order_topology ℝ≥0` * `has_continuous_sub ℝ≥0` * `has_continuous_inv' ℝ≥0` (continuity of `x⁻¹` away from `0`) * `has_continuous_smul ℝ≥0 ℝ` Everything is inherited from the corresponding structures on the reals. ## Main statements Various mathematically trivial lemmas are proved about the compatibility of limits and sums in `ℝ≥0` and `ℝ`. For example * `tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x)` says that the limit of a filter along a map to `ℝ≥0` is the same in `ℝ` and `ℝ≥0`, and * `coe_tsum {f : α → ℝ≥0} : ((∑'a, f a) : ℝ) = (∑'a, (f a : ℝ))` says that says that a sum of elements in `ℝ≥0` is the same in `ℝ` and `ℝ≥0`. Similarly, some mathematically trivial lemmas about infinite sums are proved, a few of which rely on the fact that subtraction is continuous. -/ noncomputable theory open set topological_space metric filter open_locale topological_space namespace nnreal open_locale nnreal big_operators filter instance : topological_space ℝ≥0 := infer_instance -- short-circuit type class inference instance : topological_semiring ℝ≥0 := { continuous_mul := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).mul (continuous_subtype_val.comp continuous_snd), continuous_add := continuous_subtype_mk _ $ (continuous_subtype_val.comp continuous_fst).add (continuous_subtype_val.comp continuous_snd) } instance : second_countable_topology ℝ≥0 := topological_space.subtype.second_countable_topology _ _ instance : order_topology ℝ≥0 := @order_topology_of_ord_connected _ _ _ _ (Ici 0) _ section coe variable {α : Type*} open filter finset lemma continuous_of_real : continuous real.to_nnreal := continuous_subtype_mk _ $ continuous_id.max continuous_const lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ) := continuous_subtype_val @[simp, norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {x : ℝ≥0} : tendsto (λa, (m a : ℝ)) f (𝓝 (x : ℝ)) ↔ tendsto m f (𝓝 x) := tendsto_subtype_rng.symm lemma tendsto_coe' {f : filter α} [ne_bot f] {m : α → ℝ≥0} {x : ℝ} : tendsto (λ a, m a : α → ℝ) f (𝓝 x) ↔ ∃ hx : 0 ≤ x, tendsto m f (𝓝 ⟨x, hx⟩) := ⟨λ h, ⟨ge_of_tendsto' h (λ c, (m c).2), tendsto_coe.1 h⟩, λ ⟨hx, hm⟩, tendsto_coe.2 hm⟩ @[simp] lemma map_coe_at_top : map (coe : ℝ≥0 → ℝ) at_top = at_top := map_coe_Ici_at_top 0 lemma comap_coe_at_top : comap (coe : ℝ≥0 → ℝ) at_top = at_top := (at_top_Ici_eq 0).symm @[simp, norm_cast] lemma tendsto_coe_at_top {f : filter α} {m : α → ℝ≥0} : tendsto (λ a, (m a : ℝ)) f at_top ↔ tendsto m f at_top := tendsto_Ici_at_top.symm lemma tendsto_of_real {f : filter α} {m : α → ℝ} {x : ℝ} (h : tendsto m f (𝓝 x)) : tendsto (λa, real.to_nnreal (m a)) f (𝓝 (real.to_nnreal x)) := (continuous_of_real.tendsto _).comp h lemma nhds_zero : 𝓝 (0 : ℝ≥0) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0)).has_basis (λ a : ℝ≥0, 0 < a) (λ a, Iio a) := nhds_bot_basis instance : has_continuous_sub ℝ≥0 := ⟨continuous_subtype_mk _ $ ((continuous_coe.comp continuous_fst).sub (continuous_coe.comp continuous_snd)).max continuous_const⟩ instance : has_continuous_inv' ℝ≥0 := ⟨λ x hx, tendsto_coe.1 $ (real.tendsto_inv $ nnreal.coe_ne_zero.2 hx).comp continuous_coe.continuous_at⟩ instance : has_continuous_smul ℝ≥0 ℝ := { continuous_smul := continuous.comp real.continuous_mul $ continuous.prod_mk (continuous.comp continuous_subtype_val continuous_fst) continuous_snd } @[norm_cast] lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ)) (r : ℝ) ↔ has_sum f r := by simp only [has_sum, coe_sum.symm, tendsto_coe] lemma has_sum_of_real_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : has_sum (λ n, real.to_nnreal (f n)) (real.to_nnreal (∑' n, f n)) := begin have h_sum : (λ s, ∑ b in s, real.to_nnreal (f b)) = λ s, real.to_nnreal (∑ b in s, f b), from funext (λ _, (real.to_nnreal_sum_of_nonneg (λ n _, hf_nonneg n)).symm), simp_rw [has_sum, h_sum], exact tendsto_of_real hf.has_sum, end @[norm_cast] lemma summable_coe {f : α → ℝ≥0} : summable (λa, (f a : ℝ)) ↔ summable f := begin split, exact assume ⟨a, ha⟩, ⟨⟨a, has_sum_le (λa, (f a).2) has_sum_zero ha⟩, has_sum_coe.1 ha⟩, exact assume ⟨a, ha⟩, ⟨a.1, has_sum_coe.2 ha⟩ end open_locale classical @[norm_cast] lemma coe_tsum {f : α → ℝ≥0} : ↑∑'a, f a = ∑'a, (f a : ℝ) := if hf : summable f then (eq.symm $ (has_sum_coe.2 $ hf.has_sum).tsum_eq) else by simp [tsum, hf, mt summable_coe.1 hf] lemma tsum_mul_left (a : ℝ≥0) (f : α → ℝ≥0) : ∑' x, a * f x = a * ∑' x, f x := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_left] lemma tsum_mul_right (f : α → ℝ≥0) (a : ℝ≥0) : (∑' x, f x * a) = (∑' x, f x) * a := nnreal.eq $ by simp only [coe_tsum, nnreal.coe_mul, tsum_mul_right] lemma summable_comp_injective {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : summable (f ∘ i) := nnreal.summable_coe.1 $ show summable ((coe ∘ f) ∘ i), from (nnreal.summable_coe.2 hf).comp_injective hi lemma summable_nat_add (f : ℕ → ℝ≥0) (hf : summable f) (k : ℕ) : summable (λ i, f (i + k)) := summable_comp_injective hf $ add_left_injective k lemma summable_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) : summable (λ i, f (i + k)) ↔ summable f := begin rw [← summable_coe, ← summable_coe], exact @summable_nat_add_iff ℝ _ _ _ (λ i, (f i : ℝ)) k, end lemma has_sum_nat_add_iff {f : ℕ → ℝ≥0} (k : ℕ) {a : ℝ≥0} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := by simp [← has_sum_coe, coe_sum, nnreal.coe_add, ← has_sum_nat_add_iff k] lemma sum_add_tsum_nat_add {f : ℕ → ℝ≥0} (k : ℕ) (hf : summable f) : ∑' i, f i = (∑ i in range k, f i) + ∑' i, f (i + k) := by rw [←nnreal.coe_eq, coe_tsum, nnreal.coe_add, coe_sum, coe_tsum, sum_add_tsum_nat_add k (nnreal.summable_coe.2 hf)] lemma infi_real_pos_eq_infi_nnreal_pos [complete_lattice α] {f : ℝ → α} : (⨅ (n : ℝ) (h : 0 < n), f n) = (⨅ (n : ℝ≥0) (h : 0 < n), f n) := le_antisymm (infi_le_infi2 $ assume r, ⟨r, infi_le_infi $ assume hr, le_rfl⟩) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, hr.le⟩ $ infi_le _ hr) end coe lemma tendsto_cofinite_zero_of_summable {α} {f : α → ℝ≥0} (hf : summable f) : tendsto f cofinite (𝓝 0) := begin have h_f_coe : f = λ n, real.to_nnreal (f n : ℝ), from funext (λ n, real.to_nnreal_coe.symm), rw [h_f_coe, ← @real.to_nnreal_coe 0], exact tendsto_of_real ((summable_coe.mpr hf).tendsto_cofinite_zero), end lemma tendsto_at_top_zero_of_summable {f : ℕ → ℝ≥0} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_summable hf } end nnreal
8ba6acd870f09455f32fcb367f5bd003cb293ec0
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/monoidal/functor.lean
0024b6322bfc9110e2dd7d063677c767206a11a0
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
6,463
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.monoidal.category open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory section open monoidal_category variables (C : Type u₁) [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] (D : Type u₂) [category.{v₂} D] [𝒟 : monoidal_category.{v₂} D] include 𝒞 𝒟 /-- A lax monoidal functor is a functor `F : C ⥤ D` between monoidal categories, equipped with morphisms `ε : 𝟙 _D ⟶ F.obj (𝟙_ C)` and `μ X Y : F.obj X ⊗ F.obj Y ⟶ F.obj (X ⊗ Y)`, satisfying the the appropriate coherences. -/ structure lax_monoidal_functor extends C ⥤ D := -- unit morphism (ε : 𝟙_ D ⟶ obj (𝟙_ C)) -- tensorator (μ : Π X Y : C, (obj X) ⊗ (obj Y) ⟶ obj (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map f) ⊗ (map g)) ≫ μ Y Y' = μ X X' ≫ map (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (obj Z)) ≫ μ (X ⊗ Y) Z ≫ map (α_ X Y Z).hom = (α_ (obj X) (obj Y) (obj Z)).hom ≫ (𝟙 (obj X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (λ_ (obj X)).hom = (ε ⊗ 𝟙 (obj X)) ≫ μ (𝟙_ C) X ≫ map (λ_ X).hom . obviously) (right_unitality' : ∀ X : C, (ρ_ (obj X)).hom = (𝟙 (obj X) ⊗ ε) ≫ μ X (𝟙_ C) ≫ map (ρ_ X).hom . obviously) restate_axiom lax_monoidal_functor.μ_natural' attribute [simp] lax_monoidal_functor.μ_natural restate_axiom lax_monoidal_functor.left_unitality' attribute [simp] lax_monoidal_functor.left_unitality restate_axiom lax_monoidal_functor.right_unitality' attribute [simp] lax_monoidal_functor.right_unitality restate_axiom lax_monoidal_functor.associativity' attribute [simp] lax_monoidal_functor.associativity -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity /-- A monoidal functor is a lax monoidal functor for which the tensorator and unitor as isomorphisms. -/ structure monoidal_functor extends lax_monoidal_functor.{v₁ v₂} C D := (ε_is_iso : is_iso ε . obviously) (μ_is_iso : Π X Y : C, is_iso (μ X Y) . obviously) attribute [instance] monoidal_functor.ε_is_iso monoidal_functor.μ_is_iso variables {C D} def monoidal_functor.ε_iso (F : monoidal_functor.{v₁ v₂} C D) : tensor_unit D ≅ F.obj (tensor_unit C) := as_iso F.ε def monoidal_functor.μ_iso (F : monoidal_functor.{v₁ v₂} C D) (X Y : C) : (F.obj X) ⊗ (F.obj Y) ≅ F.obj (X ⊗ Y) := as_iso (F.μ X Y) end open monoidal_category namespace monoidal_functor section variables {C : Type u₁} [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] [𝒟 : monoidal_category.{v₂} D] include 𝒞 𝒟 /-- The tensorator as a natural isomorphism. -/ def μ_nat_iso (F : monoidal_functor.{v₁ v₂} C D) : (functor.prod F.to_functor F.to_functor) ⋙ (tensor D) ≅ (tensor C) ⋙ F.to_functor := nat_iso.of_components (by { intros, apply F.μ_iso }) (by { intros, apply F.to_lax_monoidal_functor.μ_natural }) end section variables (C : Type u₁) [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] include 𝒞 /-- The identity monoidal functor. -/ @[simps] def id : monoidal_functor.{v₁ v₁} C C := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, .. 𝟭 C } end end monoidal_functor variables {C : Type u₁} [category.{v₁} C] [𝒞 : monoidal_category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] [𝒟 : monoidal_category.{v₂} D] variables {E : Type u₃} [category.{v₃} E] [ℰ : monoidal_category.{v₃} E] include 𝒞 𝒟 ℰ namespace lax_monoidal_functor variables (F : lax_monoidal_functor.{v₁ v₂} C D) (G : lax_monoidal_functor.{v₂ v₃} D E) -- The proofs here are horrendous; rewrite_search helps a lot. /-- The composition of two lax monoidal functors is again lax monoidal. -/ @[simps] def comp : lax_monoidal_functor.{v₁ v₃} C E := { ε := G.ε ≫ (G.map F.ε), μ := λ X Y, G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y), μ_natural' := λ _ _ _ _ f g, begin simp only [functor.comp_map, assoc], rw [←category.assoc, lax_monoidal_functor.μ_natural, category.assoc, ←map_comp, ←map_comp, ←lax_monoidal_functor.μ_natural] end, associativity' := λ X Y Z, begin dsimp, rw id_tensor_comp, slice_rhs 3 4 { rw [← G.to_functor.map_id, G.μ_natural], }, slice_rhs 1 3 { rw ←G.associativity, }, rw comp_tensor_id, slice_lhs 2 3 { rw [← G.to_functor.map_id, G.μ_natural], }, rw [category.assoc, category.assoc, category.assoc, category.assoc, category.assoc, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, F.associativity], end, left_unitality' := λ X, begin dsimp, rw [G.left_unitality, comp_tensor_id, category.assoc, category.assoc], apply congr_arg, rw [F.left_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, right_unitality' := λ X, begin dsimp, rw [G.right_unitality, id_tensor_comp, category.assoc, category.assoc], apply congr_arg, rw [F.right_unitality, map_comp, ←nat_trans.id_app, ←category.assoc, ←lax_monoidal_functor.μ_natural, nat_trans.id_app, map_id, ←category.assoc, map_comp], end, .. (F.to_functor) ⋙ (G.to_functor) }. end lax_monoidal_functor namespace monoidal_functor variables (F : monoidal_functor.{v₁ v₂} C D) (G : monoidal_functor.{v₂ v₃} D E) /-- The composition of two monoidal functors is again monoidal. -/ def comp : monoidal_functor.{v₁ v₃} C E := { ε_is_iso := by { dsimp, apply_instance }, μ_is_iso := by { dsimp, apply_instance }, .. (F.to_lax_monoidal_functor).comp (G.to_lax_monoidal_functor) }. end monoidal_functor end category_theory
8bf06a583fec6a88f833b048ddaf1460ec0ce416
1dd482be3f611941db7801003235dc84147ec60a
/src/data/fintype.lean
843784753f0827437829aad683119d7fcaf8a3af
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
29,375
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas data.vector2 data.equiv.encodable universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin change multiset.card s = multiset.card s' at e', revert nd nd' h h' e', refine quotient.induction_on₂ s s' (λ l₁ l₂ (nd₁ : l₁.nodup) (nd₂ : l₂.nodup) (h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂) (e' : l₁.length = l₂.length), _), haveI := classical.dec_eq α, refine ⟨equiv.of_bijective ⟨_, _⟩⟩, { refine λ a, l₂.nth_le (l₁.index_of a) _, rw ← e', exact list.index_of_lt_length.2 (h₁ a) }, { intros a b h, simpa [h₁] using congr_arg l₁.nth (list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) }, { have := classical.dec_eq β, refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩, { rw e', exact list.index_of_lt_length.2 (h₂ b) }, { simp [nd₁] } } end end, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem fintype.univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem fintype.card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype instance (n : ℕ) : fintype (fin n) := ⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1), list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩, λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := by rw [fin.fintype]; simp [fintype.card, card, univ] instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.bijective.1 (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_card_gt_one [fintype α] (h : fintype.card α > 1) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.bijective.2 (this.1 (injective_comp e.symm.bijective.1 hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.bijective.1 (this.2 (surjective_comp e.symm.bijective.2 hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive finset.sum_attach_univ] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.bijective.1 h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.bijective.1 h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.bijective.1 h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.bijective.1 $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse end fintype
571f30c44c96150aae70228dabc23f402a37dd41
3c9dc4ea6cc92e02634ef557110bde9eae393338
/src/Init/Meta.lean
d07970a6ca969be0c2400b38749e69d9dbd2695b
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,467
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private constant version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private constant version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private constant version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () -- @[extern c inline "lean_mk_string(LEAN_GITHASH)"] -- constant getGithash (u : Unit) : String -- def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] constant version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] constant version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () /- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def toStringWithSep (sep : String) : Name → String | anonymous => "[anonymous]" | str anonymous s _ => s | num anonymous v _ => toString v | str n s _ => toStringWithSep sep n ++ sep ++ s | num n v _ => toStringWithSep sep n ++ sep ++ Nat.repr v protected def toString : Name → String := toStringWithSep "." instance : ToString Name where toString n := n.toString instance : Repr Name where reprPrec n _ := Std.Format.text "`" ++ n.toString def capitalize : Name → Name | Name.str p s _ => Name.mkStr p s.capitalize | n => n def appendAfter : Name → String → Name | str p s _, suffix => Name.mkStr p (s ++ suffix) | n, suffix => Name.mkStr n suffix def appendIndexAfter : Name → Nat → Name | str p s _, idx => Name.mkStr p (s ++ "_" ++ toString idx) | n, idx => Name.mkStr n ("_" ++ toString idx) def appendBefore : Name → String → Name | anonymous, pre => Name.mkStr anonymous pre | str p s _, pre => Name.mkStr p (pre ++ s) | num p n _, pre => Name.mkNum (Name.mkStr p pre) n end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadNameGenerator m] [MonadLift m n] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax partial def getTailInfo : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node _ args => args.findSomeRev? getTailInfo | _ => none partial def getTailPos : Syntax → Option String.Pos | atom { pos := some pos, .. } val => some (pos + val.bsize) | ident { pos := some pos, .. } val .. => some (pos + val.toString.bsize) | node _ args => args.findSomeRev? getTailPos | _ => none @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i] match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node k args | none => none | stx => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | none => stx | some info => stx.setTailInfo { info with trailing := none } @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a.get ⟨i, h⟩; match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node k args | noxne => none | stx => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | stx => stx partial def replaceInfo (info : SourceInfo) : Syntax → Syntax | node k args => node k <| args.map (replaceInfo info) | stx => setInfo info stx def copyHeadInfo (s : Syntax) (source : Syntax) : Syntax := match source.getHeadInfo with | none => s | some info => s.setHeadInfo info def copyTailInfo (s : Syntax) (source : Syntax) : Syntax := match source.getTailInfo with | none => s | some info => s.setTailInfo info def copyInfo (s : Syntax) (source : Syntax) : Syntax := let s := s.copyHeadInfo source s.copyTailInfo source end Syntax def mkAtom (val : String) : Syntax := Syntax.atom {} val @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : Syntax := Syntax.node k args /- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand all macros in the given syntax -/ partial def expandMacros : Syntax → MacroM Syntax | stx@(Syntax.node k args) => do match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros pure <| Syntax.node k args | stx => pure stx /- Helper functions for processing Syntax programmatically -/ /-- Create an identifier using `SourceInfo` from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Syntax := let info := src.getHeadInfo.getD {} Syntax.ident info (toString val).toSubstring val [] /-- Create an identifier referring to a constant `c` using `SourceInfo` from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Syntax := let info := src.getHeadInfo.getD {} -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope Syntax.ident info (toString id).toSubstring id [(c, [])] def mkCIdent (c : Name) : Syntax := mkCIdentFrom Syntax.missing c def Syntax.identToAtom (stx : Syntax) : Syntax := match stx with | Syntax.ident info _ val _ => Syntax.atom info (toString val.eraseMacroScopes) | _ => stx @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Syntax := Syntax.ident {} (toString val).toSubstring val [] @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := Syntax.node nullKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => Syntax.node nullKind #[arg] | none => Syntax.node nullKind #[] def mkHole (ref : Syntax) : Syntax := Syntax.node `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (mkAtomFrom ref sep)⟩ instance (sep) : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Syntax) : (args : Array Syntax) → Syntax | #[] => fn | args => Syntax.node `Lean.Parser.Term.app #[fn, mkNullNode args] def mkCApp (fn : Name) (args : Array Syntax) : Syntax := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info : SourceInfo := {}) : Syntax := let atom : Syntax := Syntax.atom info val Syntax.node kind #[atom] def mkStrLit (val : String) (info : SourceInfo := {}) : Syntax := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info : SourceInfo := {}) : Syntax := mkLit numLitKind val info def mkScientificLit (val : String) (info : SourceInfo := {}) : Syntax := mkLit scientificLitKind val info /- Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get 1 if c == 'x' || c == 'X' then decodeHexLitAux s 2 0 else if c == 'b' || c == 'B' then decodeBinLitAux s 2 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s 2 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s 1 "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := let c := s.get 1 if c == '\\' then do let (c, _) ← decodeQuotedChar s 2 pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def decodeNameLitAux (s : String) (i : Nat) (r : Name) : Option Name := do let continue? (i : Nat) (r : Name) : Option Name := if s.get i == '.' then decodeNameLitAux s (s.next i) r else if s.atEnd i then pure r else none let curr := s.get i if isIdBeginEscape curr then let startPart := s.next i let stopPart := s.nextUntil isIdEndEscape startPart if !isIdEndEscape (s.get stopPart) then none else continue? (s.next stopPart) (Name.mkStr r (s.extract startPart stopPart)) else if isIdFirst curr then let startPart := i let stopPart := s.nextWhile isIdRest startPart continue? stopPart (Name.mkStr r (s.extract startPart stopPart)) else none def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then decodeNameLitAux s 1 Name.anonymous else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ args => args.size > 0 | _ => false def identToStrLit (stx : Syntax) : Syntax := match stx with | Syntax.ident info _ val _ => mkStrLit (toString val) info | _ => stx def strLitToAtom (stx : Syntax) : Syntax := match stx.isStrLit? with | none => stx | some val => match stx.getHeadInfo with | some info => Syntax.atom info val | none => unreachable! def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def isNone (stx : Syntax) : Bool := match stx with | Syntax.node k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node k args => if k == nullKind && args.size == 1 then some (args.get! 0) else none | _ => none def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) where quote : α → Syntax export Quote (quote) instance : Quote Syntax := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String := ⟨Syntax.mkStrLit⟩ instance : Quote Nat := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ private def quoteName : Name → Syntax | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s _ => Syntax.mkCApp ``Name.mkStr #[quoteName n, quote s] | Name.num n i _ => Syntax.mkCApp ``Name.mkNum #[quoteName n, quote i] instance : Quote Name := ⟨quoteName⟩ instance {α β : Type} [Quote α] [Quote β] : Quote (α × β) where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList {α : Type} [Quote α] : List α → Syntax | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance {α : Type} [Quote α] : Quote (List α) where quote := quoteList instance {α : Type} [Quote α] : Quote (Array α) where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] private def quoteOption {α : Type} [Quote α] : Option α → Syntax | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] instance Option.hasQuote {α : Type} [Quote α] : Quote (Option α) where quote := quoteOption /- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):numLit) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):numLit) macro "evalPrec! " p:prec:max : term => return quote (← evalPrec p) def evalOptPrec : Option Syntax → MacroM Nat | some prec => evalPrec prec | none => return 0 /- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:numLit) => return num.isNatLit?.getD 0 | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):numLit) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):numLit) macro "evalPrio! " p:prio:max : term => return quote (← evalPrio p) def evalOptPrio : Option Syntax → MacroM Nat | some prio => evalPrio prio | none => return evalPrio! default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have i.pred < i from Nat.predLt hz let sepStx := a.get ⟨i.pred, Nat.ltTrans this h⟩ filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a.get ⟨i, h⟩ if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax.SepArray def getElems {sep} (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems instance (sep) : Coe (SepArray sep) (Array Syntax) where coe := getElems end Lean.Syntax.SepArray /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /- Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop 1 "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result def expandInterpolatedStr (interpStr : Syntax) (type : Syntax) (toTypeFn : Syntax) : MacroM Syntax := do let ref := interpStr let r ← expandInterpolatedStrChunks interpStr.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace Meta.Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true iota : Bool := true proj : Bool := true ctorEq : Bool := true deriving Inhabited, BEq, Repr end Meta.Simp end Lean
8d06eac6a628bd3d3d6cfb44e60c46472a45d634
4fa118f6209450d4e8d058790e2967337811b2b5
/src/valuation/localization.lean
f4172c8d2277a7e24ebdf0ea319f8ba8d4b99a5d
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
13,435
lean
import ring_theory.localization import valuation.basic /-! # Extending valuations to localizations In this file we extend valuations on a ring R to localizations of R. We use this to define the valuation field, the valuation ring, and the residue field of a valued ring. If v is a valuation on an integral domain R and `hv : supp v = 0`, then `on_frac v hv` is the extension of v to fraction_ring R, the field of fractions of R. `valuation_field v`, `valuation_ring v`, `max_ideal v` and `residue_field v` are the valuation field, valuation ring, maximal ideal and residue field of v. See [Wedhorn; 1.26]. -/ local attribute [instance] classical.prop_decidable local attribute [instance] classical.DLO noncomputable theory universes u u₀ variables {R : Type u₀} [comm_ring R] variables {Γ₀ : Type u} [linear_ordered_comm_group_with_zero Γ₀] variables {S : set R} [is_submonoid S] namespace valuation open linear_ordered_structure variables (v : valuation R Γ₀) lemma inverse_exists (s : S) : ∃ u : localization R S, u * s = 1 := ⟨(localization.to_units s).inv, units.inv_val _⟩ /-- The underlying function of the extension of a valuation to a localization.-/ def localization_v (h : ∀ s, s ∈ S → v s ≠ 0) : localization R S → Γ₀ := λ (q : localization R S), quotient.lift_on' q (λ rs, v rs.1 * (v rs.2.1)⁻¹) begin rintros ⟨r1, s1, hs1⟩ ⟨r2, s2, hs2⟩ ⟨t, ht, hrst⟩, change (s1 * r2 + -(s2 * r1)) * t = 0 at hrst, show v r1 * (v s1)⁻¹ = v r2 * (v s2)⁻¹, rw [add_mul, ←neg_mul_eq_neg_mul, add_neg_eq_zero] at hrst, replace hrst : v (s1 * r2 * t) = v (s2 * r1 * t) := congr_arg v hrst, apply group_with_zero.mul_inv_eq_of_eq_mul (h s1 hs1), rw [mul_comm, ←mul_assoc], apply group_with_zero.eq_mul_inv_of_mul_eq (h s2 hs2), rw [←v.map_mul, ←v.map_mul, mul_comm], apply group_with_zero.mul_right_cancel (h t ht), rw [←v.map_mul, ←v.map_mul, hrst] end /-- Extension of a valuation to a localization -/ protected def localization (h : ∀ s, s ∈ S → v s ≠ 0) : valuation (localization R S) Γ₀ := { to_fun := v.localization_v h, map_zero' := show v 0 * (v 1)⁻¹ = 0, by rw [v.map_zero, zero_mul], map_one' := show v 1 * (v 1)⁻¹ = 1, by {rw [v.map_one], simp}, map_mul' := λ x y, quotient.induction_on₂' x y begin rintro ⟨r1, s1, hs1⟩, rintro ⟨r2, s2, hs2⟩, -- TODO : I had to write the next line "blind" -- I had to be the compiler. -- Am I missing a trick? show v (r1 * r2) * (v(s1 * s2))⁻¹ = (v r1 * (v s1)⁻¹) * (v r2 * (v s2)⁻¹), have hs12 : s1 * s2 ∈ S := is_submonoid.mul_mem hs1 hs2, apply group_with_zero.mul_inv_eq_of_eq_mul (h (s1 * s2) hs12), rw [mul_comm _ (v (s1 * s2)), ←mul_assoc, ←mul_assoc], apply group_with_zero.eq_mul_inv_of_mul_eq (h s2 hs2), rw [mul_comm _ (v r2), ←v.map_mul, ←mul_assoc, ←v.map_mul, ←mul_assoc, ←v.map_mul], apply group_with_zero.eq_mul_inv_of_mul_eq (h s1 hs1), rw [←v.map_mul], apply congr_arg, ring, end, map_add' := λ x y, quotient.induction_on₂' x y begin rintro ⟨r1, s1, hs1⟩, rintro ⟨r2, s2, hs2⟩, have := v.map_add (r1 * s2) (r2 * s1), rw le_max_iff at this ⊢, show v (s1 * r2 + s2 * r1) * (v (s1 * s2))⁻¹ ≤ v r1 * (v s1)⁻¹ ∨ v (s1 * r2 + s2 * r1) * (v (s1 * s2))⁻¹ ≤ v r2 * (v s2)⁻¹, cases this with h1 h2, { left, apply le_mul_inv_of_mul_le (h s1 hs1), rw [mul_comm, ←mul_assoc], apply mul_inv_le_of_le_mul (h (s1 * s2) (is_submonoid.mul_mem hs1 hs2)), replace h1 := linear_ordered_structure.mul_le_mul_right h1 (v s1), rw [←v.map_mul, ←v.map_mul] at h1 ⊢, rw (show s1 * (s1 * r2 + s2 * r1) = (r1 * s2 + r2 * s1) * s1, by ring), rwa (show r1 * (s1 * s2) = r1 * s2 * s1, by ring), }, { right, apply le_mul_inv_of_mul_le (h s2 hs2), rw [mul_comm, ←mul_assoc], apply mul_inv_le_of_le_mul (h (s1 * s2) (is_submonoid.mul_mem hs1 hs2)), replace h2 := linear_ordered_structure.mul_le_mul_right h2 (v s2), rw [←v.map_mul, ←v.map_mul] at h2 ⊢, rw (show s2 * (s1 * r2 + s2 * r1) = (r1 * s2 + r2 * s1) * s2, by ring), rwa (show r2 * (s1 * s2) = r2 * s1 * s2, by ring), } end } /-- Extension of a valuation to a localization -/ lemma localization_apply (h : ∀ s, s ∈ S → v s ≠ 0) (r : R) : (v.localization h : valuation (localization R S) Γ₀) r = v r := show v r * (v 1)⁻¹ = v r, by simp /-- the extension of a valuation pulls back to the valuation -/ lemma localization_comap (h : ∀ s, s ∈ S → v s ≠ 0) : (v.localization h).comap (localization.of) = v := valuation.ext $ λ r, localization_apply v h r lemma eq_localization_of_comap_aux {v} (w : valuation (localization R S) Γ₀) (h : w.comap (localization.of) = v) : ∀ s, s ∈ S → v s ≠ 0 := λ s hs h0, begin cases inverse_exists ⟨s, hs⟩ with u hu, let s' : units (localization R S) := ⟨localization.of s, u, mul_comm u s ▸ hu, hu⟩, refine group_with_zero.unit_ne_zero (units.map (w : (localization R S) →* Γ₀) s') _, rwa ←h at h0, end /-- If a valuation on a localisation pulls back to v then it's the localization of v -/ lemma eq_localization_of_comap (w : valuation (localization R S) Γ₀) (h : w.comap (localization.of) = v) : v.localization (eq_localization_of_comap_aux w h) = w := begin ext q, induction q, { rcases q with ⟨r, s, hs⟩, show v r * (v s)⁻¹ = w (localization.mk r ⟨s, hs⟩), rw [localization.mk_eq, ←h, w.map_mul], show w r * _ = _, congr, show (w s)⁻¹ = _, rw w.map_units_inv, refl, }, refl end section fraction_ring open localization localization.fraction_ring /-- A ring in which the zero ideal is prime is an integral domain. -/ def integral_domain_of_prime_bot (h : (⊥ : ideal R).is_prime) : integral_domain R := { zero_ne_one := assume zero_eq_one, h.1 $ (ideal.eq_top_iff_one _).mpr $ (submodule.mem_bot R).mpr zero_eq_one.symm, eq_zero_or_eq_zero_of_mul_eq_zero := λ r s, by { repeat {rw ← submodule.mem_bot R}, apply h.2 }, .. ‹comm_ring R› } /-- A ring is an integral domain if it admits a valuation whose support is the zero ideal. -/ def integral_domain_of_supp_zero (hv : v.supp = 0) : integral_domain R := integral_domain_of_prime_bot $ by { rw [← ideal.zero_eq_bot, ← hv], exact valuation.ideal.is_prime v } /-- The extension of valuation on R with support 0 to a valuation on the field of fractions. -/ def on_frac (hv : v.supp = 0) : valuation (fraction_ring R) Γ₀ := v.localization $ λ r hr hnz, begin letI := v.integral_domain_of_supp_zero hv, refine (@mem_non_zero_divisors_iff_ne_zero R _ _ r).mp hr _, rwa [← submodule.mem_bot R, ← ideal.zero_eq_bot, ← hv], end @[simp] lemma on_frac_comap_eq (hv : supp v = 0) : (v.on_frac hv).comap of = v := v.localization_comap _ lemma on_frac_comap_eq_apply (hv : supp v = 0) (r : R) : ((v.on_frac hv).comap of : valuation R Γ₀) r = v r := by rw on_frac_comap_eq /-- Pulling back a valuation on `fraction_ring R` to R and then applying `on_frac` is the identity function. -/ @[simp] lemma comap_on_frac_eq {R : Type*} [integral_domain R] (v : valuation (fraction_ring R) Γ₀) : (v.comap of).on_frac (by {rw [comap_supp, ideal.zero_eq_bot, v.supp.eq_bot_of_prime], apply ideal.comap_bot_of_inj, apply fraction_ring.of.injective }) = v := valuation.eq_localization_of_comap _ _ rfl lemma frac_preorder_comap (hv : supp v = 0) : preorder.lift (localization.of) (v.on_frac hv).to_preorder = v.to_preorder := preorder.ext $ λ x y, begin show (v.on_frac hv) x ≤ (v.on_frac hv) y ↔ v x ≤ v y, rw [←on_frac_comap_eq_apply v hv, ←on_frac_comap_eq_apply v hv], exact iff.rfl end end fraction_ring -- end of section section valuation_field /-- The quotient ring R/supp(v) associated to a valuation. -/ definition valuation_ID := (supp v).quotient /-- the support of a valuation is a prime ideal, so R/supp(v) is an integral domain. -/ instance integral_domain' : integral_domain (valuation_ID v) := by delta valuation_ID; apply_instance /-- The preorder on R/supp(v) induced by Γ₀ via `v.on_quot` -/ instance : preorder (valuation_ID v) := (v.on_quot (le_refl _)).to_preorder /-- The function R → R/supp(v). -/ def valuation_ID_mk : R → valuation_ID v := ideal.quotient.mk (supp v) /-- The function R → R/supp(v) is a ring homomorphism. -/ instance : is_ring_hom (v.valuation_ID_mk) := by unfold valuation_ID_mk; apply_instance /-- The kernel of R → R/supp(v) is supp(v). -/ lemma valuation_ID_mk_ker (r : R) : v.valuation_ID_mk r = 0 ↔ r ∈ supp v := ideal.quotient.eq_zero_iff_mem /-- `valuation_field v` is the field of fractions of R/supp(v). -/ definition valuation_field := localization.fraction_ring (valuation_ID v) /-- The field of fractions of R/supp(v) is a field. -/ instance : discrete_field (valuation_field v) := by delta valuation_field; apply_instance /-- The canonical map R → fraction_ring (R/supp(v)). -/ def valuation_field_mk (r : R) : valuation_field v := localization.of (v.valuation_ID_mk r) /-- The map R → Frac(R/supp(v)) is a ring homomorphism. -/ instance to_valuation_field.is_ring_hom : is_ring_hom (valuation_field_mk v) := by delta valuation_field_mk; apply_instance /-- The kernel of R → Frac(R/supp(v)) is supp(v). -/ lemma valuation_field_mk_ker (r : R) : v.valuation_field_mk r = 0 ↔ r ∈ supp v := ⟨λ h, (v.valuation_ID_mk_ker r).1 $ localization.fraction_ring.eq_zero_of _ h, λ h, show localization.of _ = 0, by rw (v.valuation_ID_mk_ker r).2 h; apply is_ring_hom.map_zero⟩ lemma valuation_field_mk_ne_zero (r : R) (hr : v r ≠ 0) : valuation_field_mk v r ≠ 0 := λ h, hr ((valuation_field_mk_ker v r).1 h) /-- The induced preorder on Frac(R/supp(v)). -/ instance valfield_preorder : preorder (valuation_field v) := ((v.on_quot (le_refl _)).on_frac $ supp_quot_supp v).to_preorder /-- The induced map from R \ supp(v) to the units of Frac(R/supp(v)). -/ def units_valfield_mk (r : R) (h : r ∉ supp v) : units (valuation_field v) := ⟨v.valuation_field_mk r, (v.valuation_field_mk r)⁻¹, mul_inv_cancel (λ h2, h $ ideal.quotient.eq_zero_iff_mem.1 $ localization.fraction_ring.eq_zero_of _ h2), inv_mul_cancel (λ h2, h $ ideal.quotient.eq_zero_iff_mem.1 $ localization.fraction_ring.eq_zero_of _ h2)⟩ /-- The preorder on the units of Frac(R/supp(v)) induced by the extension of v. -/ instance units_valfield_preorder : preorder (units (valuation_field v)) := preorder.lift (λ u, u.val) (by apply_instance) /-- The valuation on Frac(R/supp(v)) induced by v. -/ definition on_valuation_field : valuation (valuation_field v) Γ₀ := on_frac (v.on_quot (set.subset.refl _)) begin rw [supp_quot, ideal.zero_eq_bot], apply ideal.map_quotient_self, end /-- `valuation_ring v` is the elements of Frac(R/supp(v)) whose valuation is at most 1. -/ definition valuation_ring := {x | v.on_valuation_field x ≤ 1} /-- `valuation_ring v` is a subring of Frac(R/supp(v)). -/ instance : is_subring (valuation_ring v) := { zero_mem := show v.on_valuation_field 0 ≤ 1, by simp, add_mem := λ x y hx hy, calc v.on_valuation_field (x + y) ≤ max (v.on_valuation_field x) (v.on_valuation_field y) : v.on_valuation_field.map_add x y ... ≤ 1 : max_le hx hy, neg_mem := by simp [valuation_ring], one_mem := by simp [valuation_ring, le_refl], mul_mem := λ x y (hx : _ ≤ _) (hy : _ ≤ _), show v.on_valuation_field _ ≤ 1, by convert le_trans (linear_ordered_structure.mul_le_mul_left hy _) _; simp [hx] } /-- `max_ideal v` is the ideal of `valuation_ring v` consisting of things with valuation strictly less than 1. -/ definition max_ideal : ideal (valuation_ring v) := { carrier := { r | v.on_valuation_field r < 1 }, zero := show v.on_valuation_field 0 < 1, by apply lt_of_le_of_ne; simp, add := λ x y (hx : _ < 1) (hy : _ < 1), calc v.on_valuation_field (x + y) ≤ max (v.on_valuation_field x) (v.on_valuation_field y) : v.on_valuation_field.map_add x y ... < 1 : max_lt hx hy, smul := λ c x (hx : _ < 1), show v.on_valuation_field _ < 1, begin refine lt_of_le_of_lt _ _, swap, convert (linear_ordered_structure.mul_le_mul_right _ _), exact map_mul _ _ _, swap, convert c.property, simpa using hx end } set_option class.instance_max_depth 40 /-- `max_ideal v` is indeed a maximal ideal of `valuation_ring v`. -/ instance max_ideal_is_maximal : (max_ideal v).is_maximal := begin rw ideal.is_maximal_iff, split, { exact λ (H : _ < _), ne_of_lt H (map_one _) }, { rintros J ⟨x,hx⟩ hJ hxni hxinJ, have vx : v.on_valuation_field x = 1 := by { rw eq_iff_le_not_lt, split; assumption }, have hxinv : v.on_valuation_field x⁻¹ ≤ 1 := by simp [vx], convert J.smul_mem ⟨x⁻¹, hxinv⟩ hxinJ, symmetry, apply subtype.val_injective, apply inv_mul_cancel, show x ≠ 0, assume hxeq0, simpa [hxeq0] using vx } end set_option class.instance_max_depth 32 /-- `residue_field v` is the quotient of `valuation_ring v` by `max_ideal v`. -/ definition residue_field := (max_ideal v).quotient /-- `residue_field v` is a field. -/ instance residue_field.discrete_field : discrete_field (residue_field v) := ideal.quotient.field _ end valuation_field end valuation
db00c36bdfa33d02d512dd6124e95db7c3ec5b36
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter2/2-5.lean
ff5a4c63a2f660dfde6bf71b23e9b26f35bfec2b
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
203
lean
#check let y:= 20 in y * y def e (a : ℕ) : ℕ := let y := a + a in y * y #reduce e 2 def foo := let a := nat in λ x : a, x + 2 #print foo -- def bar := (λ a, λ x : a, x + 2) nat
99a4e2e2b6044abca33c95eb2586782173a140c5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/mv_polynomial/symmetric.lean
9eb7b27d26b8f1981cd9da45e1b9897ee380cb7e
[ "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
7,944
lean
/- Copyright (c) 2020 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang, Johan Commelin -/ import data.mv_polynomial.rename import data.mv_polynomial.comm_ring import algebra.algebra.subalgebra.basic /-! # Symmetric Polynomials and Elementary Symmetric Polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines symmetric `mv_polynomial`s and elementary symmetric `mv_polynomial`s. We also prove some basic facts about them. ## Main declarations * `mv_polynomial.is_symmetric` * `mv_polynomial.symmetric_subalgebra` * `mv_polynomial.esymm` ## Notation + `esymm σ R n`, is the `n`th elementary symmetric polynomial in `mv_polynomial σ R`. As in other polynomial files, we typically use the notation: + `σ τ : Type*` (indexing the variables) + `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients) + `r : R` elements of the coefficient ring + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `φ ψ : mv_polynomial σ R` -/ open equiv (perm) open_locale big_operators noncomputable theory namespace multiset variables {R : Type*} [comm_semiring R] /-- The `n`th elementary symmetric function evaluated at the elements of `s` -/ def esymm (s : multiset R) (n : ℕ) : R := ((s.powerset_len n).map multiset.prod).sum lemma _root_.finset.esymm_map_val {σ} (f : σ → R) (s : finset σ) (n : ℕ) : (s.val.map f).esymm n = (s.powerset_len n).sum (λ t, t.prod f) := by simpa only [esymm, powerset_len_map, ← finset.map_val_val_powerset_len, map_map] end multiset namespace mv_polynomial variables {σ : Type*} {R : Type*} variables {τ : Type*} {S : Type*} /-- A `mv_polynomial φ` is symmetric if it is invariant under permutations of its variables by the `rename` operation -/ def is_symmetric [comm_semiring R] (φ : mv_polynomial σ R) : Prop := ∀ e : perm σ, rename e φ = φ variables (σ R) /-- The subalgebra of symmetric `mv_polynomial`s. -/ def symmetric_subalgebra [comm_semiring R] : subalgebra R (mv_polynomial σ R) := { carrier := set_of is_symmetric, algebra_map_mem' := λ r e, rename_C e r, mul_mem' := λ a b ha hb e, by rw [alg_hom.map_mul, ha, hb], add_mem' := λ a b ha hb e, by rw [alg_hom.map_add, ha, hb] } variables {σ R} @[simp] lemma mem_symmetric_subalgebra [comm_semiring R] (p : mv_polynomial σ R) : p ∈ symmetric_subalgebra σ R ↔ p.is_symmetric := iff.rfl namespace is_symmetric section comm_semiring variables [comm_semiring R] [comm_semiring S] {φ ψ : mv_polynomial σ R} @[simp] lemma C (r : R) : is_symmetric (C r : mv_polynomial σ R) := (symmetric_subalgebra σ R).algebra_map_mem r @[simp] lemma zero : is_symmetric (0 : mv_polynomial σ R) := (symmetric_subalgebra σ R).zero_mem @[simp] lemma one : is_symmetric (1 : mv_polynomial σ R) := (symmetric_subalgebra σ R).one_mem lemma add (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ + ψ) := (symmetric_subalgebra σ R).add_mem hφ hψ lemma mul (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ * ψ) := (symmetric_subalgebra σ R).mul_mem hφ hψ lemma smul (r : R) (hφ : is_symmetric φ) : is_symmetric (r • φ) := (symmetric_subalgebra σ R).smul_mem hφ r @[simp] lemma map (hφ : is_symmetric φ) (f : R →+* S) : is_symmetric (map f φ) := λ e, by rw [← map_rename, hφ] end comm_semiring section comm_ring variables [comm_ring R] {φ ψ : mv_polynomial σ R} lemma neg (hφ : is_symmetric φ) : is_symmetric (-φ) := (symmetric_subalgebra σ R).neg_mem hφ lemma sub (hφ : is_symmetric φ) (hψ : is_symmetric ψ) : is_symmetric (φ - ψ) := (symmetric_subalgebra σ R).sub_mem hφ hψ end comm_ring end is_symmetric section elementary_symmetric open finset variables (σ R) [comm_semiring R] [comm_semiring S] [fintype σ] [fintype τ] /-- The `n`th elementary symmetric `mv_polynomial σ R`. -/ def esymm (n : ℕ) : mv_polynomial σ R := ∑ t in powerset_len n univ, ∏ i in t, X i /-- The `n`th elementary symmetric `mv_polynomial σ R` is obtained by evaluating the `n`th elementary symmetric at the `multiset` of the monomials -/ lemma esymm_eq_multiset_esymm : esymm σ R = (finset.univ.val.map X).esymm := funext $ λ n, (finset.univ.esymm_map_val X n).symm lemma aeval_esymm_eq_multiset_esymm [algebra R S] (f : σ → S) (n : ℕ) : aeval f (esymm σ R n) = (finset.univ.val.map f).esymm n := by simp_rw [esymm, aeval_sum, aeval_prod, aeval_X, esymm_map_val] /-- We can define `esymm σ R n` by summing over a subtype instead of over `powerset_len`. -/ lemma esymm_eq_sum_subtype (n : ℕ) : esymm σ R n = ∑ t : {s : finset σ // s.card = n}, ∏ i in (t : finset σ), X i := sum_subtype _ (λ _, mem_powerset_len_univ_iff) _ /-- We can define `esymm σ R n` as a sum over explicit monomials -/ lemma esymm_eq_sum_monomial (n : ℕ) : esymm σ R n = ∑ t in powerset_len n univ, monomial (∑ i in t, finsupp.single i 1) 1 := begin simp_rw monomial_sum_one, refl, end @[simp] lemma esymm_zero : esymm σ R 0 = 1 := by simp only [esymm, powerset_len_zero, sum_singleton, prod_empty] lemma map_esymm (n : ℕ) (f : R →+* S) : map f (esymm σ R n) = esymm σ S n := by simp_rw [esymm, map_sum, map_prod, map_X] lemma rename_esymm (n : ℕ) (e : σ ≃ τ) : rename e (esymm σ R n) = esymm τ R n := calc rename e (esymm σ R n) = ∑ x in powerset_len n univ, ∏ i in x, X (e i) : by simp_rw [esymm, map_sum, map_prod, rename_X] ... = ∑ t in powerset_len n (univ.map e.to_embedding), ∏ i in t, X i : by simp [finset.powerset_len_map, -finset.map_univ_equiv] ... = ∑ t in powerset_len n univ, ∏ i in t, X i : by rw finset.map_univ_equiv lemma esymm_is_symmetric (n : ℕ) : is_symmetric (esymm σ R n) := by { intro, rw rename_esymm } lemma support_esymm'' (n : ℕ) [decidable_eq σ] [nontrivial R] : (esymm σ R n).support = (powerset_len n (univ : finset σ)).bUnion (λ t, (finsupp.single (∑ (i : σ) in t, finsupp.single i 1) (1:R)).support) := begin rw esymm_eq_sum_monomial, simp only [← single_eq_monomial], convert finsupp.support_sum_eq_bUnion (powerset_len n (univ : finset σ)) _, intros s t hst, rw finset.disjoint_left, simp only [finsupp.support_single_ne_zero _ one_ne_zero, mem_singleton], rintro a h rfl, have := congr_arg finsupp.support h, rw [finsupp.support_sum_eq_bUnion, finsupp.support_sum_eq_bUnion] at this, { simp only [finsupp.support_single_ne_zero _ one_ne_zero, bUnion_singleton_eq_self] at this, exact absurd this hst.symm }, all_goals { intros x y, simp [finsupp.support_single_disjoint] } end lemma support_esymm' (n : ℕ) [decidable_eq σ] [nontrivial R] : (esymm σ R n).support = (powerset_len n (univ : finset σ)).bUnion (λ t, {∑ (i : σ) in t, finsupp.single i 1}) := begin rw support_esymm'', congr, funext, exact finsupp.support_single_ne_zero _ one_ne_zero end lemma support_esymm (n : ℕ) [decidable_eq σ] [nontrivial R] : (esymm σ R n).support = (powerset_len n (univ : finset σ)).image (λ t, ∑ (i : σ) in t, finsupp.single i 1) := by { rw support_esymm', exact bUnion_singleton } lemma degrees_esymm [nontrivial R] (n : ℕ) (hpos : 0 < n) (hn : n ≤ fintype.card σ) : (esymm σ R n).degrees = (univ : finset σ).val := begin classical, have : (finsupp.to_multiset ∘ λ (t : finset σ), ∑ (i : σ) in t, finsupp.single i 1) = finset.val, { funext, simp [finsupp.to_multiset_sum_single] }, rw [degrees_def, support_esymm, sup_image, this, ←comp_sup_eq_sup_comp], { obtain ⟨k, rfl⟩ := nat.exists_eq_succ_of_ne_zero hpos.ne', simpa using powerset_len_sup _ _ (nat.lt_of_succ_le hn) }, { intros, simp only [union_val, sup_eq_union], congr }, { refl } end end elementary_symmetric end mv_polynomial
37ad3d1b1ff65130bab8ea90fef4bca387004867
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/casesOnCases.lean
68b737f6894be72329864a27187d9e695cc8da19
[ "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
326
lean
import Lean @[inline] def pred? (x : Nat) : Option Nat := match x with | 0 => none | x+1 => some x def isZero (x : Nat) := match pred? x with | some _ => false | none => true #eval Lean.Compiler.compile #[``isZero] -- set_option trace.Compiler.simp true -- TODO: uncomment #eval Lean.Compiler.compile #[``isZero]
f7245bf02bbf1defca079df5c3bd584759dbcc20
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/predicate/lemmas.lean
59f8548c4b479d1d11b8f0df9619ccfd5bb8871b
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
35,359
lean
import util.data.fin import util.predicate.basic import tactic.tauto namespace predicate universe variables u u' u₀ u₁ u₂ variables {α : Sort u₀} variables {β : Sort u₁} variables {γ : Sort u₂} variables {σ : Sort u'} @[simp, predicate] lemma value_proj (p : var β γ) (f : var α β) (x : α) : (p ! f).apply x = p.apply (f.apply x) := by { cases p, cases f, refl } @[simp, predicate] lemma contramap_apply (p : var α γ) (f : var β α) (x : β) : x ⊨ (p ! f) = f.apply x ⊨ p := by { cases p , cases f, refl } @[simp, predicate] lemma p_and_to_fun (p₀ p₁ : pred' α) (x : α) : x ⊨ p_and p₀ p₁ ↔ x ⊨ p₀ ∧ x ⊨ p₁ := by refl @[simp, predicate] lemma p_impl_to_fun (p₀ p₁ : pred' α) (x : α) : x ⊨ p_impl p₀ p₁ ↔ (x ⊨ p₀ → x ⊨ p₁) := by refl @[simp, predicate] lemma p_equiv_to_fun (p₀ p₁ : pred' α) (x : α) : x ⊨ p_equiv p₀ p₁ ↔ (x ⊨ p₀ ↔ x ⊨ p₁) := by { simp with lifted_fn } lemma p_impl_revert {Γ p q : pred' α} (h : Γ ⊢ p_impl p q) : Γ ⊢ p → Γ ⊢ q := begin intros h₁, constructor, introv h₂, apply h.apply _ h₂, apply h₁.apply _ h₂, end instance imp_to_fun ⦃α⦄ ⦃Γ p q : pred' α⦄ : has_coe_to_fun (Γ ⊢ p_impl p q) := { F := λ _,(Γ ⊢ p) → (Γ ⊢ q) , coe := p_impl_revert } lemma p_imp_ext {Γ p q : pred' α} (h : ∀ σ, σ ⊨ Γ → σ ⊨ p → σ ⊨ q) : Γ ⊢ p ⟶ q := ⟨ h ⟩ lemma p_imp_sem {Γ p q : pred' α} (h : Γ ⊢ p ⟶ q) : ∀ σ, σ ⊨ Γ → σ ⊨ p → σ ⊨ q := h.apply lemma p_entails_of_fun (p₀ p₁ : pred' α) : p_entails p₀ p₁ ↔ ∀ Γ, Γ ⊢ p₀ → Γ ⊢ p₁ := begin split ; intros h _, { intro h', apply h Γ h' }, { constructor, introv h₀ h₁, apply (h ⟨ eq σ ⟩ _).apply σ rfl, constructor, introv h, cases h, assumption, } end @[simp] lemma False_eq_false (Γ : pred' β) : Γ ⊢ False ↔ Γ = False := begin split ; intro h, { cases h with h, cases Γ with Γ, simp [False,lifted₀], funext σ, specialize h σ, apply eq_false_intro, intro h', apply h h' }, { rw h, constructor, intro, exact id } end @[simp, predicate] lemma False_sem (σ : β) : σ ⊨ False ↔ false := by simp with predicate @[simp] lemma True_eq_true (Γ : pred' β) : Γ ⊢ True = true := by { apply eq_true_intro, constructor, intros, trivial } @[simp] lemma True_holds : ⊩ @True β := by simp [holds] @[simp] lemma coe_true : (true : pred' α) = True := rfl @[simp] lemma coe_false : (false : pred' α) = False := rfl @[simp, predicate] lemma True_sem (σ : β) : σ ⊨ True ↔ true := by simp [holds] lemma p_forall_revert {Γ} {p : β → pred' α} (h : Γ ⊢ p_forall p) : Π i, Γ ⊢ p i := begin introv, constructor, introv h₂, apply h.apply _ h₂, end instance forall_to_fun {Γ : pred' α} ⦃p : β → pred' α⦄ : has_coe_to_fun (Γ ⊢ p_forall p) := { F := λ _, Π i, (Γ ⊢ p i) , coe := p_forall_revert } -- instance : has_coe Prop (pred' α) := -- ⟨ lifted₀ ⟩ instance proof_coe (p : Prop) (Γ : pred' α) : has_coe p (Γ ⊢ p) := ⟨ assume h, ⟨ λ x _, h ⟩ ⟩ -- instance to_prop_to_pred : has_coe (α → Prop) (pred' α) := -- ⟨ pred'.mk ⟩ @[simp, predicate] lemma sem_coe (p : Prop) (x : β) : x ⊨ (p : pred' β) ↔ p := by refl @[simp, predicate] lemma sem_seq (σ : γ) (f : var γ (α → β)) (x : var γ α) : σ ⊨ var_seq f x = (σ ⊨ f) (σ ⊨ x) := by { cases x, cases f, simp [var_seq], } instance var_lawful_functor (α : Type u) : is_lawful_functor (var α) := by { constructor ; intros ; cases x ; refl } instance var_lawful_applicative (α : Type u) : is_lawful_applicative (var α) := by { constructor ; intros ; casesm* var _ _ ; refl } instance (α : Type u) : is_lawful_monad (var α) := { pure_bind := by { intros, cases h : f x, simp! [h], } , bind_assoc := by { intros ; cases x, simp!, funext, cases (f $ x i), refl } , map_pure := by { intros ; casesm* var _ _ ; refl } , seq_pure := by { intros ; casesm* var _ _ ; refl } , seq_assoc := by intros ; casesm* var _ _ ; refl , bind_map_eq_seq := by intros ; casesm* var _ _ ; refl , bind_pure_comp_eq_map := by intros ; casesm* var _ _ ; refl } -- , ..predicate.var_lawful_applicative α } -- , ..(predicate.var_lawful_applicative α).to_is_lawful_functor } @[simp, predicate] lemma var_map_coe {α β σ : Type u} (f : α → β) (g : σ → α) : ⟨ f ⟩!⟨ g ⟩ = ⟨ f ∘ g ⟩ := by { simp [proj] } @[simp, predicate] lemma map_proj {α β γ σ : Type u} (f : α → β) (v₁ : var σ γ) (v₀ : var γ α) : ⟨ f ⟩ ! (v₀ ! v₁) = ⟨ λ x, f $ v₀.apply $ v₁.apply x ⟩ := by { cases v₀, cases v₁, simp } @[simp, predicate] lemma var_seq_coe {α β σ : Type u} (f : σ → α → β) (g : σ → α) : (⟨ f ⟩ : var _ _) <*> ⟨ g ⟩ = (⟨ λ s : σ, f s (g s) ⟩ : var σ β) := by { simp [has_seq.seq] } @[simp, predicate] lemma models_lt {α : Type u} [has_lt α] {s : σ} (x y : var σ α) : s ⊨ x ≺ y ↔ x.apply s < y.apply s := by { cases x, cases y, refl } @[simp, predicate] lemma models_le {α : Type u} [has_le α] {s : σ} (x y : var σ α) : s ⊨ x ≼ y ↔ x.apply s ≤ y.apply s := by { cases x, cases y, refl } @[simp, predicate] lemma models_wf {_ : has_well_founded α} (s : σ) (x y : var σ α) : s ⊨ x ≺≺ y ↔ x.apply s << y.apply s := by { cases x, cases y, refl } @[simp, predicate] lemma models_eq {s : σ} (x y : var σ α) : s ⊨ x ≃ y ↔ x.apply s = y.apply s := by { cases x, cases y, refl } @[simp, predicate] lemma models_mem {α β : Type _} {s : σ} [has_mem α β] (x : var σ α) (y : var σ β) : s ⊨ (x ∊ y) ↔ x.apply s ∈ y.apply s := by { cases x, cases y, refl } @[simp, predicate] lemma coe_value {s : σ} (x : α) : (x : var σ α).apply s = x := rfl @[simp, predicate] lemma coe_fun {s : σ} (x : σ → α) : (⟨ x ⟩ : var σ α).apply s = x s := rfl @[simp, predicate] lemma coe_wf_coe {s : σ} (x y : α) : (x : var σ α) ≺≺ y = ↑(x << y) := rfl @[simp] lemma eq_judgement {p : pred' α} (σ : α) : ⟨ eq σ ⟩ ⊢ p ↔ σ ⊨ p := by { split ; intro h, { apply h.apply σ, exact rfl }, { constructor, intros _ h', cases h', assumption } } @[simp, predicate] lemma models_prop {p : Prop} (σ : α) : σ ⊨ ↑p ↔ p := by refl @[simp, predicate] lemma models_lifted₀ {p : Prop} (σ : α) : σ ⊨ lifted₀ p ↔ p := by refl @[simp, predicate] lemma models_pred {p : α → β} (σ : α) : σ ⊨ ⟨ p ⟩ = p σ := by refl @[extensionality, priority 0] lemma var_ext_sem {p q : var α β} (h : ∀ σ, p.apply σ = q.apply σ) : p = q := begin cases p, cases q, congr, funext y, simp with predicate at h, rw h end @[extensionality] lemma pred_ext_sem {p q : pred' α} (h : ∀ σ, σ ⊨ p ↔ σ ⊨ q) : p = q := begin apply var_ext_sem, simp [h] end lemma pred_ext {p q : pred' α} (h : ∀ Γ, Γ ⊢ p ↔ Γ ⊢ q) : p = q := begin cases p, cases q, congr, funext y, specialize h ⟨eq y⟩, simp with predicate at h, rw h, end lemma entails_of_pointwise {p q : pred' β} (h : ∀ σ, σ ⊨ p → σ ⊨ q) : p ⟹ q := begin intros _, constructor, introv h', apply h, end lemma entails_of_forall_impl {p q : pred' β} (h : p ⟹ q) : ∀ i, i ⊨ p ⟶ q := by { intros i hp, apply (h ⟨eq i⟩).apply i rfl hp, } lemma ew_str {p : pred' β} : ⊩ p → ∀ x, x ⊨ p := by { intros h _, apply (h ⟨eq x⟩).apply _ rfl } lemma ew_wk {p : pred' β} : (∀ x, x ⊨ p) → ⊩ p := by { intros h Γ, constructor, intros, apply h } lemma ew_wk' {Γ p : pred' β} : (∀ x, x ⊨ Γ → x ⊨ p) → Γ ⊢ p := by { intros h, constructor, apply h } lemma judgement_sem {Γ p : pred' β} : Γ ⊢ p → (∀ x, x ⊨ Γ → x ⊨ p) := by { intros h σ hΓ, apply h.apply _ hΓ } section open interactive interactive.types lean lean.parser tactic tactic.interactive (simp dsimp unfold_coes) local postfix `?`:9001 := optional local postfix *:9001 := many meta def using_idents := (tk "using" *> ident*) <|> pure [] meta def lifted_asm (v Γ : expr) (rs : parse simp_arg_list) (h : name) : tactic unit := do h' ← get_local h, p ← to_expr ``(p_imp_sem %%h' %%v %%Γ) <|> to_expr ``(judgement_sem %%h' %%v %%Γ) <|> to_expr ``(ew_str %%h' %%v) <|> fail format!"assumtion {h} should be `⊩ p` or `p ⟹ q` or `Γ ⊢ p ⟶ q`", h ← note h none p, let l := loc.ns [some h.local_pp_name], try $ unfold_coes l, try $ simp none ff rs [] l, try (clear h') meta def keep_flag := (tt <$ tk "keep") <|> pure ff precedence `keep`:0 meta def lifted_pred (keep_Γ : parse keep_flag) (no_dflt : parse only_flag) (rs : parse simp_arg_list) (hs : parse using_idents) : tactic unit := do b ← tt <$ `[apply p_imp_ext _] <|> ff <$ `[apply pred_ext_sem] <|> ff <$ `[apply var_ext_sem] <|> tt <$ `[apply ew_wk' _] <|> ff <$ `[apply ew_wk _], v ← intro1, hΓ ← if b then intro1 else return (default _), mmap' (lifted_asm v hΓ rs) (hs : list _), when (b ∧ ¬ keep_Γ) $ clear hΓ, try (simp none no_dflt rs [`predicate] (loc.ns [none])), try (dsimp no_dflt rs [`predicate] (loc.ns [none])), try `[unfold_coes], try reflexivity run_cmd add_interactive [`lifted_pred] end @[simp, predicate] lemma value_coe_comp (x : α) (v : var β γ) : (x : var γ α) ! v = (x : var β α) := by lifted_pred @[simp, predicate] lemma True_comp (v : var β γ) : True ! v = True := by lifted_pred @[simp, predicate] lemma False_comp (v : var β γ) : False ! v = False := by lifted_pred @[simp] lemma proj_assoc (x : var α β) (y : var β γ) (z : var γ σ) : (z ! y) ! x = z ! (y ! x) := by lifted_pred @[simp] lemma p_and_comp (p q : pred' α) (f : var β α) : ((p ⋀ q) ! f) = (p ! f) ⋀ (q ! f) := by lifted_pred @[simp] lemma const_over_comp (p : γ) (v : var β α) : (p : var α γ) ! v = ↑p := by lifted_pred @[predicate] lemma coe_over_comp' (p : α → γ) (f : β → α) : ⟨ p ⟩ ! ⟨ f ⟩ = ⟨ p ∘ f ⟩ := by lifted_pred -- @[simp] lemma coe_over_comp (p : α → γ) (f : β → α) : (⟨ p ∘ f ⟩ : var _ _) = ⟨ p ⟩ ! ⟨ f ⟩ := by lifted_pred @[simp] lemma p_or_comp (p q : pred' α) (f : var β α) : ((p ⋁ q) ! f) = (p ! f) ⋁ (q ! f) := by lifted_pred @[simp, predicate] lemma eq_comp (p q : var α γ) (f : var β α) : ((p ≃ q) ! f) = (p ! f) ≃ (q ! f) := by lifted_pred @[simp, predicate] lemma wf_comp {_ : has_well_founded γ} (p q : var α γ) (f : var β α) : ((p ≺≺ q) ! f) = (p ! f) ≺≺ (q ! f) := by lifted_pred @[simp, predicate] lemma lt_comp {γ : Type _} [has_lt γ] (p q : var α γ) (f : var β α) : ((p ≺ q) ! f) = ((p ! f) ≺ (q ! f)) := by lifted_pred @[simp, predicate] lemma mem_comp {α γ} [has_mem α γ] (p : var σ α) (q : var σ γ) (f : var β σ) : ((p ∊ q) ! f) = ((p ! f) ∊ (q ! f)) := by lifted_pred @[simp, predicate] lemma coe_apply (v : var α β) : (⟨ v.apply ⟩ : var _ _) = v := by lifted_pred @[simp, predicate] lemma p_exists_comp {t} (p : t → pred' α) (f : var β α) : (p_exists p ! f) = (∃∃ x, p x ! f) := by lifted_pred [p_exists] @[simp] lemma coe_to_prop_p_and (p q : α → Prop) : (⟨λ s, p s ∧ q s⟩ : pred' α) = ⟨p⟩ ⋀ ⟨q⟩ := rfl @[simp] lemma coe_to_prop_p_or (p q : α → Prop) : (⟨λ s, p s ∨ q s⟩ : pred' α) = ⟨p⟩ ⋁ ⟨q⟩ := rfl @[simp] lemma coe_to_prop_p_not (p : α → Prop) : (⟨λ s, ¬ p s⟩ : pred' α) = - ⟨p⟩ := rfl @[simp] lemma coe_to_prop_p_equiv (p q : α → Prop) : (⟨λ s, p s ↔ q s⟩ : pred' α) = ⟨p⟩ ≡ ⟨q⟩ := by { ext, simp } lemma lifting_prop_asm (Γ : pred' α) {p : Prop} {q : pred' α} (h : p → Γ ⊢ q) : Γ ⊢ p → Γ ⊢ q := begin intro h₁, constructor, introv h₂, have h₃ := h₁.apply _ h₂, apply (h h₃).apply _ h₂, end @[simp, predicate] lemma p_not_to_fun (p₀ : pred' α) (x : α) : x ⊨ (- p₀) ↔ ¬ x ⊨ p₀ := by { refl, } lemma p_not_eq_not (p : pred' β) (x : β) : ¬ x ⊨ p ↔ x ⊨ (-p) := by refl @[simp] lemma p_not_True : (- True : pred' α) = (False) := by lifted_pred @[simp] lemma p_not_False : (- False : pred' α) = True := by lifted_pred -- @[simp] -- lemma entails_True (p q : pred' α) -- : p ⟹ q ↔ (∀ h, h ⟹ p → h ⟹ q) := -- begin -- split ; intro h, -- { intros h₀ h₁, }, -- end @[simp] lemma entails_True (p : pred' α) : p ⟹ True := by lifted_pred @[simp] lemma True_p_and (p : pred' α) : True ⋀ p = p := by lifted_pred @[simp] lemma p_and_True (p : pred' α) : p ⋀ True = p := by lifted_pred @[simp] lemma True_p_or (p : pred' α) : True ⋁ p = True := by lifted_pred @[simp] lemma p_or_False (p : pred' α) : p ⋁ False = p := by lifted_pred @[simp] lemma False_p_or (p : pred' α) : False ⋁ p = p := by lifted_pred @[refl] lemma entails_refl (p : pred' β) : p ⟹ p := by lifted_pred @[refl] lemma ctx_impl_refl (Γ p : pred' β) : ctx_impl Γ p p := by lifted_pred lemma p_impl_refl (Γ p : pred' β) : Γ ⊢ p ⟶ p := by lifted_pred @[simp,predicate] lemma p_impl_refl_eq_True (p : pred' β) : p ⟶ p = True := by lifted_pred @[refl] lemma v_eq_refl (Γ : pred' β) (v : var β α) : Γ ⊢ v ≃ v := by lifted_pred lemma v_eq_symm {Γ : pred' β} {v₀ v₁ : var β α} (h : Γ ⊢ v₁ ≃ v₀) : Γ ⊢ v₀ ≃ v₁ := by lifted_pred using h ; rw h @[mono] lemma ctx_p_or_p_imp_p_or' {Γ p p' q q' : pred' α} (hp : ctx_impl Γ p p') (hq : ctx_impl Γ q q') : ctx_impl Γ (p ⋁ q) (p' ⋁ q') := by { lifted_pred using hp hq, begin [smt] intros, destruct a end, } @[mono] lemma p_or_p_imp_p_or' {p p' q q' : pred' α} (hp : p ⟹ p') (hq : q ⟹ q') : (p ⋁ q) ⟹ (p' ⋁ q') := by { lifted_pred using hp hq, apply or.imp hp hq, } @[mono] lemma p_and_p_imp_p_and' {p p' q q' : pred' α} (hp : p ⟹ p') (hq : q ⟹ q') : (p ⋀ q) ⟹ (p' ⋀ q') := by { lifted_pred only using hp hq, apply and.imp hp hq, } lemma p_or_p_imp_p_or {p p' q q' : pred' α} {τ} (hp : τ ⊨ p ⟶ p') (hq : τ ⊨ q ⟶ q') : τ ⊨ p ⋁ q → τ ⊨ p' ⋁ q' := by apply or.imp hp hq @[mono] lemma ctx_p_and_p_imp_p_and_right' {Γ p p' q q' : pred' α} (hp : ctx_impl Γ p p') (hq : ctx_impl Γ q q') : ctx_impl Γ ( p ⋀ q ) ( p' ⋀ q' ) := by { lifted_pred using hp hq, intros, tauto } lemma ctx_p_and_p_imp_p_and' {Γ p p' q q' : pred' α} (hp : ctx_impl Γ p p') (hq : ctx_impl Γ q q') : ctx_impl Γ (p ⋀ q) (p' ⋀ q') := by { lifted_pred using hp hq, begin [smt] intros end, } lemma p_or_p_imp_p_or_right {p q q' : pred' α} {τ} (hq : τ ⊨ q ⟶ q') : τ ⊨ p ⋁ q → τ ⊨ p ⋁ q' := by apply or.imp id hq lemma p_or_p_imp_p_or_left {p p' q : pred' α} {τ} (hp : τ ⊨ p ⟶ p') : τ ⊨ p ⋁ q → τ ⊨ p' ⋁ q := by apply or.imp hp id lemma p_imp_p_imp_p_imp {p p' q q' : pred' α} {Γ} (hp : Γ ⊢ p' ⟶ p) (hq : Γ ⊢ q ⟶ q') : Γ ⊢ p ⟶ q → Γ ⊢ p' ⟶ q' := by { intro h₂, constructor, introv h₀ h₁, replace hp := hp.apply _ h₀, replace hq := hq.apply _ h₀, replace h₂ := h₂.apply _ h₀, apply_assumption, solve_by_elim, } lemma revert_p_imp {p q : pred' α} (h : ⊩ p ⟶ q) : p ⊢ q := begin constructor, intro, exact (h True).apply σ trivial, end lemma revert_p_imp' {p q r : pred' α} (h : p ⟹ q) : q ⊢ r → p ⊢ r := by { intro h₀, constructor, introv h₁, apply h₀.apply, apply (h p).apply _ h₁ h₁, } @[simp] lemma from_True {p : pred' α} : True ⊢ p ↔ ⊩ p := by { unfold holds ; split ; intro h, intro, apply revert_p_imp' _ h, simp, apply h } lemma intro_p_imp {p q : pred' α} (h : p ⊢ q) : ⊩ p ⟶ q := begin intro, constructor, introv h', apply h.apply, end @[mono] lemma p_imp_entails_p_imp {p p' q q' : pred' α} (hp : p' ⟹ p) (hq : q ⟹ q') : ( p ⟶ q ) ⟹ ( p' ⟶ q' ) := by { lifted_pred using hp hq, intros, repeat { apply_assumption }, } lemma p_imp_p_imp_p_imp_left {p p' q : pred' α} {Γ} (hp : Γ ⊢ p' ⟶ p) : Γ ⊢ p ⟶ q → Γ ⊢ p' ⟶ q := p_imp_p_imp_p_imp hp (ctx_impl_refl _ _) lemma p_imp_p_imp_p_imp_right {p q q' : pred' α} {Γ} (hq : Γ ⊢ q ⟶ q') : Γ ⊢ p ⟶ q → Γ ⊢ p ⟶ q' := p_imp_p_imp_p_imp (ctx_impl_refl _ _) hq lemma ctx_imp_entails_p_imp {Γ p p' q q' : pred' α} (hp : ctx_impl Γ p' p) (hq : ctx_impl Γ q q') : ctx_impl Γ ( p ⟶ q ) ( p' ⟶ q' ) := by { lifted_pred using hp hq, intros, apply_assumption, solve_by_elim } @[mono] lemma ctx_imp_entails_p_imp_left {Γ p p' q q' : pred' α} (hp : ctx_impl Γ p' p) (hq : ctx_impl Γ q q') : ctx_impl Γ ( p ⟶ q ) ( p' ⟶ q' ) := by { lifted_pred using hp hq, intros, apply_assumption, tauto } lemma entails_imp_entails_left {p p' q : pred' α} (hp : p' ⟹ p) : ( p ⟹ q ) → ( p' ⟹ q ) := begin intros h₁ Γ, constructor, introv h₂ h₃, apply (h₁ Γ).apply _ h₂, apply (hp Γ).apply _ h₂ h₃, end @[simp] lemma p_or_self (p : pred' β) : p ⋁ p = p := by lifted_pred @[simp] lemma p_not_p_not_iff_self (p : pred' β) : - - p = p := by lifted_pred [not_not_iff_self] lemma p_not_eq_iff_eq_p_not (p q : pred' β) : - p = q ↔ p = - q := by { split ; intro h, rw [← h,p_not_p_not_iff_self], rw [h,p_not_p_not_iff_self], } @[simp] lemma p_not_eq_p_not_iff_eq (p q : pred' β) : - p = - q ↔ p = q := by simp [p_not_eq_iff_eq_p_not] lemma p_and_over_or_left (p q r : pred' β) : p ⋀ (q ⋁ r) = (p ⋀ q) ⋁ (p ⋀ r) := begin lifted_pred, split, { begin [smt] intros, eblast end }, { begin [smt] intros, destruct a end }, end lemma p_and_over_or_right (p q r : pred' β) : (q ⋁ r) ⋀ p = (q ⋀ p) ⋁ (r ⋀ p) := begin lifted_pred, split, { begin [smt] intros, eblast end }, { begin [smt] intros, destruct a end }, end instance : is_left_distrib (pred' β) (⋀) (⋁) := ⟨ p_and_over_or_left ⟩ instance : is_right_distrib (pred' β) (⋀) (⋁) := ⟨ by { intros, apply p_and_over_or_right } ⟩ instance : is_left_id (pred' β) (⋀) True := ⟨ by simp ⟩ instance : is_right_id (pred' β) (⋀) True := ⟨ by simp ⟩ instance or_left_id : is_left_id (pred' β) (⋁) False := ⟨ by simp ⟩ instance or_right_id : is_right_id (pred' β) (⋁) False := ⟨ by simp ⟩ lemma p_or_over_and_left (p q r : pred' β) : p ⋁ (q ⋀ r) = (p ⋁ q) ⋀ (p ⋁ r) := begin lifted_pred, split, { begin [smt] intros, destruct a end }, { begin [smt] intros, destruct a.left, end }, end lemma p_or_over_and_right (p q r : pred' β) : (q ⋀ r) ⋁ p = (q ⋁ p) ⋀ (r ⋁ p) := by { lifted_pred [distrib_left_or] } instance is_left_distrib_or_and : is_left_distrib (pred' β) (⋁) (⋀) := ⟨ p_or_over_and_left ⟩ instance is_right_distrib_or_and : is_right_distrib (pred' β) (⋁) (⋀) := ⟨ by { intros, apply p_or_over_and_right } ⟩ lemma mutual_p_imp {Γ p q : pred' β} (h₀ : Γ ⊢ p ⟶ q) (h₁ : Γ ⊢ q ⟶ p) : Γ ⊢ p ≡ q := begin lifted_pred using h₀ h₁, split ; assumption, end lemma mutual_entails {p q : pred' β} (h₀ : p ⟹ q) (h₁ : q ⟹ p) : p = q := begin lifted_pred using h₀ h₁, split ; assumption, end @[simp] lemma False_entails (p : pred' β) : False ⟹ p := by lifted_pred @[simp] lemma p_imp_False (p : pred' β) : p ⟶ False = -p := by lifted_pred lemma p_and_p_not_self (p : pred' β) : p ⋀ -p = False := by lifted_pred @[simp] lemma p_or_p_not_self (p : pred' β) : p ⋁ -p = True := by lifted_pred [classical.em] lemma em (p : pred' β) : ⊩ p ⋁ -p := by lifted_pred [classical.em] lemma p_and_p_or_p_not_self (p q : pred' β) : p ⋀ (q ⋁ -p) = p ⋀ q := by simp [p_and_over_or_left,p_and_p_not_self] lemma p_not_and_self (p : pred' β) : (-p) ⋀ p = False := by lifted_pred lemma p_not_p_and (p q : pred' β) : - (p ⋀ q) = -p ⋁ -q := by lifted_pred [classical.not_and_iff_not_or_not] lemma p_not_p_or (p q : pred' β) : - (p ⋁ q) = -p ⋀ -q := by lifted_pred [not_or_iff_not_and_not] lemma p_not_and_self_or (p q : pred' β) : - p ⋀ (p ⋁ q) = -p ⋀ q := by rw [p_and_over_or_left,p_not_and_self,False_p_or] @[simp, predicate] lemma p_exists_apply {t : Sort u'} {P : t → pred' β} (σ : β) : σ ⊨ (∃∃ x, P x) ↔ (∃ x, σ ⊨ P x) := by { unfold p_exists } lemma p_exists_to_fun {t : Sort u'} {h : pred' β} {P : t → pred' β} (x : t) (Hh : h ⊢ P x) : h ⊢ (∃∃ x, P x) := by { constructor, intros _ h', existsi x, apply Hh.apply _ h', } @[simp, predicate] lemma models_p_forall {t : Sort u'} (P : t → pred' β) (σ : β) : σ ⊨ (∀∀ x, P x) ↔ (∀ x, σ ⊨ P x) := by refl lemma p_forall_to_fun {t : Sort u'} (h : pred' β) (P : t → pred' β) : h ⊢ (∀∀ x, P x) ↔ (∀ x, h ⊢ P x) := begin split ; intro h, { intro, constructor, intros, cases h with h, apply h σ a, }, { constructor, introv h' x, apply (h x).apply _ h', } end lemma p_forall_subtype_to_fun {t : Sort u'} (h : pred' β) (p : t → Prop) (q : t → pred' β) : h ⊢ (∀∀ x, p x ⟶ q x) ↔ (∀ x, p x → h ⊢ q x) := begin split, { intros h x hp, apply h x hp }, { intros h, constructor, introv hσ x hp, apply (h x hp).apply _ hσ, } end lemma ew_p_forall {t} (p : t → pred' β) : ⊩ (∀∀ x, p x) ↔ ∀ x, ⊩ p x := by { simp only [holds,forall_swap] { single_pass := tt }, apply forall_congr, intro, apply p_forall_to_fun } lemma p_not_p_exists {t : Sort*} (p : t → pred' β) : (- ∃∃ x, p x) = (∀∀ x, -p x) := by lifted_pred [not_exists_iff_forall_not,p_exists] lemma p_not_p_forall {t : Sort*} (p : t → pred' β) : (- ∀∀ x, p x) = (∃∃ x, -p x) := by { rw [p_not_eq_iff_eq_p_not,p_not_p_exists], simp [p_not_p_not_iff_self] } lemma p_exists_p_imp {t} (p : t → pred' β) (q : pred' β) : (∃∃ x, p x) ⟶ q = (∀∀ x, p x ⟶ q) := by lifted_pred [p_exists] lemma p_or_comm (p q : pred' β) : p ⋁ q = q ⋁ p := by lifted_pred [or_comm] lemma p_or_assoc (p q r : pred' β) : p ⋁ (q ⋁ r) = p ⋁ q ⋁ r := by lifted_pred [or_assoc] instance p_or_is_assoc : is_associative (pred' β) (⋁) := ⟨ by { intros, rw p_or_assoc, } ⟩ instance p_or_is_comm : is_commutative (pred' β) (⋁) := ⟨ by apply p_or_comm ⟩ lemma p_and_comm (p q : pred' β) : p ⋀ q = q ⋀ p := by lifted_pred [and_comm] lemma p_and_assoc (p q r : pred' β) : p ⋀ (q ⋀ r) = p ⋀ q ⋀ r := by lifted_pred [and_assoc] instance p_and_is_assoc : is_associative (pred' β) (⋀) := ⟨ by { intros, rw p_and_assoc, } ⟩ instance p_and_is_comm : is_commutative (pred' β) (⋀) := ⟨ by apply p_and_comm ⟩ @[simp] lemma p_and_p_imp (p q r : pred' β) : p ⋀ q ⟶ r = p ⟶ (q ⟶ r) := by lifted_pred -- lemma p_imp_intro_wrong (Γ p q : pred' β) -- (h : Γ ⊢ p → Γ ⊢ q) -- : Γ ⊢ p ⟶ q := -- sorry lemma p_imp_intro (p q r : pred' β) (h : ∀ Γ, Γ ⊢ p → Γ ⊢ q → Γ ⊢ r) (Γ : pred' β) (h' : Γ ⊢ p) : Γ ⊢ q ⟶ r := begin constructor, introv hΓ hq, apply (h ⟨eq σ⟩ _ _).apply _ rfl ; constructor ; intros _ h ; cases h, { apply h'.apply _ hΓ }, assumption end @[simp] lemma p_or_intro_left (p q : pred' β) : p ⟹ p ⋁ q := by { lifted_pred, begin [smt] intros end } @[simp] lemma p_or_intro_right (p q : pred' β) : q ⟹ p ⋁ q := by { lifted_pred, begin [smt] intros end } @[simp] lemma p_and_intro (p q : pred' β) : p ⟹ (q ⟶ p ⋀ q) := by { lifted_pred, begin [smt] intros end } lemma p_or_entails_of_entails' {Γ p q r : pred' β} (h₀ : Γ ⊢ p ⟶ r) (h₁ : Γ ⊢ q ⟶ r) : Γ ⊢ p ⋁ q ⟶ r := by { constructor, simp_intros _ hΓ _, have h₀ := h₀.apply σ hΓ, simp at h₀, have h₁ := h₁.apply σ hΓ, simp at h₁, begin [smt] intros, destruct a, end } lemma p_or_entails_of_entails {p q r : pred' β} (h₀ : p ⟹ r) (h₁ : q ⟹ r) : p ⋁ q ⟹ r := by { lifted_pred using h₀ h₁, begin [smt] intros, destruct a end } lemma entails_p_or_of_entails_left {p q r : pred' β} (h₀ : p ⟹ q) : p ⟹ q ⋁ r := by { lifted_pred using h₀, begin [smt] intros end } lemma entails_p_or_of_entails_right {p q r : pred' β} (h₀ : p ⟹ r) : p ⟹ q ⋁ r := by { lifted_pred using h₀, begin [smt] intros end } lemma entails_p_and_of_entails {p q r : pred' β} (h₀ : p ⟹ q) (h₁ : p ⟹ r) : p ⟹ q ⋀ r := by { lifted_pred using h₀ h₁, begin [smt] intros end } lemma p_and_entails_of_entails_left {p q r : pred' β} (h₁ : p ⟹ r) : p ⋀ q ⟹ r := by { lifted_pred using h₁, begin [smt] intros end } lemma p_and_entails_of_entails_right {p q r : pred' β} (h₁ : q ⟹ r) : p ⋀ q ⟹ r := by { lifted_pred using h₁, begin [smt] intros end } @[simp] lemma p_and_elim_left (p q : pred' β) : p ⋀ q ⟹ p := by { lifted_pred, begin [smt] intros end } @[simp] lemma p_and_elim_right (p q : pred' β) : p ⋀ q ⟹ q := by lifted_pred lemma judgement.left {Γ p q : pred' β} (h : Γ ⊢ p ⋀ q) : Γ ⊢ p := p_and_elim_left p q Γ h lemma judgement.right {Γ p q : pred' β} (h : Γ ⊢ p ⋀ q) : Γ ⊢ q := p_and_elim_right p q Γ h lemma p_imp_trans {Γ p q r : pred' β} (h₀ : Γ ⊢ p ⟶ q) (h₁ : Γ ⊢ q ⟶ r) : Γ ⊢ p ⟶ r := begin lifted_pred using h₀ h₁, intros, solve_by_elim, end @[trans] lemma entails_trans {p q r : pred' β} (h₀ : p ⟹ q) (h₁ : q ⟹ r) : p ⟹ r := begin lifted_pred using h₀ h₁, intro, solve_by_elim, end @[simp] lemma p_not_comp' (p : pred' α) (f : var β α) : -p ! f = -(p ! f) := by lifted_pred lemma p_not_comp (p : pred' α) (f : var β α) : -(p ! f) = -p ! f := by lifted_pred @[mono] lemma comp_entails_comp {p q : pred' β} (f : var α β) (H : p ⟹ q) : p ! f ⟹ q ! f := begin intros Γ, constructor, introv h hp, simp at ⊢ hp, specialize H ⟨eq $ f.apply σ⟩, apply H.apply (f.apply σ) rfl hp, end @[mono] lemma ctx_comp_imp_comp {Γ : pred' α} {p q : pred' β} (f : var α β) (H : p ⟹ q) : ctx_impl Γ (p ! f) (q ! f) := by apply comp_entails_comp _ H @[mono] lemma ctx_p_not_entails_p_not_right {Γ p q : pred' β} (h : ctx_impl Γ q p) : ctx_impl Γ (- p) (- q) := by { lifted_pred using h, begin [smt] intros end } @[mono] lemma p_not_entails_p_not_right {p q : pred' β} (h : q ⟹ p) : - p ⟹ - q := by { lifted_pred using h, begin [smt] intros end } lemma entails_of_eq (p q : pred' β) (h : p = q) : p ⟹ q := by simp [h] lemma p_imp_of_equiv {Γ : pred' β} (p q : pred' β) (h : Γ ⊢ p ≡ q) : Γ ⊢ p ⟶ q := by lifted_pred using h ; simp [h] lemma equiv_of_eq (Γ p q : pred' β) (h : p = q) : Γ ⊢ p ≡ q := by { cases p, cases q, simp [h] } lemma p_and_entails_p_or (p q : pred' β) : p ⋀ q ⟹ p ⋁ q := by { lifted_pred, begin [smt] intros end } @[simp] lemma True_p_imp (p : pred' β) : True ⟶ p = p := by lifted_pred @[simp] lemma p_imp_True (p : pred' β) : p ⟶ True = True := by lifted_pred @[simp] lemma p_forall_True : (∀∀ x : α, @True β) = True := by lifted_pred @[simp] lemma p_exists_True [nonempty α] : (∃∃ x : α, @True β) = True := by { lifted_pred, apply classical.exists_true_of_nonempty, apply_instance } lemma ew_eq_true {p : pred' β} : ⊩ p → p = True := by { intro h, lifted_pred using h, begin [smt] intros end } @[mono, priority 0] lemma ew_imp_ew {p q : pred' β} (H : p ⟹ q) : ⊩ p → ⊩ q := by { intros hp, lifted_pred using hp H, solve_by_elim } lemma entails_to_pointwise {p q : pred' β} (h : p ⟹ q) : ∀ i, i ⊨ p → i ⊨ q := by { intros i h', apply (h ⟨eq i⟩).apply i rfl h' } lemma impl_of_p_impl {p q : pred' β} (i : β) (h : ⊩ p ⟶ q) : i ⊨ p → i ⊨ q := entails_of_forall_impl h _ open interactive.types interactive open lean.parser lean tactic (hiding funext) meta def entails_or_ew {α : Type u} (t : expr) (tag : string) (ent_tac ew_tac : tactic α) : tactic α := do match t with | `(_ ⟹ _) := ew_tac | `(_ ⊢ _) := ent_tac | `(⊩ _) := ew_tac | _ := fail format!"expecting {tag} of shape `_ ⟹ _` or `⊩ _`" end meta def pointwise (h : parse (many ident)) (ids : parse with_ident_list) : tactic unit := do t ← target, try $ entails_or_ew t "goal" `[refine revert_p_imp _,refine ew_wk _] `[refine ew_wk _], tactic.intro_lst ids, ls ← mmap get_local h, mmap' (λ l : expr, do entails_or_ew t "goal" (to_expr ``(ew_str (intro_p_imp %%l))) (to_expr ``(ew_str %%l)) >>= note l.local_pp_name none, try (clear l)) ls run_cmd add_interactive [`pointwise] lemma p_or_over_p_exists_left {t} (p : t → pred' β) (q : pred' β) {w : t → pred' β} (h : ⊩ ∃∃ x : t, w x) : q ⋁ (∃∃ x, p x) = (∃∃ x, q ⋁ p x) := begin lifted_pred, have h := (h ⟨eq σ⟩).apply _ rfl, have _inst : nonempty t := nonempty_of_exists h, resetI, simp [distrib_or_over_exists_left,p_exists], end @[congr] lemma {v} p_exists_congr {α : Sort u} {β : Sort v} {p q : α → pred' β} (h : ∀ i, p i = q i) : p_exists p = p_exists q := begin lifted_pred [p_exists], rw [exists_congr], intro, rw h, end lemma p_and_over_p_exists_right {t} (p : t → pred' β) (q : pred' β) : (∃∃ x, p x) ⋀ q = (∃∃ x, p x ⋀ q) := by lifted_pred only [iff_self, exists_and_distrib_right] lemma p_and_over_p_exists_left {t} (p : pred' β) (q : t → pred' β) : p ⋀ (∃∃ x, q x) = (∃∃ x, p ⋀ q x) := begin rw [p_and_comm,p_and_over_p_exists_right], apply p_exists_congr, intro, simp [p_and_comm] end lemma shunting {β : Sort*} (p q r : pred' β) : p ⟶ q ⋁ r = (p ⋀ - q) ⟶ r := begin lifted_pred, begin [smt] split, all_goals { intros }, by_cases (q.apply σ), end, end lemma shunting' {β : Sort*} (p q r : pred' β) : p ⟶ (q ⟶ r) = (p ⋀ q) ⟶ r := by lifted_pred lemma imp_swap {β : Sort*} (p q r : pred' β) : p ⟶ (q ⟶ r) = q ⟶ (p ⟶ r) := by { lifted_pred, begin [smt] split, all_goals { intros }, end } lemma entails_swap {β : Sort*} (p q r : pred' β) : p ⟹ (q ⟶ r) ↔ q ⟹ (p ⟶ r) := by simp [p_entails,imp_swap] -- ◻◇p ⊢ ◻◇q τ -- `τ : stream σ, h : (◻◇p) τ ⊢ (◻◇q) τ` lemma p_not_p_imp {β : Sort*} (p q : pred' β) : (-p) ⟶ q = p ⋁ q := by rw [← True_p_and (-p),← shunting,True_p_imp] lemma p_imp_iff_p_not_p_or {β : Sort*} (p q : pred' β) : p ⟶ q = -p ⋁ q := by rw [← p_not_p_imp,p_not_p_not_iff_self] lemma p_or_not_and {β : Sort*} (p q : pred' β) : p ⋁ (- p ⋀ q) = p ⋁ q := begin lifted_pred, begin [smt] split, all_goals { intros h }, destruct h, by_cases (p.apply σ) end end lemma p_exists_intro {t : Sort u'} {p : t → pred' β} (x : t) : p x ⟹ (∃∃ x, p x) := by { lifted_pred, apply exists.intro x, } lemma p_exists_elim {t : Sort u'} {p : t → pred' β} {q : pred' β} (H : ∀ x, p x ⟹ q) : (∃∃ x, p x) ⟹ q := begin pointwise with σ, simp, intro, apply entails_to_pointwise (H x) σ, end lemma p_forall_p_imp_p_forall {Γ : pred' β} {t : Sort u'} (p q : t → pred' β) : Γ ⊢ (∀∀ x, p x ⟶ q x) → Γ ⊢ (∀∀ x, p x) ⟶ (∀∀ x, q x) := begin intros h, lifted_pred [- exists_imp_distrib] using h, apply forall_imp_forall, intro x, apply h, end lemma p_exists_p_imp_p_exists {Γ : pred' β} {t : Sort u'} (p q : t → pred' β) : Γ ⊢ (∀∀ x, p x ⟶ q x) → Γ ⊢ (∃∃ x, p x) ⟶ (∃∃ x, q x) := begin intros h, lifted_pred [- exists_imp_distrib] using h, apply exists_imp_exists, intro x, apply h, end lemma p_exists_entails_p_exists {t : Sort u'} (p q : t → pred' β) : (∀ x, p x ⟹ q x) → (∃∃ x, p x) ⟹ (∃∃ x, q x) := begin intros h _, apply p_exists_p_imp_p_exists, constructor, introv h' x, apply (h x Γ).apply _ h' end lemma p_exists_over_p_or {t} (p q : t → pred' β) : (∃∃ x, p x) ⋁ (∃∃ x, q x) = (∃∃ x, p x ⋁ q x) := begin lifted_pred, split ; simp_intros ; cases a with a_1 a_1 ; revert a_1, { apply exists_imp_exists, intro, apply or.intro_left, }, { apply exists_imp_exists, intro, apply or.intro_right, }, apply or.imp ; apply Exists.intro a_1, end @[simp] lemma p_exists_imp_eq_p_forall_imp (p : α → pred' β) (q : pred' β) : ((∃∃ x, p x) ⟶ q) = (∀∀ x, p x ⟶ q) := by lifted_pred lemma p_exists_entails_eq_p_forall_entails (p : α → pred' β) (q : pred' β) : ((∃∃ x, p x) ⟹ q) ↔ (∀ x, p x ⟹ q) := by simp [p_entails,p_exists_imp_eq_p_forall_imp,ew_p_forall] lemma p_exists_imp_p_exists' {t : Sort u₀} {t' : Sort u₂} {Γ : pred' β} (p : t → pred' β) (q : t' → pred' β) (f : t → t') (h : Γ ⊢ (∀∀ x, p x ⟶ q (f x))) : Γ ⊢ (∃∃ x, p x) ⟶ (∃∃ x, q x) := begin intros, lifted_pred keep [- exists_imp_distrib], apply exists_imp_exists' f _ , intro x, apply (h.apply _ a), end lemma p_exists_entails_p_exists' {t : Sort u₀} {t' : Sort u₂} (p : t → pred' β) (q : t' → pred' β) (f : t → t') (h : (∀ x, p x ⟹ q (f x))) : (∃∃ x, p x) ⟹ (∃∃ x, q x) := begin intro, apply p_exists_imp_p_exists' _ _ f, apply (ew_p_forall _).mpr h, end lemma p_exists_variable_change (p : α → pred' β) (q : γ → pred' β) (f : α → γ) (g : γ → α) (Hf : ∀ i, p i ⟹ q (f i)) (Hg : ∀ j, q j ⟹ p (g j)) : (∃∃ i, p i) = (∃∃ j, q j) := begin lifted_pred [- exists_imp_distrib], rw exists_variable_change _ _ f g ; intro x ; apply entails_to_pointwise ; solve_by_elim, end lemma p_exists_partial_intro {t : Sort u₀} {t' : Sort u₂} (p : t → pred' β) (f : t' → t) : (∃∃ x, p (f x)) ⟹ (∃∃ x, p x) := begin intro, apply p_exists_imp_p_exists' _ _ f, lifted_pred, end lemma p_exists_range_subtype {α : Sort u} (p : α → Prop) (q : α → pred' β) : (∃∃ i, p i ⋀ q i : pred' β) = (∃∃ j : subtype p, q (j.val)) := by lifted_pred lemma p_or_iff_not_imp (p q : pred' β) : p ⋁ q = - p ⟶ q := begin lifted_pred, simp [or_iff_not_imp], end lemma p_forall_fin_zero (p : fin 0 → pred' β) : (∀∀ i, p i) = True := begin lifted_pred, simp [forall_fin_zero_iff_true], end lemma p_forall_split_one {n : ℕ} (p : fin (nat.succ n) → pred' β) : (∀∀ i, p i) = p fin.max ⋀ (∀∀ i, restr p i) := begin lifted_pred, simp [forall_split_one], refl, end lemma p_exists_split_one {n : ℕ} (p : fin (nat.succ n) → pred' β) : (∃∃ i, p i) = p fin.max ⋁ (∃∃ i, restr p i) := begin lifted_pred, simp [exists_split_one], refl, end @[simp] lemma whole_v_eq_prj (x : var α α) (y : var γ α) : (whole ≃ x) ! y = y ≃ (x ! y) := by lifted_pred @[simp] lemma models_whole (s : σ) : s ⊨ whole = s := rfl instance entails_category {α} : category (@p_entails α) := { ident := by { intro, refl } , comp := by { intros, apply entails_trans ; assumption } , assoc := by { intros, refl } , left_ident := by { intros, refl } , right_ident := by { intros, refl } } end predicate
b2f82bd9ae7255543e9f670aaaaddded3aeec9b1
315b4184091c669ce8e5e07f9b24473c4bcfbaaf
/library/init/meta/interactive.lean
8e6f9a987ed56f231c3e921fe8e82161ffeef2e4
[ "Apache-2.0" ]
permissive
haraldschilly/lean
78404910ad4c258cdf84e0509e4348c1525e57a9
d01e2d7ae8250e8f69139d8cb37950079e76ca9d
refs/heads/master
1,619,977,395,095
1,517,501,044,000
1,517,940,670,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
67,965
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators import init.meta.interactive_base init.meta.derive init.meta.match_tactic import init.meta.congr_tactic open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit meta def propagate_tags (tac : tactic unit) : tactic unit := do tag ← get_main_tag, if tag = [] then tac else focus1 $ do tac, gs ← get_goals, when (bnot gs.empty) $ do new_tag ← get_main_tag, when new_tag.empty $ with_enable_tags (set_main_tag tag) meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit := mcond tags_enabled (do in_tag ← get_main_tag, r ← tac, /- remove assigned metavars -/ r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m, match r with | [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/ | _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag)) end) (tac >> skip) /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ meta def intro : parse ident_? → tactic unit | none := propagate_tags (intro1 >> skip) | (some h) := propagate_tags (tactic.intro h >> skip) /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := propagate_tags (tactic.intros >> skip) | hs := propagate_tags (intro_lst hs >> skip) /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := propagate_tags (tactic.introv ns >> return ()) /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` to `h₂` in the current local context. -/ meta def rename (h₁ h₂ : parse ident) : tactic unit := propagate_tags (tactic.rename h₁ h₂) /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h) /-- Similar to the `apply` tactic, but does not reorder goals. -/ meta def fapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply) /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply) /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg) /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ meta def mapply (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff}) /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- Try to apply `assumption` to all goals. -/ meta def assumption' : tactic unit := tactic.any_goals tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip) private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end @[derive has_reflect] meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep @[derive has_reflect] meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) /-- `rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. `rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `rewrite`. -/ meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- `rewrite` followed by `assumption`. -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `erewrite`. -/ meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) precedence `generalizing` : 0 private meta def collect_hyps_uids : tactic name_set := do ctx ← local_context, return $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set private meta def revert_new_hyps (input_hyp_uids : name_set) : tactic unit := do ctx ← local_context, let to_revert := ctx.foldr (λ h r, if input_hyp_uids.contains h.local_uniq_name then r else h::r) [], tag ← get_main_tag, m ← revert_lst to_revert, set_main_tag (mk_num_name `_case m :: tag) /-- Apply `t` to main goal, and revert any new hypothesis in the generated goals, and tag generated goals when using supported tactics such as: `induction`, `apply`, `cases`, `constructor`, ... This tactic is useful for writing robust proof scripts that are not sensitive to the name generation strategy used by `t`. ``` example (n : ℕ) : n = n := begin with_cases { induction n }, case nat.zero { reflexivity }, case nat.succ : n' ih { reflexivity } end ``` TODO(Leo): improve docstring -/ meta def with_cases (t : itactic) : tactic unit := with_enable_tags $ focus1 $ do input_hyp_uids ← collect_hyps_uids, t, all_goals (revert_new_hyps input_hyp_uids) private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type, return I private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize e x >> intro1 >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h meta def cases_arg_p : parser (option name × pexpr) := with_desc "(id :)? expr" $ do t ← texpr, match t with | (local_const x _ _ _) := (tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t) | _ := pure (none, t) end /-- Given the initial tag `in_tag` and the cases names produced by `induction` or `cases` tactic, update the tag of the new subgoals. -/ private meta def set_cases_tags (in_tag : tag) (rs : list name) : tactic unit := do te ← tags_enabled, gs ← get_goals, match gs with | [g] := when te (set_tag g in_tag) -- if only one goal was produced, we should not make the tag longer | _ := do let tgs : list (name × expr) := rs.map₂ (λ n g, (n, g)) gs, if te then tgs.mmap' (λ ⟨n, g⟩, set_tag g (n::in_tag)) /- If `induction/cases` is not in a `with_cases` block, we still set tags using `_case_simple` to make sure we can use the `case` notation. ``` induction h, case c { ... } ``` -/ else tgs.mmap' (λ ⟨n, g⟩, with_enable_tags (set_tag g (`_case_simple::n::[]))) end private meta def set_induction_tags (in_tag : tag) (rs : list (name × list expr × list (name × expr))) : tactic unit := set_cases_tags in_tag (rs.map (λ e, e.1)) /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically. `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. `induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do in_tag ← get_main_tag, focus1 $ do { -- process `h : t` case e ← match hp with | (some h, p) := do x ← mk_fresh_name, generalize h () (p, x), get_local x | (none, p) := i_to_expr p end, -- generalize major premise e ← if e.is_local_constant then pure e else tactic.generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, t ← whnf_ginductive t, const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst, rs ← tactic.induction e ids rec_name, all_goals $ do { intron n, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear) }, set_induction_tags in_tag rs } private meta def is_case_simple_tag : tag → bool | (`_case_simple :: _) := tt | _ := ff private meta def is_case_tag : tag → option nat | (name.mk_numeral n `_case :: _) := some n.val | _ := none private meta def tag_match (t : tag) (pre : list name) : bool := pre.is_prefix_of t.reverse && ((is_case_tag t).is_some || is_case_simple_tag t) private meta def collect_tagged_goals (pre : list name) : tactic (list expr) := do gs ← get_goals, gs.mfoldr (λ g r, do t ← get_tag g, if tag_match t pre then return (g::r) else return r) [] private meta def find_tagged_goal_aux (pre : list name) : tactic expr := do gs ← collect_tagged_goals pre, match gs with | [] := fail ("invalid `case`, there is no goal tagged with prefix " ++ to_string pre) | [g] := return g | gs := do tags : list (list name) ← gs.mmap get_tag, fail ("invalid `case`, there is more than one goal tagged with prefix " ++ to_string pre ++ ", matching tags: " ++ to_string tags) end private meta def find_tagged_goal (pre : list name) : tactic expr := match pre with | [] := do g::gs ← get_goals, return g | _ := find_tagged_goal_aux pre <|> -- try to resolve constructor names, and try again do env ← get_env, pre ← pre.mmap (λ id, (do r_id ← resolve_constant id, if (env.inductive_type_of r_id).is_none then return id else return r_id) <|> return id), find_tagged_goal_aux pre end private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr) | case e := if e.has_meta_var then match e with | (mvar _ _ _) := do case ← case, guard $ e ∈ goals, pure (case, e) | (app _ _) := let idx := match e.get_app_fn with | const (name.mk_string rec ty') _ := guard (ty' = ty) >> match mk_simple_name rec with | `drec := some idx | `rec := some idx -- indices + major premise | `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1) | _ := none end | _ := none end in match idx with | none := list.foldl (<|>) (find_case case e.get_app_fn) $ e.get_app_args.map (find_case case) | some idx := let args := e.get_app_args in do arg ← args.nth idx, args.enum.foldl (λ acc ⟨i, arg⟩, match acc with | some _ := acc | _ := if i ≠ idx then find_case none arg else none end) -- start recursion with likely case (find_case (some arg) arg) end | (lam _ _ _ e) := find_case case e | (macro n args) := list.foldl (<|>) none $ args.map (find_case case) | _ := none end else none private meta def rename_lams : expr → list name → tactic unit | (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns) | _ _ := skip /-- Focuses on the `induction`/`cases`/`with_cases` subgoal corresponding to the given tag prefix, optionally renaming introduced locals. ``` example (n : ℕ) : n = n := begin induction n, case nat.zero { reflexivity }, case nat.succ : a ih { reflexivity } end ``` -/ meta def case (pre : parse ident_*) (ids : parse $ (tk ":" *> ident_*)?) (tac : itactic) : tactic unit := do g ← find_tagged_goal pre, tag ← get_tag g, let ids := ids.get_or_else [], match is_case_tag tag with | some n := do let m := ids.length, gs ← get_goals, set_goals $ g :: gs.filter (≠ g), intro_lst ids, when (m < n) $ intron (n - m), solve1 tac | none := match is_case_simple_tag tag with | tt := /- Use the old `case` implementation -/ do r ← result, env ← get_env, [ctor_id] ← return pre, ctor ← resolve_constant ctor_id <|> fail ("'" ++ to_string ctor_id ++ "' is not a constructor"), ty ← (env.inductive_type_of ctor).to_monad <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), let ctors := env.constructors_of ty, let idx := env.inductive_num_params ty + /- motive -/ 1 + list.index_of ctor ctors, /- Remark: we now use `find_case` just to locate the `lambda` used in `rename_lams`. The goal is now located using tags. -/ (case, _) ← (find_case [g] ty idx (env.inductive_num_indices ty) none r ).to_monad <|> fail "could not find open goal of given case", gs ← get_goals, set_goals $ g :: gs.filter (≠ g), rename_lams case ids, solve1 tac | ff := failed end end /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct meta def cases_core (e : expr) (ids : list name := []) : tactic unit := do in_tag ← get_main_tag, focus1 $ do rs ← tactic.cases e ids, set_cases_tags in_tag rs /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit | (none, p) ids := do e ← i_to_expr p, cases_core e ids | (some h, p) ids := do x ← mk_fresh_name, generalize h () (p, x), hx ← get_local x, cases_core hx ids private meta def find_matching_hyp (ps : list pattern) : tactic expr := any_hyp $ λ h, do type ← infer_type h, ps.mfirst $ λ p, do match_pattern p type, return h /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then find_matching_hyp ps >>= cases_core else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core /-- Shorthand for `cases_matching` -/ meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := cases_matching rec ps private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit := any_hyp $ λ h, do I ← expr.get_app_fn <$> (infer_type h >>= head_beta), guard I.is_constant, guard (I.const_name ∈ type_names), tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip) /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit := do type_names ← type_names.mmap resolve_constant, if rec.is_none then try_cases_for_types type_names (bnot one.is_none) else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none) /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using `sorry`. -/ meta def admit : tactic unit := tactic.admit /-- Closes the main goal using `sorry`. -/ meta def «sorry» : tactic unit := tactic.admit /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit := match n with | none := tactic.iterate t | some n := iterate_exactly n t end /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ meta def repeat : itactic → tactic unit := tactic.repeat /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ meta def try : itactic → tactic unit := tactic.try /-- A do-nothing tactic that always succeeds. -/ meta def skip : tactic unit := tactic.skip /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ meta def solve1 : itactic → tactic unit := tactic.solve1 /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ meta def all_goals : itactic → tactic unit := tactic.all_goals /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ meta def any_goals : itactic → tactic unit := tactic.any_goals /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ meta def focus (tac : itactic) : tactic unit := tactic.focus1 tac private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr e >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr e >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit := «have» h t none >> tactic.swap /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := concat_tags tactic.constructor /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ meta def econstructor : tactic unit := concat_tags tactic.econstructor /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ meta def left : tactic unit := concat_tags tactic.left /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ meta def right : tactic unit := concat_tags tactic.right /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ meta def split : tactic unit := concat_tags tactic.split private meta def constructor_matching_aux (ps : list pattern) : tactic unit := do t ← target, ps.mfirst (λ p, match_pattern p t), constructor meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then constructor_matching_aux ps else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps /-- Replaces the target of the main goal by `false`. -/ meta def exfalso : tactic unit := tactic.exfalso /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types @[derive has_reflect] meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /- Return (hs, gex, hex, all) -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := (e::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)" private meta def check_no_overload (p : pexpr) : tactic unit := when p.is_choice_macro $ match p with | macro _ ps := fail $ to_fmt "ambiguous overload, possible interpretations" ++ format.join (ps.map (λ p, (to_fmt p).indent 4)) | _ := failed end private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) := do p ← resolve_name n, check_no_overload p, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (clear h)) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. `simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. `simp *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. `simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ meta def simp (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := let cfg := if use_iota_eqn.is_none then cfg else {iota_eqn := tt, ..cfg} in propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat) /-- Just construct the simp set and trace it. Used for debugging. -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (es : list pexpr) : list simp_arg_type := es.map simp_arg_type.expr /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := do ls ← local_context, n ← revert_lst ls, dsimp_target s u cfg, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ meta def symmetry : tactic unit := tactic.symmetry /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ meta def ac_reflexivity : tactic unit := tactic.ac_refl /-- An abbreviation for `ac_reflexivity`. -/ meta def ac_refl : tactic unit := tactic.ac_refl /-- Tries to prove the main goal using congruence closure. -/ meta def cc : tactic unit := tactic.cc /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) /-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ meta def subst_vars : tactic unit := tactic.subst_vars /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) /-- Similar to `unfold`, but only uses definitional equalities. -/ meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) (constructor_eq := ff) namespace interactive open interactive interactive.types expr /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat /-- Similar to `unfold`, but does not iterate the unfolding. -/ meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ meta def apply_opt_param : tactic unit := tactic.apply_opt_param /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ meta def apply_auto_param : tactic unit := tactic.apply_auto_param /-- Fails if the given tactic succeeds. -/ meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac /-- Succeeds if the given tactic fails. -/ meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ meta def guard_hyp (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type, guard_expr_eq h p /-- `match_target t` fails if target does not match pattern `t`. -/ meta def match_target (t : parse texpr) (m := reducible) : tactic unit := tactic.match_target t m >> skip /-- `by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute classical.prop_decidable [instance]`. -/ meta def by_cases : parse cases_arg_p → tactic unit | (n, q) := concat_tags $ do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h), pos_g :: neg_g :: rest ← get_goals, return [(`pos, pos_g), (`neg, neg_g)] /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ meta def funext : parse ident_* → tactic unit | [] := tactic.funext >> skip | hs := funext_lst hs >> skip /-- If the target of the main goal is a proposition `p`, `by_contradiction h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute classical.prop_decidable [instance]`. -/ meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () /-- An abbreviation for `by_contradiction`. -/ meta def by_contra (n : parse ident?) : tactic unit := by_contradiction n /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ meta def specialize (p : parse texpr) : tactic unit := do e ← i_to_expr p, let h := expr.get_app_fn e, if h.is_local_constant then tactic.note h.local_pp_name none e >> try (tactic.clear h) else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" meta def congr := tactic.congr meta def rel_congr := tactic.rel_congr end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := `tactic.interactive <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns meta def has_dup : tactic bool := do ctx ← local_context, let p : name_set × bool := ctx.foldl (λ ⟨s, r⟩ h, if r then (s, r) else if s.contains h.local_pp_name then (s, tt) else (s.insert h.local_pp_name, ff)) (mk_name_set, ff), return p.2 /-- Renames hypotheses with the same name. -/ meta def dedup : tactic unit := mwhen has_dup $ do ctx ← local_context, n ← revert_lst ctx, intron n end add_interactive namespace tactic /- Helper tactic for `mk_inj_eq -/ protected meta def apply_inj_lemma : tactic unit := do h ← intro `h, some (lhs, rhs) ← expr.is_eq <$> infer_type h, (expr.const C _) ← return lhs.get_app_fn, applyc (name.mk_string "inj" C), assumption /- Auxiliary tactic for proving `I.C.inj_eq` lemmas. These lemmas are automatically generated by the equation compiler. Example: ``` list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) := by mk_inj_eq ``` -/ meta def mk_inj_eq : tactic unit := `[ intros, /- We use `_root_.*` in the following tactics because names are resolved at tactic execution time in interactive mode. See PR #1913 TODO(Leo): This is probably not the only instance of this problem. `[ ... ] blocks are convenient to use because they allow us to use the interactive mode to write non interactive tactics. One potential fix for this issue is to resolve names in `[ ... ] at tactic compilation time. After this issue is fixed, we should remove the `_root_.*` workaround. -/ apply _root_.propext, apply _root_.iff.intro, { tactic.apply_inj_lemma }, { intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } } ] end tactic /- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/ universes u v lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) := by tactic.mk_inj_eq lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) := by tactic.mk_inj_eq
81a813b6102458effbf12214598c6d28843b5da9
f1a12d4db0f46eee317d703e3336d33950a2fe7e
/common/algebra.lean
9eb1d18eb543259fb98815f2dd417fe8baa74bee
[ "Apache-2.0" ]
permissive
avigad/qelim
bce89b79c717b7649860d41a41a37e37c982624f
b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60
refs/heads/master
1,584,548,938,232
1,526,773,708,000
1,526,773,708,000
134,967,693
2
0
null
null
null
null
UTF-8
Lean
false
false
664
lean
lemma add_assoc' {α : Type} [add_semigroup α] : ∀ (a b c : α), a + (b + c) = a + b + c := begin intros a b c, rewrite add_assoc end lemma mul_assoc' {α : Type} [comm_semigroup α] : ∀ (a b c : α), a * (b * c) = a * b * c := begin intros a b c, rewrite mul_assoc end #check add_right_comm lemma mul_comm_assoc {α : Type} [comm_semigroup α] : ∀ a b c : α, (a * b) * c = (a * c) * b := begin intros a b c, rewrite mul_assoc, rewrite mul_comm b c, rewrite mul_assoc end lemma mul_add_mul_add {α : Type} [ring α] (t c x d : α) : (t + c * x) + (d * x) = t + ((c + d) * x) := begin rewrite add_assoc, rewrite add_mul end
fb4918502698743f37fdab7717ed3802a3528a1d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/nat_coe.lean
bb9c5280d7ce543ae45f89e682d9a36133f741e3
[ "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
447
lean
import logic namespace experiment constant nat : Type.{1} constant int : Type.{1} constant nat_add : nat → nat → nat infixl `+` := nat_add constant int_add : int → int → int infixl `+` := int_add constant of_nat : nat → int attribute of_nat [coercion] constants a b : nat constants i j : int definition c1 := a + b theorem T1 : c1 = nat_add a b := eq.refl _ definition c2 := i + j theorem T2 : c2 = int_add i j := eq.refl _ exit
562d2c940942d0b5a9138ca3b19329025202a499
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/meta_tac3.lean
b3bfd667444f0ea1c6b1b8261c63e1e4bd2158e7
[ "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
483
lean
open tactic name list set_option pp.goal.compact true set_option pp.binder_types true example : ∀ (A B : Prop), A → A ∧ B → A → A := by do intro_lst [`_, `_, `H1, `H2, `H3], trace_state, h2 ← get_local `H2, infer_type h2 >>= trace, h1 ← get_local `H1, h3 ← get_local `H3, unify h1 h3, (unify h2 h3 <|> trace "fail to unify H2 =?= H3"), assumption, trace_state, result >>= trace, trace "--------------", return ()
bec6205c1da03ac1c7e8ed7fefe3f33855d88538
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/run/concatElim.lean
ead40d45bd4e03a1d095bd0bb47012067a66d762
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,993
lean
universes u def concat {α} : List α → α → List α | [], a => [a] | x::xs, a => x :: concat xs a def last {α} : (xs : List α) → xs ≠ [] → α | [], h => absurd rfl h | [a], h => a | _::a::as, h => last (a::as) (fun h => by injection h) def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as variables {α} theorem concatEq (xs : List α) (h : xs ≠ []) : concat (dropLast xs) (last xs h) = xs := by match xs, h with | [], h => apply False.elim apply h rfl | [x], h => rfl | x₁::x₂::xs, h => have x₂::xs ≠ [] by intro h; injection h have ih := concatEq (x₂::xs) this show x₁ :: concat (dropLast (x₂::xs)) (last (x₂::xs) this) = x₁ :: x₂ :: xs rewrite ih rfl theorem lengthCons {α} (x : α) (xs : List α) : (x::xs).length = xs.length + 1 := let rec aux (a : α) (xs : List α) : (n : Nat) → (a::xs).lengthAux n = xs.lengthAux n + 1 := match xs with | [] => fun _ => rfl | x::xs => fun n => aux a xs (n+1) aux x xs 0 theorem eqNilOfLengthZero {α} : (xs : List α) → xs.length = 0 → xs = [] | [], h => rfl | x::xs, h => by rw [lengthCons] at h; injection h theorem dropLastLen {α} (xs : List α) : (n : Nat) → xs.length = n+1 → (dropLast xs).length = n := by match xs with | [] => intro _ h; injection h | [a] => intro n h have 1 = n + 1 from h have 0 = n by injection this; assumption subst this rfl | x₁::x₂::xs => intro n h cases n with | zero => rw [lengthCons, lengthCons] at h injection h with h injection h | succ n => have (x₁ :: x₂ :: xs).length = xs.length + 2 by rw [lengthCons, lengthCons] have xs.length = n by rw [this] at h; injection h with h; injection h with h; assumption have ih : (dropLast (x₂::xs)).length = xs.length from dropLastLen (x₂::xs) xs.length (lengthCons _ _) show (x₁ :: dropLast (x₂ :: xs)).length = n+1 rw [lengthCons, ih, this] @[inline] def concatElim {α} (motive : List α → Sort u) (base : Unit → motive []) (ind : (xs : List α) → (a : α) → motive xs → motive (concat xs a)) (xs : List α) : motive xs := let rec @[specialize] aux : (n : Nat) → (xs : List α) → xs.length = n → motive xs | 0, xs, h => by have aux := eqNilOfLengthZero _ h subst aux apply base () | n+1, xs, h => by have notNil : xs ≠ [] by intro h1; subst h1; injection h let ih := aux n (dropLast xs) (dropLastLen _ _ h) let aux := ind (dropLast xs) (last xs notNil) ih rw [concatEq] at aux exact aux aux xs.length xs rfl -- The generated code is tail recursive def test (xs : List Nat) : IO Unit := concatElim (motive := fun _ => IO Unit) (fun _ => pure ()) (fun xs x r => do IO.println s!"step xs: {xs} x: {x}"; r) xs #eval test [1, 2, 3, 4]
b705c43b4f7f0b2e1315271b26464c91ac942878
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/monoid.lean
305780ebd37023e3b35d9a450ec190b0574e025e
[ "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
30,841
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import algebra.big_operators.finprod import order.filter.pointwise import topology.algebra.mul_action import algebra.big_operators.pi import topology.continuous_function.basic /-! # Theory of topological monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ universes u v open classical set filter topological_space open_locale classical topology big_operators pointwise variables {ι α X M N : Type*} [topological_space X] @[to_additive] lemma continuous_one [topological_space M] [has_one M] : continuous (1 : X → M) := @continuous_const _ _ _ _ 1 /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `M`, for example, is obtained by requiring both the instances `add_monoid M` and `has_continuous_add M`. Continuity in only the left/right argument can be stated using `has_continuous_const_vadd α α`/`has_continuous_const_vadd αᵐᵒᵖ α`. -/ class has_continuous_add (M : Type u) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `M`, for example, is obtained by requiring both the instances `monoid M` and `has_continuous_mul M`. Continuity in only the left/right argument can be stated using `has_continuous_const_smul α α`/`has_continuous_const_smul αᵐᵒᵖ α`. -/ @[to_additive] class has_continuous_mul (M : Type u) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] instance : has_continuous_mul Mᵒᵈ := ‹has_continuous_mul M› @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[to_additive] instance has_continuous_mul.to_has_continuous_smul : has_continuous_smul M M := ⟨continuous_mul⟩ @[to_additive] instance has_continuous_mul.to_has_continuous_smul_op : has_continuous_smul Mᵐᵒᵖ M := ⟨show continuous ((λ p : M × M, p.1 * p.2) ∘ prod.swap ∘ prod.map mul_opposite.unop id), from continuous_mul.comp $ continuous_swap.comp $ continuous.prod_map mul_opposite.continuous_unop continuous_id⟩ @[continuity, to_additive] lemma continuous.mul {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg : _) @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul {f g : X → M} {s : set X} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma filter.tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma filter.tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds @[to_additive] lemma le_nhds_mul (a b : M) : 𝓝 a * 𝓝 b ≤ 𝓝 (a * b) := by { rw [← map₂_mul, ← map_uncurry_prod, ← nhds_prod_eq], exact continuous_mul.tendsto _ } @[simp, to_additive] lemma nhds_one_mul_nhds {M} [mul_one_class M] [topological_space M] [has_continuous_mul M] (a : M) : 𝓝 (1 : M) * 𝓝 a = 𝓝 a := ((le_nhds_mul _ _).trans_eq $ congr_arg _ (one_mul a)).antisymm $ le_mul_of_one_le_left' $ pure_le_nhds 1 @[simp, to_additive] lemma nhds_mul_nhds_one {M} [mul_one_class M] [topological_space M] [has_continuous_mul M] (a : M) : 𝓝 a * 𝓝 1 = 𝓝 a := ((le_nhds_mul _ _).trans_eq $ congr_arg _ (mul_one a)).antisymm $ le_mul_of_one_le_right' $ pure_le_nhds 1 section tendsto_nhds variables {𝕜 : Type*} [preorder 𝕜] [has_zero 𝕜] [has_mul 𝕜] [topological_space 𝕜] [has_continuous_mul 𝕜] {l : filter α} {f : α → 𝕜} {b c : 𝕜} (hb : 0 < b) lemma filter.tendsto_nhds_within_Ioi.const_mul [pos_mul_strict_mono 𝕜] [pos_mul_reflect_lt 𝕜] (h : tendsto f l (𝓝[>] c)) : tendsto (λ a, b * f a) l (𝓝[>] (b * c)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).const_mul b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_left hb).mpr) lemma filter.tendsto_nhds_within_Iio.const_mul [pos_mul_strict_mono 𝕜] [pos_mul_reflect_lt 𝕜] (h : tendsto f l (𝓝[<] c)) : tendsto (λ a, b * f a) l (𝓝[<] (b * c)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).const_mul b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_left hb).mpr) lemma filter.tendsto_nhds_within_Ioi.mul_const [mul_pos_strict_mono 𝕜] [mul_pos_reflect_lt 𝕜] (h : tendsto f l (𝓝[>] c)) : tendsto (λ a, f a * b) l (𝓝[>] (c * b)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).mul_const b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_right hb).mpr) lemma filter.tendsto_nhds_within_Iio.mul_const [mul_pos_strict_mono 𝕜] [mul_pos_reflect_lt 𝕜] (h : tendsto f l (𝓝[<] c)) : tendsto (λ a, f a * b) l (𝓝[<] (c * b)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).mul_const b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_right hb).mpr) end tendsto_nhds /-- Construct a unit from limits of units and their inverses. -/ @[to_additive filter.tendsto.add_units "Construct an additive unit from limits of additive units and their negatives.", simps] def filter.tendsto.units [topological_space N] [monoid N] [has_continuous_mul N] [t2_space N] {f : ι → Nˣ} {r₁ r₂ : N} {l : filter ι} [l.ne_bot] (h₁ : tendsto (λ x, ↑(f x)) l (𝓝 r₁)) (h₂ : tendsto (λ x, ↑(f x)⁻¹) l (𝓝 r₂)) : Nˣ := { val := r₁, inv := r₂, val_inv := by { symmetry, simpa using h₁.mul h₂ }, inv_val := by { symmetry, simpa using h₂.mul h₁ } } @[to_additive] lemma continuous_at.mul {f g : X → M} {x : X} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul {f g : X → M} {s : set X} {x : X} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨(continuous_fst.fst'.mul continuous_fst.snd').prod_mk (continuous_snd.fst'.mul continuous_snd.snd')⟩ @[to_additive] instance pi.has_continuous_mul {C : ι → Type*} [∀ i, topological_space (C i)] [∀ i, has_mul (C i)] [∀ i, has_continuous_mul (C i)] : has_continuous_mul (Π i, C i) := { continuous_mul := continuous_pi (λ i, (continuous_apply i).fst'.mul (continuous_apply i).snd') } /-- A version of `pi.has_continuous_mul` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_mul` for non-dependent functions. -/ @[to_additive "A version of `pi.has_continuous_add` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_add` for non-dependent functions."] instance pi.has_continuous_mul' : has_continuous_mul (ι → M) := pi.has_continuous_mul @[priority 100, to_additive] instance has_continuous_mul_of_discrete_topology [topological_space N] [has_mul N] [discrete_topology N] : has_continuous_mul N := ⟨continuous_of_discrete_topology⟩ open_locale filter open function @[to_additive] lemma has_continuous_mul.of_nhds_one {M : Type u} [monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : has_continuous_mul M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ p : M × M, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : M × M), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, hleft x₀, hright y₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by { rw [key, ← filter.map_map], } ... ≤ map ((λ (x : M), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← hright, hleft y₀, filter.map_map, key₂, ← hleft] end⟩ @[to_additive] lemma has_continuous_mul_of_comm_of_nhds_one (M : Type u) [comm_monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : has_continuous_mul M := begin apply has_continuous_mul.of_nhds_one hmul hleft, intros x₀, simp_rw [mul_comm, hleft x₀] end end has_continuous_mul section pointwise_limits variables (M₁ M₂ : Type*) [topological_space M₂] [t2_space M₂] @[to_additive] lemma is_closed_set_of_map_one [has_one M₁] [has_one M₂] : is_closed {f : M₁ → M₂ | f 1 = 1} := is_closed_eq (continuous_apply 1) continuous_const @[to_additive] lemma is_closed_set_of_map_mul [has_mul M₁] [has_mul M₂] [has_continuous_mul M₂] : is_closed {f : M₁ → M₂ | ∀ x y, f (x * y) = f x * f y} := begin simp only [set_of_forall], exact is_closed_Inter (λ x, is_closed_Inter (λ y, is_closed_eq (continuous_apply _) ((continuous_apply _).mul (continuous_apply _)))) end variables {M₁ M₂} [mul_one_class M₁] [mul_one_class M₂] [has_continuous_mul M₂] {F : Type*} [monoid_hom_class F M₁ M₂] {l : filter α} /-- Construct a bundled monoid homomorphism `M₁ →* M₂` from a function `f` and a proof that it belongs to the closure of the range of the coercion from `M₁ →* M₂` (or another type of bundled homomorphisms that has a `monoid_hom_class` instance) to `M₁ → M₂`. -/ @[to_additive "Construct a bundled additive monoid homomorphism `M₁ →+ M₂` from a function `f` and a proof that it belongs to the closure of the range of the coercion from `M₁ →+ M₂` (or another type of bundled homomorphisms that has a `add_monoid_hom_class` instance) to `M₁ → M₂`.", simps { fully_applied := ff }] def monoid_hom_of_mem_closure_range_coe (f : M₁ → M₂) (hf : f ∈ closure (range (λ (f : F) (x : M₁), f x))) : M₁ →* M₂ := { to_fun := f, map_one' := (is_closed_set_of_map_one M₁ M₂).closure_subset_iff.2 (range_subset_iff.2 map_one) hf, map_mul' := (is_closed_set_of_map_mul M₁ M₂).closure_subset_iff.2 (range_subset_iff.2 map_mul) hf } /-- Construct a bundled monoid homomorphism from a pointwise limit of monoid homomorphisms. -/ @[to_additive "Construct a bundled additive monoid homomorphism from a pointwise limit of additive monoid homomorphisms", simps { fully_applied := ff }] def monoid_hom_of_tendsto (f : M₁ → M₂) (g : α → F) [l.ne_bot] (h : tendsto (λ a x, g a x) l (𝓝 f)) : M₁ →* M₂ := monoid_hom_of_mem_closure_range_coe f $ mem_closure_of_tendsto h $ eventually_of_forall $ λ a, mem_range_self _ variables (M₁ M₂) @[to_additive] lemma monoid_hom.is_closed_range_coe : is_closed (range (coe_fn : (M₁ →* M₂) → (M₁ → M₂))) := is_closed_of_closure_subset $ λ f hf, ⟨monoid_hom_of_mem_closure_range_coe f hf, rfl⟩ end pointwise_limits @[to_additive] lemma inducing.has_continuous_mul {M N F : Type*} [has_mul M] [has_mul N] [mul_hom_class F M N] [topological_space M] [topological_space N] [has_continuous_mul N] (f : F) (hf : inducing f) : has_continuous_mul M := ⟨hf.continuous_iff.2 $ by simpa only [(∘), map_mul f] using (hf.continuous.fst'.mul hf.continuous.snd')⟩ @[to_additive] lemma has_continuous_mul_induced {M N F : Type*} [has_mul M] [has_mul N] [mul_hom_class F M N] [topological_space N] [has_continuous_mul N] (f : F) : @has_continuous_mul M (induced f ‹_›) _ := by { letI := induced f ‹_›, exact inducing.has_continuous_mul f ⟨rfl⟩ } @[to_additive] instance subsemigroup.has_continuous_mul [topological_space M] [semigroup M] [has_continuous_mul M] (S : subsemigroup M) : has_continuous_mul S := inducing.has_continuous_mul (⟨coe, λ _ _, rfl⟩ : mul_hom S M) ⟨rfl⟩ @[to_additive] instance submonoid.has_continuous_mul [topological_space M] [monoid M] [has_continuous_mul M] (S : submonoid M) : has_continuous_mul S := S.to_subsemigroup.has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive] lemma submonoid.top_closure_mul_self_subset (s : submonoid M) : closure (s : set M) * closure s ⊆ closure s := image2_subset_iff.2 $ λ x hx y hy, map_mem_closure₂ continuous_mul hx hy $ λ a ha b hb, s.mul_mem ha hb @[to_additive] lemma submonoid.top_closure_mul_self_eq (s : submonoid M) : closure (s : set M) * closure s = closure s := subset.antisymm s.top_closure_mul_self_subset (λ x hx, ⟨x, 1, hx, subset_closure s.one_mem, mul_one _⟩) /-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is itself a submonoid. -/ @[to_additive "The (topological-space) closure of an additive submonoid of a space `M` with `has_continuous_add` is itself an additive submonoid."] def submonoid.topological_closure (s : submonoid M) : submonoid M := { carrier := closure (s : set M), one_mem' := subset_closure s.one_mem, mul_mem' := λ a b ha hb, s.top_closure_mul_self_subset ⟨a, b, ha, hb, rfl⟩ } @[to_additive] lemma submonoid.le_topological_closure (s : submonoid M) : s ≤ s.topological_closure := subset_closure @[to_additive] lemma submonoid.is_closed_topological_closure (s : submonoid M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure @[to_additive] lemma submonoid.topological_closure_minimal (s : submonoid M) {t : submonoid M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a submonoid of a topological monoid is commutative, then so is its topological closure. -/ @[to_additive "If a submonoid of an additive topological monoid is commutative, then so is its topological closure."] def submonoid.comm_monoid_topological_closure [t2_space M] (s : submonoid M) (hs : ∀ (x y : s), x * y = y * x) : comm_monoid s.topological_closure := { mul_comm := have ∀ (x ∈ s) (y ∈ s), x * y = y * x, from λ x hx y hy, congr_arg subtype.val (hs ⟨x, hx⟩ ⟨y, hy⟩), λ ⟨x, hx⟩ ⟨y, hy⟩, subtype.ext $ eq_on_closure₂ this continuous_mul (continuous_snd.mul continuous_fst) x hx y hy, ..s.topological_closure.to_monoid } @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, is_open.mem_nhds Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma is_compact.mul {s t : set M} (hs : is_compact s) (ht : is_compact t) : is_compact (s * t) := by { rw [← image_mul_prod], exact (hs.prod ht).image continuous_mul } @[to_additive] lemma tendsto_list_prod {f : ι → α → M} {x : filter α} {a : ι → M} : ∀ l:list ι, (∀i∈l, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod {f : ι → X → M} (l : list ι) (h : ∀ i ∈ l, continuous (f i)) : continuous (λ a, (l.map (λ i, f i a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive] lemma continuous_on_list_prod {f : ι → X → M} (l : list ι) {t : set X} (h : ∀ i ∈ l, continuous_on (f i) t) : continuous_on (λ a, (l.map (λ i, f i a)).prod) t := begin intros x hx, rw continuous_within_at_iff_continuous_at_restrict _ hx, refine tendsto_list_prod _ (λ i hi, _), specialize h i hi x hx, rw continuous_within_at_iff_continuous_at_restrict _ hx at h, exact h, end @[continuity, to_additive] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := by { simp only [pow_succ], exact continuous_id.mul (continuous_pow _) } instance add_monoid.has_continuous_const_smul_nat {A} [add_monoid A] [topological_space A] [has_continuous_add A] : has_continuous_const_smul ℕ A := ⟨continuous_nsmul⟩ instance add_monoid.has_continuous_smul_nat {A} [add_monoid A] [topological_space A] [has_continuous_add A] : has_continuous_smul ℕ A := ⟨continuous_uncurry_of_discrete_topology continuous_nsmul⟩ @[continuity, to_additive continuous.nsmul] lemma continuous.pow {f : X → M} (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := (continuous_pow n).comp h @[to_additive] lemma continuous_on_pow {s : set M} (n : ℕ) : continuous_on (λ x, x ^ n) s := (continuous_pow n).continuous_on @[to_additive] lemma continuous_at_pow (x : M) (n : ℕ) : continuous_at (λ x, x ^ n) x := (continuous_pow n).continuous_at @[to_additive filter.tendsto.nsmul] lemma filter.tendsto.pow {l : filter α} {f : α → M} {x : M} (hf : tendsto f l (𝓝 x)) (n : ℕ) : tendsto (λ x, f x ^ n) l (𝓝 (x ^ n)) := (continuous_at_pow _ _).tendsto.comp hf @[to_additive continuous_within_at.nsmul] lemma continuous_within_at.pow {f : X → M} {x : X} {s : set X} (hf : continuous_within_at f s x) (n : ℕ) : continuous_within_at (λ x, f x ^ n) s x := hf.pow n @[to_additive continuous_at.nsmul] lemma continuous_at.pow {f : X → M} {x : X} (hf : continuous_at f x) (n : ℕ) : continuous_at (λ x, f x ^ n) x := hf.pow n @[to_additive continuous_on.nsmul] lemma continuous_on.pow {f : X → M} {s : set X} (hf : continuous_on f s) (n : ℕ) : continuous_on (λ x, f x ^ n) s := λ x hx, (hf x hx).pow n /-- Left-multiplication by a left-invertible element of a topological monoid is proper, i.e., inverse images of compact sets are compact. -/ lemma filter.tendsto_cocompact_mul_left {a b : M} (ha : b * a = 1) : filter.tendsto (λ x : M, a * x) (filter.cocompact M) (filter.cocompact M) := begin refine filter.tendsto.of_tendsto_comp _ (filter.comap_cocompact_le (continuous_mul_left b)), convert filter.tendsto_id, ext x, simp [ha], end /-- Right-multiplication by a right-invertible element of a topological monoid is proper, i.e., inverse images of compact sets are compact. -/ lemma filter.tendsto_cocompact_mul_right {a b : M} (ha : a * b = 1) : filter.tendsto (λ x : M, x * a) (filter.cocompact M) (filter.cocompact M) := begin refine filter.tendsto.of_tendsto_comp _ (filter.comap_cocompact_le (continuous_mul_right b)), convert filter.tendsto_id, ext x, simp [ha], end /-- If `R` acts on `A` via `A`, then continuous multiplication implies continuous scalar multiplication by constants. Notably, this instances applies when `R = A`, or when `[algebra R A]` is available. -/ @[priority 100, to_additive "If `R` acts on `A` via `A`, then continuous addition implies continuous affine addition by constants."] instance is_scalar_tower.has_continuous_const_smul {R A : Type*} [monoid A] [has_smul R A] [is_scalar_tower R A A] [topological_space A] [has_continuous_mul A] : has_continuous_const_smul R A := { continuous_const_smul := λ q, begin simp only [←smul_one_mul q (_ : A)] { single_pass := tt }, exact continuous_const.mul continuous_id, end } /-- If the action of `R` on `A` commutes with left-multiplication, then continuous multiplication implies continuous scalar multiplication by constants. Notably, this instances applies when `R = Aᵐᵒᵖ` -/ @[priority 100, to_additive "If the action of `R` on `A` commutes with left-addition, then continuous addition implies continuous affine addition by constants. Notably, this instances applies when `R = Aᵃᵒᵖ`. "] instance smul_comm_class.has_continuous_const_smul {R A : Type*} [monoid A] [has_smul R A] [smul_comm_class R A A] [topological_space A] [has_continuous_mul A] : has_continuous_const_smul R A := { continuous_const_smul := λ q, begin simp only [←mul_smul_one q (_ : A)] { single_pass := tt }, exact continuous_id.mul continuous_const, end } end has_continuous_mul namespace mul_opposite /-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/ @[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."] instance [topological_space α] [has_mul α] [has_continuous_mul α] : has_continuous_mul αᵐᵒᵖ := ⟨continuous_op.comp (continuous_unop.snd'.mul continuous_unop.fst')⟩ end mul_opposite namespace units open mul_opposite variables [topological_space α] [monoid α] [has_continuous_mul α] /-- If multiplication on a monoid is continuous, then multiplication on the units of the monoid, with respect to the induced topology, is continuous. Inversion is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_inv` has not yet been defined. -/ @[to_additive "If addition on an additive monoid is continuous, then addition on the additive units of the monoid, with respect to the induced topology, is continuous. Negation is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_neg` has not yet been defined."] instance : has_continuous_mul αˣ := inducing_embed_product.has_continuous_mul (embed_product α) end units @[to_additive] lemma continuous.units_map [monoid M] [monoid N] [topological_space M] [topological_space N] (f : M →* N) (hf : continuous f) : continuous (units.map f) := units.continuous_iff.2 ⟨hf.comp units.continuous_coe, hf.comp units.continuous_coe_inv⟩ section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := is_open.mem_nhds oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : multiset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simpa using tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : finset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[continuity, to_additive] lemma continuous_multiset_prod {f : ι → X → M} (s : multiset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λ a, (s.map (λ i, f i a)).prod) := by { rcases s with ⟨l⟩, simpa using continuous_list_prod l } @[to_additive] lemma continuous_on_multiset_prod {f : ι → X → M} (s : multiset ι) {t : set X} : (∀i ∈ s, continuous_on (f i) t) → continuous_on (λ a, (s.map (λ i, f i a)).prod) t := by { rcases s with ⟨l⟩, simpa using continuous_on_list_prod l } @[continuity, to_additive] lemma continuous_finset_prod {f : ι → X → M} (s : finset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λ a, ∏ i in s, f i a) := continuous_multiset_prod _ @[to_additive] lemma continuous_on_finset_prod {f : ι → X → M} (s : finset ι) {t : set X} : (∀ i ∈ s, continuous_on (f i) t) → continuous_on (λ a, ∏ i in s, f i a) t := continuous_on_multiset_prod _ @[to_additive] lemma eventually_eq_prod {X M : Type*} [comm_monoid M] {s : finset ι} {l : filter X} {f g : ι → X → M} (hs : ∀ i ∈ s, f i =ᶠ[l] g i) : ∏ i in s, f i =ᶠ[l] ∏ i in s, g i := begin replace hs: ∀ᶠ x in l, ∀ i ∈ s, f i x = g i x, { rwa eventually_all_finset }, filter_upwards [hs] with x hx, simp only [finset.prod_apply, finset.prod_congr rfl hx], end open function @[to_additive] lemma locally_finite.exists_finset_mul_support {M : Type*} [comm_monoid M] {f : ι → X → M} (hf : locally_finite (λ i, mul_support $ f i)) (x₀ : X) : ∃ I : finset ι, ∀ᶠ x in 𝓝 x₀, mul_support (λ i, f i x) ⊆ I := begin rcases hf x₀ with ⟨U, hxU, hUf⟩, refine ⟨hUf.to_finset, mem_of_superset hxU $ λ y hy i hi, _⟩, rw [hUf.coe_to_finset], exact ⟨y, hi, hy⟩ end @[to_additive] lemma finprod_eventually_eq_prod {M : Type*} [comm_monoid M] {f : ι → X → M} (hf : locally_finite (λ i, mul_support (f i))) (x : X) : ∃ s : finset ι, ∀ᶠ y in 𝓝 x, (∏ᶠ i, f i y) = ∏ i in s, f i y := let ⟨I, hI⟩ := hf.exists_finset_mul_support x in ⟨I, hI.mono (λ y hy, finprod_eq_prod_of_mul_support_subset _ $ λ i hi, hy hi)⟩ @[to_additive] lemma continuous_finprod {f : ι → X → M} (hc : ∀ i, continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i, f i x) := begin refine continuous_iff_continuous_at.2 (λ x, _), rcases finprod_eventually_eq_prod hf x with ⟨s, hs⟩, refine continuous_at.congr _ (eventually_eq.symm hs), exact tendsto_finset_prod _ (λ i hi, (hc i).continuous_at), end @[to_additive] lemma continuous_finprod_cond {f : ι → X → M} {p : ι → Prop} (hc : ∀ i, p i → continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i (hi : p i), f i x) := begin simp only [← finprod_subtype_eq_finprod_cond], exact continuous_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective) end end instance [topological_space M] [has_mul M] [has_continuous_mul M] : has_continuous_add (additive M) := { continuous_add := @continuous_mul M _ _ _ } instance [topological_space M] [has_add M] [has_continuous_add M] : has_continuous_mul (multiplicative M) := { continuous_mul := @continuous_add M _ _ _ } section lattice_ops variables {ι' : Sort*} [has_mul M] @[to_additive] lemma has_continuous_mul_Inf {ts : set (topological_space M)} (h : Π t ∈ ts, @has_continuous_mul M t _) : @has_continuous_mul M (Inf ts) _ := { continuous_mul := continuous_Inf_rng.2 (λ t ht, continuous_Inf_dom₂ ht ht (@has_continuous_mul.continuous_mul M t _ (h t ht))) } @[to_additive] lemma has_continuous_mul_infi {ts : ι' → topological_space M} (h' : Π i, @has_continuous_mul M (ts i) _) : @has_continuous_mul M (⨅ i, ts i) _ := by { rw ← Inf_range, exact has_continuous_mul_Inf (set.forall_range_iff.mpr h') } @[to_additive] lemma has_continuous_mul_inf {t₁ t₂ : topological_space M} (h₁ : @has_continuous_mul M t₁ _) (h₂ : @has_continuous_mul M t₂ _) : @has_continuous_mul M (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine has_continuous_mul_infi (λ b, _), cases b; assumption } end lattice_ops namespace continuous_map variables [has_mul X] [has_continuous_mul X] /-- The continuous map `λ y, y * x` -/ @[to_additive "The continuous map `λ y, y + x"] protected def mul_right (x : X) : C(X, X) := mk _ (continuous_mul_right x) @[simp, to_additive] lemma coe_mul_right (x : X) : ⇑(continuous_map.mul_right x) = λ y, y * x := rfl /-- The continuous map `λ y, x * y` -/ @[to_additive "The continuous map `λ y, x + y"] protected def mul_left (x : X) : C(X, X) := mk _ (continuous_mul_left x) @[simp, to_additive] lemma coe_mul_left (x : X) : ⇑(continuous_map.mul_left x) = λ y, x * y := rfl end continuous_map
2f3321f3f786a3f78885f609f95ecd6910ece5c8
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/category_theory/limits/shapes/biproducts.lean
7bad27816c065dac5d4d0a7c0ddad1ed4369905b
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
11,699
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.epi_mono import category_theory.limits.shapes.binary_products /-! # Biproducts and binary biproducts We introduce the notion of biproducts and binary biproducts. These are slightly unusual relative to the other shapes in the library, as they are simultaneously limits and colimits. (Zero objects are similar; they are "biterminal".) We model these here using a `bicone`, with a cone point `X`, and natural transformations `π` from the constant functor with value `X` to `F` and `ι` in the other direction. We implement `has_bilimit` as a `bicone`, equipped with the evidence `is_limit bicone.to_cone` and `is_colimit bicone.to_cocone`. In practice, of course, we are only interested in the special case of bilimits over `discrete J` for `[fintype J] [decidable_eq J]`, which corresponds to finite biproducts. TODO: We should provide a constructor that takes `has_limit F`, `has_colimit F`, and and iso `limit F ≅ colimit F`, and produces `has_bilimit F`. TODO: perhaps it makes sense to unify the treatment of zero objects with this a bit. TODO: later, in pre-additive categories, we should give the equational characterisation of biproducts. ## Notation As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for a binary biproduct. We introduce `⨁ f` for the indexed biproduct. -/ universes v u open category_theory open category_theory.functor namespace category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] /-- A `c : bicone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. -/ @[nolint has_inhabited_instance] structure bicone {J : Type v} [small_category J] (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) (ι : F ⟶ (const J).obj X) variables {F : J ⥤ C} namespace bicone /-- Extract the cone from a bicone. -/ @[simps] def to_cone (B : bicone F) : cone F := { .. B } /-- Extract the cocone from a bicone. -/ @[simps] def to_cocone (B : bicone F) : cocone F := { .. B } end bicone /-- `has_bilimit F` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `F`. (This is only interesting when the source category is discrete.) -/ class has_bilimit (F : J ⥤ C) := (bicone : bicone F) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) @[priority 100] instance has_limit_of_has_bilimit [has_bilimit F] : has_limit F := { cone := has_bilimit.bicone.to_cone, is_limit := has_bilimit.is_limit, } @[priority 100] instance has_colimit_of_has_bilimit [has_bilimit F] : has_colimit F := { cocone := has_bilimit.bicone.to_cocone, is_colimit := has_bilimit.is_colimit, } variables (J C) /-- `C` has bilimits of shape `J` if we have chosen a particular limit and a particular colimit, with the same cone points, of every functor `F : J ⥤ C`. (This is only interesting if `J` is discrete.) -/ class has_bilimits_of_shape := (has_bilimit : Π F : J ⥤ C, has_bilimit F) attribute [instance, priority 100] has_bilimits_of_shape.has_bilimit @[priority 100] instance [has_bilimits_of_shape J C] : has_limits_of_shape J C := { has_limit := λ F, by apply_instance } @[priority 100] instance [has_bilimits_of_shape J C] : has_colimits_of_shape J C := { has_colimit := λ F, by apply_instance } /-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C` indexed by a finite type with decidable equality. -/ class has_finite_biproducts := (has_bilimits_of_shape : Π (J : Type v) [fintype J] [decidable_eq J], has_bilimits_of_shape.{v} (discrete J) C) attribute [instance] has_finite_biproducts.has_bilimits_of_shape /-- The isomorphism between the specified limit and the specified colimit for a functor with a bilimit. -/ def biproduct_iso {J : Type v} (F : J → C) [has_bilimit (functor.of_function F)] : limits.pi_obj F ≅ limits.sigma_obj F := eq_to_iso rfl end category_theory.limits namespace category_theory.limits variables {J : Type v} variables {C : Type u} [category.{v} C] /-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an abbreviation for `limit (functor.of_function f)`, so for most facts about `biproduct f`, you will just use general facts about limits and colimits.) -/ abbreviation biproduct (f : J → C) [has_bilimit (functor.of_function f)] := limit (functor.of_function f) notation `⨁ ` f:20 := biproduct f /-- The projection onto a summand of a biproduct. -/ abbreviation biproduct.π (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : ⨁ f ⟶ f b := limit.π (functor.of_function f) b /-- The inclusion into a summand of a biproduct. -/ abbreviation biproduct.ι (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : f b ⟶ ⨁ f := colimit.ι (functor.of_function f) b /-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/ abbreviation biproduct.lift {f : J → C} [has_bilimit (functor.of_function f)] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f := limit.lift _ (fan.mk p) /-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/ abbreviation biproduct.desc {f : J → C} [has_bilimit (functor.of_function f)] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P := colimit.desc _ (cofan.mk p) /-- Given a collection of maps between corresponding summands of a pair of biproducts indexed by the same type, we obtain a map betweeen the biproducts. -/ abbreviation biproduct.map [fintype J] [decidable_eq J] {f g : J → C} [has_finite_biproducts.{v} C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := (@lim (discrete J) _ C _ _).map (nat_trans.of_function p) instance biproduct.ι_mono [decidable_eq J] (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : split_mono (biproduct.ι f b) := { retraction := biproduct.desc $ λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b } instance biproduct.π_epi [decidable_eq J] (f : J → C) [has_bilimit (functor.of_function f)] (b : J) : split_epi (biproduct.π f b) := { section_ := biproduct.lift $ λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' } variables {C} /-- A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`, maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`. -/ @[nolint has_inhabited_instance] structure binary_bicone (P Q : C) := (X : C) (π₁ : X ⟶ P) (π₂ : X ⟶ Q) (ι₁ : P ⟶ X) (ι₂ : Q ⟶ X) namespace binary_bicone variables {P Q : C} /-- Extract the cone from a binary bicone. -/ @[simp] def to_cone (c : binary_bicone.{v} P Q) : cone (pair P Q) := binary_fan.mk c.π₁ c.π₂ /-- Extract the cocone from a binary bicone. -/ @[simp] def to_cocone (c : binary_bicone.{v} P Q) : cocone (pair P Q) := binary_cofan.mk c.ι₁ c.ι₂ end binary_bicone /-- `has_binary_biproduct P Q` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`. -/ class has_binary_biproduct (P Q : C) := (bicone : binary_bicone.{v} P Q) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) section variable (C) /-- `has_binary_biproducts C` represents a particular chosen bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`. -/ class has_binary_biproducts := (has_binary_biproduct : Π (P Q : C), has_binary_biproduct.{v} P Q) attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct end variables {P Q : C} instance has_binary_biproduct.has_limit_pair [has_binary_biproduct.{v} P Q] : has_limit (pair P Q) := { cone := has_binary_biproduct.bicone.to_cone, is_limit := has_binary_biproduct.is_limit.{v}, } instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct.{v} P Q] : has_colimit (pair P Q) := { cocone := has_binary_biproduct.bicone.to_cocone, is_colimit := has_binary_biproduct.is_colimit.{v}, } @[priority 100] instance has_limits_of_shape_walking_pair [has_binary_biproducts.{v} C] : has_limits_of_shape.{v} (discrete walking_pair) C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } @[priority 100] instance has_colimits_of_shape_walking_pair [has_binary_biproducts.{v} C] : has_colimits_of_shape.{v} (discrete walking_pair) C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } /-- The isomorphism between the specified binary product and the specified binary coproduct for a pair for a binary biproduct. -/ def biprod_iso (X Y : C) [has_binary_biproduct.{v} X Y] : limits.prod X Y ≅ limits.coprod X Y := eq_to_iso rfl /-- The chosen biproduct of a pair of objects. -/ abbreviation biprod (X Y : C) [has_binary_biproduct.{v} X Y] := limit (pair X Y) notation X ` ⊞ `:20 Y:20 := biprod X Y /-- The projection onto the first summand of a binary biproduct. -/ abbreviation biprod.fst {X Y : C} [has_binary_biproduct.{v} X Y] : X ⊞ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projection onto the second summand of a binary biproduct. -/ abbreviation biprod.snd {X Y : C} [has_binary_biproduct.{v} X Y] : X ⊞ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion into the first summand of a binary biproduct. -/ abbreviation biprod.inl {X Y : C} [has_binary_biproduct.{v} X Y] : X ⟶ X ⊞ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion into the second summand of a binary biproduct. -/ abbreviation biprod.inr {X Y : C} [has_binary_biproduct.{v} X Y] : Y ⟶ X ⊞ Y := colimit.ι (pair X Y) walking_pair.right /-- Given a pair of maps into the summands of a binary biproduct, we obtain a map into the binary biproduct. -/ abbreviation biprod.lift {W X Y : C} [has_binary_biproduct.{v} X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⊞ Y := limit.lift _ (binary_fan.mk f g) /-- Given a pair of maps out of the summands of a binary biproduct, we obtain a map out of the binary biproduct. -/ abbreviation biprod.desc {W X Y : C} [has_binary_biproduct.{v} X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⊞ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) /-- Given a pair of maps between the summands of a pair of binary biproducts, we obtain a map between the binary biproducts. -/ abbreviation biprod.map {W X Y Z : C} [has_binary_biproducts.{v} C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := (@lim (discrete walking_pair) _ C _ _).map (@map_pair _ _ (pair W X) (pair Y Z) f g) instance biprod.inl_mono {X Y : C} [has_binary_biproduct.{v} X Y] : split_mono (biprod.inl : X ⟶ X ⊞ Y) := { retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) } instance biprod.inr_mono {X Y : C} [has_binary_biproduct.{v} X Y] : split_mono (biprod.inr : Y ⟶ X ⊞ Y) := { retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)} instance biprod.fst_epi {X Y : C} [has_binary_biproduct.{v} X Y] : split_epi (biprod.fst : X ⊞ Y ⟶ X) := { section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) } instance biprod.snd_epi {X Y : C} [has_binary_biproduct.{v} X Y] : split_epi (biprod.snd : X ⊞ Y ⟶ Y) := { section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) } -- TODO: -- If someone is interested, they could provide the constructions: -- has_binary_biproducts ↔ has_finite_biproducts end category_theory.limits
ca326e8c5b0e38969e997a852ecea575e437aef8
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/linear_algebra/affine_space.lean
699d9f18a2004cf255544334777f3ab1201eeb3a
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
10,402
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import algebra.add_torsor import linear_algebra.basis noncomputable theory /-! # Affine spaces This file defines affine spaces (over modules) and subspaces, affine maps, and the affine span of a set of points. ## Implementation notes This file is very minimal and many things are surely omitted. Most results can be deduced from corresponding results for modules or vector spaces. The variables `k` and `V` are explicit rather than implicit arguments to lemmas because otherwise the elaborator sometimes has problems inferring appropriate types and type class instances. Definitions of affine spaces vary as to whether a space with no points is permitted; here, we require a nonempty type of points (via the definition of torsors requiring a nonempty type). ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ /-- `affine_space` is an abbreviation for `add_torsor` in the case where the group is a vector space, or more generally a module, but we omit the type classes `[ring k]` and `[module k V]` in the type synonym itself to simplify type class search.. -/ @[nolint unused_arguments] abbreviation affine_space (k : Type*) (V : Type*) (P : Type*) [add_comm_group V] := add_torsor V P namespace affine_space open add_action open add_torsor variables (k : Type*) (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] variables [S : affine_space k V P] include S /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (vsub_set V s) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k V P`, if the set of points is known to be nonempty. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k V s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k V s | hp := ⟨p, hp, 0, submodule.zero _, (zero_vadd V p).symm⟩ /-- The set of points in the affine span of a nonempty set of points is nonempty. -/ lemma span_points_nonempty_of_nonempty {s : set P} : s.nonempty → (span_points k V s).nonempty | ⟨p, hp⟩ := ⟨p, mem_span_points k V p s hp⟩ /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k V s) (hv : v ∈ vector_span k V s) : v +ᵥ p ∈ span_points k V s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k V s).add hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k V s) (hp2 : p2 ∈ span_points k V s) : p1 -ᵥ p2 ∈ vector_span k V s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub V (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k V s, { apply (vector_span k V s).add hv1, rw ←neg_one_smul k v2, exact (vector_span k V s).smul (-1 : k) hv2 }, refine (vector_span k V s).add _ hv1v2, unfold vector_span, change p1a -ᵥ p2a ∈ submodule.span k (vsub_set V s), have hp1p2 : p1a -ᵥ p2a ∈ vsub_set V s, { use [p1a, hp1a, p2a, hp2a] }, have hp1p2s : vsub_set V s ⊆ submodule.span k (vsub_set V s) := submodule.subset_span, apply set.mem_of_mem_of_subset hp1p2 hp1p2s end end affine_space open add_torsor affine_space /-- An `affine_subspace k V P` is a subset of an `affine_space k V P` that has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space k V P] := (carrier : set P) (direction : submodule k V) (nonempty : carrier.nonempty) (add : ∀ (p : P) (v : V), p ∈ carrier → v ∈ direction → v +ᵥ p ∈ carrier) (sub : ∀ (p1 p2 : P), p1 ∈ carrier → p2 ∈ carrier → p1 -ᵥ p2 ∈ direction) namespace affine_subspace variables (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [S : affine_space k V P] include S instance : has_coe (affine_subspace k V P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k V P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k V P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl /-- The whole affine space as a subspace of itself. -/ def univ : affine_subspace k V P := { carrier := set.univ, direction := submodule.span k set.univ, nonempty := set.nonempty_iff_univ_nonempty.1 S.nonempty, add := λ p v hp hv, set.mem_univ _, sub := begin intros p1 p2 hp1 hp2, apply set.mem_bInter, intros x hx, rw set.mem_set_of_eq at hx, exact set.mem_of_mem_of_subset (set.mem_univ _) hx end } /-- `univ`, coerced to a set, is the whole set of points. -/ @[simp] lemma univ_coe : (univ k V P : set P) = set.univ := rfl /-- All points are in `univ`. -/ lemma mem_univ (p : P) : p ∈ univ k V P := set.mem_univ p instance : inhabited (affine_subspace k V P) := ⟨univ k V P⟩ end affine_subspace section affine_span variables (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space k V P] /-- The affine span of a nonempty set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) (h : s.nonempty) : affine_subspace k V P := { carrier := span_points k V s, direction := vector_span k V s, nonempty := span_points_nonempty_of_nonempty k V h, add := λ p v hp hv, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k V hp hv, sub := λ p1 p2 hp1 hp2, vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k V hp1 hp2 } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma affine_span_coe (s : set P) (h : s.nonempty) : (affine_span k V P s h : set P) = span_points k V s := rfl /-- A point in a set is in its affine span. -/ lemma affine_span_mem (p : P) (s : set P) (hp : p ∈ s) : p ∈ affine_span k V P s ⟨p, hp⟩ := mem_span_points k V p s hp end affine_span /-- An `affine_map k V1 P1 V2 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 k V1 P1] [add_comm_group V2] [module k V2] [affine_space k V2 P2] := (to_fun : P1 → P2) (linear : linear_map k V1 V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear.to_fun v +ᵥ to_fun p) namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] [affine_space k V2 P2] [add_comm_group V3] [module k V3] [affine_space k V3 P3] instance: has_coe_to_fun (affine_map k V1 P1 V2 P2) := ⟨_, to_fun⟩ /-- 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 : affine_map k V1 P1 V2 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 : affine_map k V1 P1 V2 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 : affine_map k V1 P1 V2 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. -/ lemma map_vsub (f : affine_map k V1 P1 V2 P2) (p1 p2 : P1) : f p1 -ᵥ f p2 = f.linear (p1 -ᵥ p2) := by conv_lhs { rw [←vsub_vadd V1 p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext (f g : affine_map k V1 P1 V2 P2) (h : (f : P1 → P2) = g) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, change f = g at h, subst g, congr', ext v, cases (add_torsor.nonempty V1 : nonempty P1) with p, apply vadd_right_cancel V2 (f p), erw [← f_add, ← g_add] end variables (k V1 P1) /-- Identity map as an affine map. -/ def id : affine_map k V1 P1 V1 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 V1 P1) = _root_.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k V1 P1 p = p := rfl variables {k V1 P1} instance : inhabited (affine_map k V1 P1 V1 P1) := ⟨id k V1 P1⟩ /-- Composition of affine maps. -/ def comp (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) : affine_map k V1 P1 V3 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 : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) (p : P1) : f.comp g p = f (g p) := rfl end affine_map
59c488b572849b149094f9ff7bb8e388081e3a7b
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/defaul_param3.lean
1db7967f9a6e89d1924973ec476d5b30698e2f9b
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
261
lean
meta constant f (a : nat) (b : nat := 10) : tactic unit meta example : tactic unit := f 10 constant g (a : nat) (b : nat := 10) (c : nat) : nat example : g 0 = g 0 10 := rfl noncomputable example : nat := g 0 1 2 noncomputable example : nat → nat := g 0
aa8831ae8d1a36b70fb52d424fc5d3738385a93a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/theories/analysis/real_limit.lean
b97c1969dcb7f2ae950d3febddf4f63ca6c4dbf3
[ "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
22,416
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 Instantiates the reals as a Banach space. -/ import .metric_space data.real.complete data.set .normed_space open real classical analysis nat noncomputable theory /- sup and inf -/ -- Expresses completeness, sup, and inf in a manner that is less constructive, but more convenient, -- than the way it is done in data.real.complete. -- Issue: real.sup and real.inf conflict with sup and inf in lattice. -- Perhaps put algebra sup and inf into a namespace? namespace real open set private definition exists_is_sup {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) : ∃ y, is_sup X y := let x := some (and.left H), b := some (and.right H) in exists_is_sup_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H)) private definition sup_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) := some (exists_is_sup H) private definition sup_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) : is_sup X (sup_aux H) := some_spec (exists_is_sup H) definition sup (X : set ℝ) : ℝ := if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b) then sup_aux H else 0 proposition le_sup {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : x ≤ sup X := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b), from and.intro (exists.intro x Hx) (exists.intro b Hb), by rewrite [↑sup, dif_pos H]; exact and.left (sup_aux_spec H) x Hx proposition sup_le {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : sup X ≤ b := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b), from and.intro HX (exists.intro b Hb), by rewrite [↑sup, dif_pos H]; exact and.right (sup_aux_spec H) b Hb proposition exists_mem_and_lt_of_lt_sup {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : b < sup X) : ∃ x, x ∈ X ∧ b < x := have ¬ ∀ x, x ∈ X → x ≤ b, from assume H, not_le_of_gt Hb (sup_le HX H), obtain x (Hx : ¬ (x ∈ X → x ≤ b)), from exists_not_of_not_forall this, exists.intro x (have x ∈ X ∧ ¬ x ≤ b, by rewrite [-not_implies_iff_and_not]; apply Hx, and.intro (and.left this) (lt_of_not_ge (and.right this))) private definition exists_is_inf {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) : ∃ y, is_inf X y := let x := some (and.left H), b := some (and.right H) in exists_is_inf_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H)) private definition inf_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) := some (exists_is_inf H) private definition inf_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) : is_inf X (inf_aux H) := some_spec (exists_is_inf H) definition inf (X : set ℝ) : ℝ := if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x) then inf_aux H else 0 proposition inf_le {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : inf X ≤ x := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x), from and.intro (exists.intro x Hx) (exists.intro b Hb), by rewrite [↑inf, dif_pos H]; exact and.left (inf_aux_spec H) x Hx proposition le_inf {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : b ≤ inf X := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x), from and.intro HX (exists.intro b Hb), by rewrite [↑inf, dif_pos H]; exact and.right (inf_aux_spec H) b Hb proposition exists_mem_and_lt_of_inf_lt {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : inf X < b) : ∃ x, x ∈ X ∧ x < b := have ¬ ∀ x, x ∈ X → b ≤ x, from assume H, not_le_of_gt Hb (le_inf HX H), obtain x (Hx : ¬ (x ∈ X → b ≤ x)), from exists_not_of_not_forall this, exists.intro x (have x ∈ X ∧ ¬ b ≤ x, by rewrite [-not_implies_iff_and_not]; apply Hx, and.intro (and.left this) (lt_of_not_ge (and.right this))) section local attribute mem [reducible] -- TODO: is there a better place to put this? proposition image_neg_eq (X : set ℝ) : (λ x, -x) ' X = {x | -x ∈ X} := set.ext (take x, iff.intro (assume H, obtain y [(Hy₁ : y ∈ X) (Hy₂ : -y = x)], from H, show -x ∈ X, by rewrite [-Hy₂, neg_neg]; exact Hy₁) (assume H : -x ∈ X, exists.intro (-x) (and.intro H !neg_neg))) proposition sup_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : sup {x | -x ∈ X} = - inf X := let negX := {x | -x ∈ X} in have nonempty_negX : ∃ x, x ∈ negX, from obtain x Hx, from nonempty_X, have -(-x) ∈ X, by rewrite neg_neg; apply Hx, exists.intro (-x) this, have H₁ : ∀ x, x ∈ negX → x ≤ - inf X, from take x, assume H, have inf X ≤ -x, from inf_le H Hb, show x ≤ - inf X, from le_neg_of_le_neg this, have H₂ : ∀ x, x ∈ X → -sup negX ≤ x, from take x, assume H, have -(-x) ∈ X, by rewrite neg_neg; apply H, have -x ≤ sup negX, from le_sup this H₁, show -sup negX ≤ x, from !neg_le_of_neg_le this, eq_of_le_of_ge (show sup negX ≤ - inf X, from sup_le nonempty_negX H₁) (show -inf X ≤ sup negX, from !neg_le_of_neg_le (le_inf nonempty_X H₂)) proposition inf_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : inf {x | -x ∈ X} = - sup X := let negX := {x | -x ∈ X} in have nonempty_negX : ∃ x, x ∈ negX, from obtain x Hx, from nonempty_X, have -(-x) ∈ X, by rewrite neg_neg; apply Hx, exists.intro (-x) this, have Hb' : ∀ x, x ∈ negX → -b ≤ x, from take x, assume H, !neg_le_of_neg_le (Hb _ H), have HX : X = {x | -x ∈ negX}, from set.ext (take x, by rewrite [↑set_of, ↑mem, +neg_neg]), show inf {x | -x ∈ X} = - sup X, by rewrite [HX at {2}, sup_neg nonempty_negX Hb', neg_neg] end end real /- the reals form a complete metric space -/ namespace analysis theorem dist_eq_abs (x y : real) : dist x y = abs (x - y) := rfl proposition converges_to_seq_real_intro {X : ℕ → ℝ} {y : ℝ} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε) : (X ⟶ y in ℕ) := H proposition converges_to_seq_real_elim {X : ℕ → ℝ} {y : ℝ} (H : X ⟶ y in ℕ) : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε := H proposition converges_to_seq_real_intro' {X : ℕ → ℝ} {y : ℝ} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) ≤ ε) : converges_to_seq X y := converges_to_seq.intro H open pnat subtype local postfix ⁻¹ := pnat.inv private definition pnat.succ (n : ℕ) : ℕ+ := tag (succ n) !succ_pos private definition r_seq_of (X : ℕ → ℝ) : r_seq := λ n, X (elt_of n) private lemma rate_of_cauchy_aux {X : ℕ → ℝ} (H : cauchy X) : ∀ k : ℕ+, ∃ N : ℕ+, ∀ m n : ℕ+, m ≥ N → n ≥ N → abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹ := take k : ℕ+, have H1 : (k⁻¹ >[rat] (rat.of_num 0)), from !pnat.inv_pos, have H2 : (of_rat k⁻¹ > of_rat (rat.of_num 0)), from !of_rat_lt_of_rat_of_lt H1, obtain (N : ℕ) (H : ∀ m n, m ≥ N → n ≥ N → abs (X m - X n) < of_rat k⁻¹), from H _ H2, exists.intro (pnat.succ N) (take m n : ℕ+, assume Hm : m ≥ (pnat.succ N), assume Hn : n ≥ (pnat.succ N), have Hm' : elt_of m ≥ N, begin apply le.trans, apply le_succ, apply Hm end, have Hn' : elt_of n ≥ N, begin apply le.trans, apply le_succ, apply Hn end, show abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹, from le_of_lt (H _ _ Hm' Hn')) private definition rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) (k : ℕ+) : ℕ+ := some (rate_of_cauchy_aux H k) private lemma cauchy_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : cauchy_with_rate (r_seq_of X) (rate_of_cauchy H) := take k : ℕ+, some_spec (rate_of_cauchy_aux H k) private lemma converges_to_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : ∃ l Nb, converges_to_with_rate (r_seq_of X) l Nb := begin apply exists.intro, apply exists.intro, apply converges_to_with_rate_of_cauchy_with_rate, exact cauchy_with_rate_of_cauchy H end theorem converges_seq_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : converges_seq X := obtain l Nb (conv : converges_to_with_rate (r_seq_of X) l Nb), from converges_to_with_rate_of_cauchy H, exists.intro l (take ε : ℝ, suppose ε > 0, obtain (k' : ℕ) (Hn : 1 / succ k' < ε), from archimedean_small `ε > 0`, let k : ℕ+ := tag (succ k') !succ_pos, N : ℕ+ := Nb k in have Hk : real.of_rat k⁻¹ < ε, by rewrite [↑pnat.inv, of_rat_divide]; exact Hn, exists.intro (elt_of N) (take n : ℕ, assume Hn : n ≥ elt_of N, let n' : ℕ+ := tag n (nat.lt_of_lt_of_le (has_property N) Hn) in have abs (X n - l) ≤ real.of_rat k⁻¹, by apply conv k n' Hn, show abs (X n - l) < ε, from lt_of_le_of_lt this Hk)) end analysis attribute [trans_instance] definition complete_metric_space_real : complete_metric_space ℝ := ⦃complete_metric_space, metric_space_real, complete := @analysis.converges_seq_of_cauchy ⦄ /- the real numbers can be viewed as a banach space -/ definition real_vector_space_real : real_vector_space ℝ := ⦃ real_vector_space, real.discrete_linear_ordered_field, smul := mul, smul_left_distrib := left_distrib, smul_right_distrib := right_distrib, mul_smul := mul.assoc, one_smul := one_mul ⦄ attribute [trans_instance] definition banach_space_real : banach_space ℝ := ⦃ banach_space, real_vector_space_real, norm := abs, norm_zero := abs_zero, eq_zero_of_norm_eq_zero := λ a H, eq_zero_of_abs_eq_zero H, norm_triangle := abs_add_le_abs_add_abs, norm_smul := abs_mul, complete := λ X H, analysis.complete ℝ H ⦄ /- limits under pointwise operations -/ section limit_operations variables {X Y : ℕ → ℝ} variables {x y : ℝ} proposition mul_left_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, c * X n) ⟶ c * x in ℕ := smul_converges_to_seq c HX proposition mul_right_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, X n * c) ⟶ x * c in ℕ := have (λ n, X n * c) = (λ n, c * X n), from funext (take x, !mul.comm), by rewrite [this, mul.comm]; apply mul_left_converges_to_seq c HX theorem converges_to_seq_squeeze (HX : X ⟶ x in ℕ) (HY : Y ⟶ x in ℕ) {Z : ℕ → ℝ} (HZX : ∀ n, X n ≤ Z n) (HZY : ∀ n, Z n ≤ Y n) : Z ⟶ x in ℕ := begin intros ε Hε, have Hε4 : ε / 4 > 0, from div_pos_of_pos_of_pos Hε four_pos, cases HX Hε4 with N1 HN1, cases HY Hε4 with N2 HN2, existsi max N1 N2, intro n Hn, have HXY : abs (Y n - X n) < ε / 2, begin apply lt_of_le_of_lt, apply abs_sub_le _ x, have Hε24 : ε / 2 = ε / 4 + ε / 4, from eq.symm !add_quarters, rewrite Hε24, apply add_lt_add, apply HN2, apply ge.trans Hn !le_max_right, rewrite abs_sub, apply HN1, apply ge.trans Hn !le_max_left end, have HZX : abs (Z n - X n) < ε / 2, begin have HZXnp : Z n - X n ≥ 0, from sub_nonneg_of_le !HZX, have HXYnp : Y n - X n ≥ 0, from sub_nonneg_of_le (le.trans !HZX !HZY), rewrite [abs_of_nonneg HZXnp, abs_of_nonneg HXYnp at HXY], note Hgt := lt_add_of_sub_lt_right HXY, have Hlt : Z n < ε / 2 + X n, from calc Z n ≤ Y n : HZY ... < ε / 2 + X n : Hgt, apply sub_lt_right_of_lt_add Hlt end, have H : abs (Z n - x) < ε, begin apply lt_of_le_of_lt, apply abs_sub_le _ (X n), apply lt.trans, apply add_lt_add, apply HZX, apply HN1, apply ge.trans Hn !le_max_left, apply div_two_add_div_four_lt Hε end, exact H end proposition converges_to_seq_of_abs_sub_converges_to_seq (Habs : (λ n, abs (X n - x)) ⟶ 0 in ℕ) : X ⟶ x in ℕ := begin intros ε Hε, cases Habs Hε with N HN, existsi N, intro n Hn, have Hn' : abs (abs (X n - x) - 0) < ε, from HN Hn, rewrite [sub_zero at Hn', abs_abs at Hn'], exact Hn' end proposition abs_sub_converges_to_seq_of_converges_to_seq (HX : X ⟶ x in ℕ) : (λ n, abs (X n - x)) ⟶ 0 in ℕ := begin intros ε Hε, cases HX Hε with N HN, existsi N, intro n Hn, have Hn' : abs (abs (X n - x) - 0) < ε, by rewrite [sub_zero, abs_abs]; apply HN Hn, exact Hn' end proposition mul_converges_to_seq (HX : X ⟶ x in ℕ) (HY : Y ⟶ y in ℕ) : (λ n, X n * Y n) ⟶ x * y in ℕ := have Hbd : ∃ K : ℝ, ∀ n : ℕ, abs (X n) ≤ K, begin cases bounded_of_converges_seq HX with K HK, existsi K + abs x, intro n, note Habs := le.trans (abs_abs_sub_abs_le_abs_sub (X n) x) !HK, apply le_add_of_sub_right_le, apply le.trans, apply le_abs_self, assumption end, obtain K HK, from Hbd, have Habsle : ∀ n, abs (X n * Y n - x * y) ≤ K * abs (Y n - y) + abs y * abs (X n - x), begin intro, have Heq : X n * Y n - x * y = (X n * Y n - X n * y) + (X n * y - x * y), by rewrite [-sub_add_cancel (X n * Y n) (X n * y) at {1}, sub_eq_add_neg, *add.assoc], apply le.trans, rewrite Heq, apply abs_add_le_abs_add_abs, apply add_le_add, rewrite [-mul_sub_left_distrib, abs_mul], apply mul_le_mul_of_nonneg_right, apply HK, apply abs_nonneg, rewrite [-mul_sub_right_distrib, abs_mul, mul.comm], apply le.refl end, have Hdifflim : (λ n, abs (X n * Y n - x * y)) ⟶ 0 in ℕ, begin apply converges_to_seq_squeeze, rotate 2, intro, apply abs_nonneg, apply Habsle, apply converges_to_seq_constant, rewrite -{0}zero_add, apply add_converges_to_seq, krewrite -(mul_zero K), apply mul_left_converges_to_seq, apply abs_sub_converges_to_seq_of_converges_to_seq, exact HY, krewrite -(mul_zero (abs y)), apply mul_left_converges_to_seq, apply abs_sub_converges_to_seq_of_converges_to_seq, exact HX end, converges_to_seq_of_abs_sub_converges_to_seq Hdifflim -- TODO: converges_to_seq_div, converges_to_seq_mul_left_iff, etc. proposition abs_converges_to_seq_zero (HX : X ⟶ 0 in ℕ) : (λ n, abs (X n)) ⟶ 0 in ℕ := norm_converges_to_seq_zero HX proposition converges_to_seq_zero_of_abs_converges_to_seq_zero (HX : (λ n, abs (X n)) ⟶ 0 in ℕ) : X ⟶ 0 in ℕ := converges_to_seq_zero_of_norm_converges_to_seq_zero HX proposition abs_converges_to_seq_zero_iff (X : ℕ → ℝ) : ((λ n, abs (X n)) ⟶ 0 in ℕ) ↔ (X ⟶ 0 in ℕ) := iff.intro converges_to_seq_zero_of_abs_converges_to_seq_zero abs_converges_to_seq_zero -- TODO: products of two sequences, converges_seq, limit_seq end limit_operations /- properties of converges_to_at -/ section limit_operations_continuous variables {f g : ℝ → ℝ} variables {a b x y : ℝ} theorem mul_converges_to_at (Hf : f ⟶ a at x) (Hg : g ⟶ b at x) : (λ z, f z * g z) ⟶ a * b at x := begin apply converges_to_at_of_all_conv_seqs, intro X HX, apply mul_converges_to_seq, note Hfc := all_conv_seqs_of_converges_to_at Hf, apply Hfc _ HX, note Hgb := all_conv_seqs_of_converges_to_at Hg, apply Hgb _ HX end end limit_operations_continuous /- monotone sequences -/ section monotone_sequences open real set variable {X : ℕ → ℝ} proposition converges_to_seq_sup_of_nondecreasing (nondecX : nondecreasing X) {b : ℝ} (Hb : ∀ i, X i ≤ b) : X ⟶ sup (X ' univ) in ℕ := let sX := sup (X ' univ) in have Xle : ∀ i, X i ≤ sX, from take i, have ∀ x, x ∈ X ' univ → x ≤ b, from (take x, assume H, obtain i [H' (Hi : X i = x)], from H, by rewrite -Hi; exact Hb i), show X i ≤ sX, from le_sup (mem_image_of_mem X !mem_univ) this, have exX : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ), take ε, assume epos : ε > 0, have sX - ε < sX, from !sub_lt_of_pos epos, obtain x' [(H₁x' : x' ∈ X ' univ) (H₂x' : sX - ε < x')], from exists_mem_and_lt_of_lt_sup exX this, obtain i [H' (Hi : X i = x')], from H₁x', have Hi' : ∀ j, j ≥ i → sX - ε < X j, from take j, assume Hj, lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj), exists.intro i (take j, assume Hj : j ≥ i, have X j - sX ≤ 0, from sub_nonpos_of_le (Xle j), have eq₁ : abs (X j - sX) = sX - X j, by rewrite [abs_of_nonpos this, neg_sub], have sX - ε < X j, from lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj), have sX < X j + ε, from lt_add_of_sub_lt_right this, have sX - X j < ε, from sub_lt_left_of_lt_add this, show (abs (X j - sX)) < ε, by rewrite eq₁; exact this) proposition converges_to_seq_inf_of_nonincreasing (nonincX : nonincreasing X) {b : ℝ} (Hb : ∀ i, b ≤ X i) : X ⟶ inf (X ' univ) in ℕ := have H₁ : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ), have H₂ : ∀ x, x ∈ X ' univ → b ≤ x, from (take x, assume H, obtain i [Hi₁ (Hi₂ : X i = x)], from H, show b ≤ x, by rewrite -Hi₂; apply Hb i), have H₃ : {x : ℝ | -x ∈ X ' univ} = {x : ℝ | x ∈ (λ n, -X n) ' univ}, from calc {x : ℝ | -x ∈ X ' univ} = (λ y, -y) ' (X ' univ) : by rewrite image_neg_eq ... = {x : ℝ | x ∈ (λ n, -X n) ' univ} : image_comp, have H₄ : ∀ i, - X i ≤ - b, from take i, neg_le_neg (Hb i), begin -- need krewrite here krewrite [-neg_converges_to_seq_iff, -sup_neg H₁ H₂, H₃, -nondecreasing_neg_iff at nonincX], apply converges_to_seq_sup_of_nondecreasing nonincX H₄ end end monotone_sequences /- x^n converges to 0 if abs x < 1 -/ section xn open nat set theorem pow_converges_to_seq_zero {x : ℝ} (H : abs x < 1) : (λ n, x^n) ⟶ 0 in ℕ := suffices H' : (λ n, (abs x)^n) ⟶ 0 in ℕ, from have (λ n, (abs x)^n) = (λ n, abs (x^n)), from funext (take n, eq.symm !abs_pow), by rewrite this at H'; exact converges_to_seq_zero_of_abs_converges_to_seq_zero H', let aX := (λ n, (abs x)^n), iaX := real.inf (aX ' univ), asX := (λ n, (abs x)^(succ n)) in have noninc_aX : nonincreasing aX, from nonincreasing_of_forall_ge_succ (take i, have (abs x) * (abs x)^i ≤ 1 * (abs x)^i, from mul_le_mul_of_nonneg_right (le_of_lt H) (!pow_nonneg_of_nonneg !abs_nonneg), have (abs x) * (abs x)^i ≤ (abs x)^i, by krewrite one_mul at this; exact this, show (abs x) ^ (succ i) ≤ (abs x)^i, by rewrite pow_succ; apply this), have bdd_aX : ∀ i, 0 ≤ aX i, from take i, !pow_nonneg_of_nonneg !abs_nonneg, have aXconv : aX ⟶ iaX in ℕ, proof converges_to_seq_inf_of_nonincreasing noninc_aX bdd_aX qed, have asXconv : asX ⟶ iaX in ℕ, from converges_to_seq_offset_succ aXconv, have asXconv' : asX ⟶ (abs x) * iaX in ℕ, from mul_left_converges_to_seq (abs x) aXconv, have iaX = (abs x) * iaX, from converges_to_seq_unique asXconv asXconv', have iaX = 0, from eq_zero_of_mul_eq_self_left (ne_of_lt H) (eq.symm this), show aX ⟶ 0 in ℕ, begin rewrite -this, exact aXconv end --from this ▸ aXconv end xn /- continuity on the reals -/ section continuous theorem continuous_real_elim {f : ℝ → ℝ} (H : continuous f) : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ, abs (x' - x) < δ → abs (f x' - f x) < ε := take x, continuous_at_elim (H x) theorem continuous_real_intro {f : ℝ → ℝ} (H : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ, abs (x' - x) < δ → abs (f x' - f x) < ε) : continuous f := take x, continuous_at_intro (H x) theorem pos_on_nbhd_of_cts_of_pos {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b > 0) : ∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y > 0 := begin let Hcont := continuous_real_elim Hf b Hb, cases Hcont with δ Hδ, existsi δ, split, exact and.left Hδ, intro y Hy, let Hy' := and.right Hδ y Hy, note Hlt := sub_lt_of_abs_sub_lt_left Hy', rewrite sub_self at Hlt, assumption end theorem neg_on_nbhd_of_cts_of_neg {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b < 0) : ∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y < 0 := begin let Hcont := continuous_real_elim Hf b (neg_pos_of_neg Hb), cases Hcont with δ Hδ, existsi δ, split, exact and.left Hδ, intro y Hy, let Hy' := and.right Hδ y Hy, let Hlt := sub_lt_of_abs_sub_lt_right Hy', note Hlt' := lt_add_of_sub_lt_left Hlt, rewrite [add.comm at Hlt', -sub_eq_add_neg at Hlt', sub_self at Hlt'], assumption end theorem continuous_neg_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) : continuous (λ x, - f x) := begin apply continuous_real_intro, intros x ε Hε, cases continuous_real_elim Hcon x Hε with δ Hδ, cases Hδ with Hδ₁ Hδ₂, existsi δ, split, assumption, intros x' Hx', let HD := Hδ₂ x' Hx', rewrite [-abs_neg, neg_neg_sub_neg], exact HD end theorem continuous_offset_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) (a : ℝ) : continuous (λ x, (f x) + a) := begin apply continuous_real_intro, intros x ε Hε, cases continuous_real_elim Hcon x Hε with δ Hδ, cases Hδ with Hδ₁ Hδ₂, existsi δ, split, assumption, intros x' Hx', rewrite [add_sub_comm, sub_self, add_zero], apply Hδ₂, assumption end theorem continuous_mul_of_continuous {f g : ℝ → ℝ} (Hconf : continuous f) (Hcong : continuous g) : continuous (λ x, f x * g x) := begin intro x, apply continuous_at_of_converges_to_at, apply mul_converges_to_at, all_goals apply converges_to_at_of_continuous_at, apply Hconf, apply Hcong end end continuous
8ce56ac57ab610dd64acd9660aacbdabbb4a8fc8
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/integral/riesz_markov_kakutani.lean
aeff61a56f4f42b412eaaa937c41595579b5a661
[ "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
5,014
lean
/- Copyright (c) 2022 Jesse Reimann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Reimann, Kalle Kytölä -/ import topology.continuous_function.bounded import topology.sets.compacts /-! # Riesz–Markov–Kakutani representation theorem This file will prove different versions of the Riesz-Markov-Kakutani representation theorem. The theorem is first proven for compact spaces, from which the statements about linear functionals on bounded continuous functions or compactly supported functions on locally compact spaces follow. To make use of the existing API, the measure is constructed from a content `λ` on the compact subsets of the space X, rather than the usual construction of open sets in the literature. ## References * [Walter Rudin, Real and Complex Analysis.][Rud87] -/ noncomputable theory open_locale bounded_continuous_function nnreal ennreal open set function topological_space variables {X : Type*} [topological_space X] variables (Λ : (X →ᵇ ℝ≥0) →ₗ[ℝ≥0] ℝ≥0) /-! ### Construction of the content: -/ /-- Given a positive linear functional Λ on X, for `K ⊆ X` compact define `λ(K) = inf {Λf | 1≤f on K}`. When X is a compact Hausdorff space, this will be shown to be a content, and will be shown to agree with the Riesz measure on the compact subsets `K ⊆ X`. -/ def riesz_content_aux : (compacts X) → ℝ≥0 := λ K, Inf (Λ '' {f : X →ᵇ ℝ≥0 | ∀ x ∈ K, (1 : ℝ≥0) ≤ f x}) section riesz_monotone /-- For any compact subset `K ⊆ X`, there exist some bounded continuous nonnegative functions f on X such that `f ≥ 1` on K. -/ lemma riesz_content_aux_image_nonempty (K : compacts X) : (Λ '' {f : X →ᵇ ℝ≥0 | ∀ x ∈ K, (1 : ℝ≥0) ≤ f x}).nonempty := begin rw nonempty_image_iff, use (1 : X →ᵇ ℝ≥0), intros x x_in_K, simp only [bounded_continuous_function.coe_one, pi.one_apply], end /-- Riesz content λ (associated with a positive linear functional Λ) is monotone: if `K₁ ⊆ K₂` are compact subsets in X, then `λ(K₁) ≤ λ(K₂)`. -/ lemma riesz_content_aux_mono {K₁ K₂ : compacts X} (h : K₁ ≤ K₂) : riesz_content_aux Λ K₁ ≤ riesz_content_aux Λ K₂ := cInf_le_cInf (order_bot.bdd_below _) (riesz_content_aux_image_nonempty Λ K₂) (image_subset Λ (set_of_subset_set_of.mpr (λ f f_hyp x x_in_K₁, f_hyp x (h x_in_K₁)))) end riesz_monotone section riesz_subadditive /-- Any bounded continuous nonnegative f such that `f ≥ 1` on K gives an upper bound on the content of K; namely `λ(K) ≤ Λ f`. -/ lemma riesz_content_aux_le {K : compacts X} {f : X →ᵇ ℝ≥0} (h : ∀ x ∈ K, (1 : ℝ≥0) ≤ f x) : riesz_content_aux Λ K ≤ Λ f := cInf_le (order_bot.bdd_below _) ⟨f, ⟨h, rfl⟩⟩ /-- The Riesz content can be approximated arbitrarily well by evaluating the positive linear functional on test functions: for any `ε > 0`, there exists a bounded continuous nonnegative function f on X such that `f ≥ 1` on K and such that `λ(K) ≤ Λ f < λ(K) + ε`. -/ lemma exists_lt_riesz_content_aux_add_pos (K : compacts X) {ε : ℝ≥0} (εpos : 0 < ε) : ∃ (f : X →ᵇ ℝ≥0), (∀ x ∈ K, (1 : ℝ≥0) ≤ f x) ∧ Λ f < riesz_content_aux Λ K + ε := begin --choose a test function `f` s.t. `Λf = α < λ(K) + ε` obtain ⟨α, ⟨⟨f, f_hyp⟩, α_hyp⟩⟩ := exists_lt_of_cInf_lt (riesz_content_aux_image_nonempty Λ K) (lt_add_of_pos_right (riesz_content_aux Λ K) εpos), refine ⟨f, f_hyp.left, _ ⟩, rw f_hyp.right, exact α_hyp, end /-- The Riesz content λ associated to a given positive linear functional Λ is finitely subadditive: `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)` for any compact subsets `K₁, K₂ ⊆ X`. -/ lemma riesz_content_aux_sup_le (K1 K2 : compacts X) : riesz_content_aux Λ (K1 ⊔ K2) ≤ riesz_content_aux Λ (K1) + riesz_content_aux Λ (K2) := begin apply nnreal.le_of_forall_pos_le_add, intros ε εpos, --get test functions s.t. `λ(Ki) ≤ Λfi ≤ λ(Ki) + ε/2, i=1,2` obtain ⟨f1, f_test_function_K1⟩ := exists_lt_riesz_content_aux_add_pos Λ K1 (half_pos εpos), obtain ⟨f2, f_test_function_K2⟩ := exists_lt_riesz_content_aux_add_pos Λ K2 (half_pos εpos), --let `f := f1 + f2` test function for the content of `K` have f_test_function_union : (∀ x ∈ (K1 ⊔ K2), (1 : ℝ≥0) ≤ (f1 + f2) x), { rintros x (x_in_K1 | x_in_K2), { exact le_add_right (f_test_function_K1.left x x_in_K1) }, { exact le_add_left (f_test_function_K2.left x x_in_K2) }}, --use that `Λf` is an upper bound for `λ(K1⊔K2)` apply (riesz_content_aux_le Λ f_test_function_union).trans (le_of_lt _), rw map_add, --use that `Λfi` are lower bounds for `λ(Ki) + ε/2` apply lt_of_lt_of_le (add_lt_add f_test_function_K1.right f_test_function_K2.right) (le_of_eq _), rw [add_assoc, add_comm (ε/2), add_assoc, add_halves ε, add_assoc], end end riesz_subadditive